You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@tomcat.apache.org by ma...@apache.org on 2023/01/24 11:02:26 UTC
[tomcat] 02/07: Code cleanup (format). No functional change.
This is an automated email from the ASF dual-hosted git repository.
markt pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 045743367b1911066a3b244446f9abfb06f5baee
Author: Mark Thomas <ma...@apache.org>
AuthorDate: Tue Jan 24 09:55:53 2023 +0000
Code cleanup (format). No functional change.
---
.../catalina/filters/AddDefaultCharsetFilter.java | 34 +-
java/org/apache/catalina/filters/Constants.java | 37 +-
java/org/apache/catalina/filters/CorsFilter.java | 542 +++++++++------------
.../catalina/filters/CsrfPreventionFilter.java | 121 ++---
.../catalina/filters/CsrfPreventionFilterBase.java | 25 +-
.../org/apache/catalina/filters/ExpiresFilter.java | 428 +++++++---------
.../catalina/filters/FailedRequestFilter.java | 25 +-
java/org/apache/catalina/filters/FilterBase.java | 30 +-
.../catalina/filters/HttpHeaderSecurityFilter.java | 15 +-
.../apache/catalina/filters/RemoteAddrFilter.java | 17 +-
.../apache/catalina/filters/RemoteCIDRFilter.java | 27 +-
.../apache/catalina/filters/RemoteHostFilter.java | 16 +-
.../apache/catalina/filters/RemoteIpFilter.java | 262 +++++-----
.../catalina/filters/RequestDumperFilter.java | 69 ++-
.../org/apache/catalina/filters/RequestFilter.java | 91 ++--
.../catalina/filters/RestCsrfPreventionFilter.java | 74 ++-
.../catalina/filters/SessionInitializerFilter.java | 23 +-
.../filters/SetCharacterEncodingFilter.java | 88 ++--
.../apache/catalina/filters/WebdavFixFilter.java | 58 +--
19 files changed, 833 insertions(+), 1149 deletions(-)
diff --git a/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java b/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
index 7270be8f09..3c84bebd77 100644
--- a/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
+++ b/java/org/apache/catalina/filters/AddDefaultCharsetFilter.java
@@ -32,17 +32,13 @@ import org.apache.juli.logging.LogFactory;
/**
- * Filter that explicitly sets the default character set for media subtypes of
- * the "text" type to ISO-8859-1, or another user defined character set. RFC2616
- * explicitly states that browsers must use ISO-8859-1 if no character set is
- * defined for media with subtype "text". However, browsers may attempt to
- * auto-detect the character set. This may be exploited by an attacker to
- * perform an XSS attack. Internet Explorer has this behaviour by default. Other
- * browsers have an option to enable it.<br>
- *
- * This filter prevents the attack by explicitly setting a character set. Unless
- * the provided character set is explicitly overridden by the user - in which
- * case they deserve everything they get - the browser will adhere to an
+ * Filter that explicitly sets the default character set for media subtypes of the "text" type to ISO-8859-1, or another
+ * user defined character set. RFC2616 explicitly states that browsers must use ISO-8859-1 if no character set is
+ * defined for media with subtype "text". However, browsers may attempt to auto-detect the character set. This may be
+ * exploited by an attacker to perform an XSS attack. Internet Explorer has this behaviour by default. Other browsers
+ * have an option to enable it.<br>
+ * This filter prevents the attack by explicitly setting a character set. Unless the provided character set is
+ * explicitly overridden by the user - in which case they deserve everything they get - the browser will adhere to an
* explicitly set character set, thus preventing the XSS attack.
*/
public class AddDefaultCharsetFilter extends FilterBase {
@@ -67,25 +63,22 @@ public class AddDefaultCharsetFilter extends FilterBase {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
- if (encoding == null || encoding.length() == 0 ||
- encoding.equalsIgnoreCase("default")) {
+ if (encoding == null || encoding.length() == 0 || encoding.equalsIgnoreCase("default")) {
encoding = DEFAULT_ENCODING;
} else if (encoding.equalsIgnoreCase("system")) {
encoding = Charset.defaultCharset().name();
} else if (!Charset.isSupported(encoding)) {
- throw new IllegalArgumentException(sm.getString(
- "addDefaultCharset.unsupportedCharset", encoding));
+ throw new IllegalArgumentException(sm.getString("addDefaultCharset.unsupportedCharset", encoding));
}
}
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
// Wrap the response
if (response instanceof HttpServletResponse) {
- ResponseWrapper wrapped =
- new ResponseWrapper((HttpServletResponse)response, encoding);
+ ResponseWrapper wrapped = new ResponseWrapper((HttpServletResponse) response, encoding);
chain.doFilter(request, wrapped);
} else {
chain.doFilter(request, response);
@@ -93,8 +86,7 @@ public class AddDefaultCharsetFilter extends FilterBase {
}
/**
- * Wrapper that adds a character set for text media types if no character
- * set is specified.
+ * Wrapper that adds a character set for text media types if no character set is specified.
*/
public static class ResponseWrapper extends HttpServletResponseWrapper {
diff --git a/java/org/apache/catalina/filters/Constants.java b/java/org/apache/catalina/filters/Constants.java
index ab550b1419..25693aef56 100644
--- a/java/org/apache/catalina/filters/Constants.java
+++ b/java/org/apache/catalina/filters/Constants.java
@@ -20,38 +20,29 @@ package org.apache.catalina.filters;
/**
* Manifest constants for this Java package.
*
- *
* @author Craig R. McClanahan
*/
public final class Constants {
/**
- * The session attribute key under which the CSRF nonce
- * cache will be stored.
+ * The session attribute key under which the CSRF nonce cache will be stored.
*/
- public static final String CSRF_NONCE_SESSION_ATTR_NAME =
- "org.apache.catalina.filters.CSRF_NONCE";
+ public static final String CSRF_NONCE_SESSION_ATTR_NAME = "org.apache.catalina.filters.CSRF_NONCE";
/**
- * The request attribute key under which the current
- * requests's CSRF nonce can be found.
+ * The request attribute key under which the current requests's CSRF nonce can be found.
*/
- public static final String CSRF_NONCE_REQUEST_ATTR_NAME =
- "org.apache.catalina.filters.CSRF_REQUEST_NONCE";
+ public static final String CSRF_NONCE_REQUEST_ATTR_NAME = "org.apache.catalina.filters.CSRF_REQUEST_NONCE";
/**
- * The name of the request parameter which carries CSRF nonces
- * from the client to the server for validation.
+ * The name of the request parameter which carries CSRF nonces from the client to the server for validation.
*/
- public static final String CSRF_NONCE_REQUEST_PARAM =
- "org.apache.catalina.filters.CSRF_NONCE";
+ public static final String CSRF_NONCE_REQUEST_PARAM = "org.apache.catalina.filters.CSRF_NONCE";
/**
- * The servlet context attribute key under which the
- * CSRF request parameter name can be found.
+ * The servlet context attribute key under which the CSRF request parameter name can be found.
*/
- public static final String CSRF_NONCE_REQUEST_PARAM_NAME_KEY =
- "org.apache.catalina.filters.CSRF_NONCE_PARAM_NAME";
+ public static final String CSRF_NONCE_REQUEST_PARAM_NAME_KEY = "org.apache.catalina.filters.CSRF_NONCE_PARAM_NAME";
public static final String METHOD_GET = "GET";
@@ -62,16 +53,12 @@ public final class Constants {
public static final String CSRF_REST_NONCE_HEADER_REQUIRED_VALUE = "Required";
/**
- * The session attribute key under which the CSRF REST nonce
- * cache will be stored.
+ * The session attribute key under which the CSRF REST nonce cache will be stored.
*/
- public static final String CSRF_REST_NONCE_SESSION_ATTR_NAME =
- "org.apache.catalina.filters.CSRF_REST_NONCE";
+ public static final String CSRF_REST_NONCE_SESSION_ATTR_NAME = "org.apache.catalina.filters.CSRF_REST_NONCE";
/**
- * The servlet context attribute key under which the
- * CSRF REST header name can be found.
+ * The servlet context attribute key under which the CSRF REST header name can be found.
*/
- public static final String CSRF_REST_NONCE_HEADER_NAME_KEY =
- "org.apache.catalina.filters.CSRF_REST_NONCE_HEADER_NAME";
+ public static final String CSRF_REST_NONCE_HEADER_NAME_KEY = "org.apache.catalina.filters.CSRF_REST_NONCE_HEADER_NAME";
}
diff --git a/java/org/apache/catalina/filters/CorsFilter.java b/java/org/apache/catalina/filters/CorsFilter.java
index 0b76b1e83d..74314ba6b8 100644
--- a/java/org/apache/catalina/filters/CorsFilter.java
+++ b/java/org/apache/catalina/filters/CorsFilter.java
@@ -43,25 +43,19 @@ import org.apache.tomcat.util.res.StringManager;
/**
* <p>
- * A {@link jakarta.servlet.Filter} that enable client-side cross-origin requests
- * by implementing W3C's CORS (<b>C</b>ross-<b>O</b>rigin <b>R</b>esource
- * <b>S</b>haring) specification for resources. Each {@link HttpServletRequest}
- * request is inspected as per specification, and appropriate response headers
- * are added to {@link HttpServletResponse}.
+ * A {@link jakarta.servlet.Filter} that enable client-side cross-origin requests by implementing W3C's CORS
+ * (<b>C</b>ross-<b>O</b>rigin <b>R</b>esource <b>S</b>haring) specification for resources. Each
+ * {@link HttpServletRequest} request is inspected as per specification, and appropriate response headers are added to
+ * {@link HttpServletResponse}.
* </p>
- *
* <p>
- * By default, it also sets following request attributes, that help to
- * determine the nature of the request downstream.
+ * By default, it also sets following request attributes, that help to determine the nature of the request downstream.
* </p>
* <ul>
- * <li><b>cors.isCorsRequest:</b> Flag to determine if the request is a CORS
- * request. Set to <code>true</code> if a CORS request; <code>false</code>
- * otherwise.</li>
- * <li><b>cors.request.origin:</b> The Origin URL, i.e. the URL of the page from
- * where the request is originated.</li>
- * <li>
- * <b>cors.request.type:</b> Type of request. Possible values:
+ * <li><b>cors.isCorsRequest:</b> Flag to determine if the request is a CORS request. Set to <code>true</code> if a CORS
+ * request; <code>false</code> otherwise.</li>
+ * <li><b>cors.request.origin:</b> The Origin URL, i.e. the URL of the page from where the request is originated.</li>
+ * <li><b>cors.request.type:</b> Type of request. Possible values:
* <ul>
* <li>SIMPLE: A request which is not preceded by a pre-flight request.</li>
* <li>ACTUAL: A request which is preceded by a pre-flight request.</li>
@@ -70,15 +64,12 @@ import org.apache.tomcat.util.res.StringManager;
* <li>INVALID_CORS: A cross-origin request which is invalid.</li>
* </ul>
* </li>
- * <li><b>cors.request.headers:</b> Request headers sent as
- * 'Access-Control-Request-Headers' header, for pre-flight request.</li>
+ * <li><b>cors.request.headers:</b> Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight
+ * request.</li>
* </ul>
- *
- * If you extend this class and override one or more of the getXxx() methods,
- * consider whether you also need to override
- * {@link CorsFilter#doFilter(ServletRequest, ServletResponse, FilterChain)} and
- * add appropriate locking so that the {@code doFilter()} method executes with a
- * consistent configuration.
+ * If you extend this class and override one or more of the getXxx() methods, consider whether you also need to override
+ * {@link CorsFilter#doFilter(ServletRequest, ServletResponse, FilterChain)} and add appropriate locking so that the
+ * {@code doFilter()} method executes with a consistent configuration.
*
* @see <a href="http://www.w3.org/TR/cors/">CORS specification</a>
*/
@@ -91,8 +82,7 @@ public class CorsFilter extends GenericFilter {
/**
- * A {@link Collection} of origins consisting of zero or more origins that
- * are allowed access to the resource.
+ * A {@link Collection} of origins consisting of zero or more origins that are allowed access to the resource.
*/
private final Collection<String> allowedOrigins = new HashSet<>();
@@ -102,34 +92,29 @@ public class CorsFilter extends GenericFilter {
private boolean anyOriginAllowed;
/**
- * A {@link Collection} of methods consisting of zero or more methods that
- * are supported by the resource.
+ * A {@link Collection} of methods consisting of zero or more methods that are supported by the resource.
*/
private final Collection<String> allowedHttpMethods = new HashSet<>();
/**
- * A {@link Collection} of headers consisting of zero or more header field
- * names that are supported by the resource.
+ * A {@link Collection} of headers consisting of zero or more header field names that are supported by the resource.
*/
private final Collection<String> allowedHttpHeaders = new HashSet<>();
/**
- * A {@link Collection} of exposed headers consisting of zero or more header
- * field names of headers other than the simple response headers that the
- * resource might use and can be exposed.
+ * A {@link Collection} of exposed headers consisting of zero or more header field names of headers other than the
+ * simple response headers that the resource might use and can be exposed.
*/
private final Collection<String> exposedHeaders = new HashSet<>();
/**
- * A supports credentials flag that indicates whether the resource supports
- * user credentials in the request. It is true when the resource does and
- * false otherwise.
+ * A supports credentials flag that indicates whether the resource supports user credentials in the request. It is
+ * true when the resource does and false otherwise.
*/
private boolean supportsCredentials;
/**
- * Indicates (in seconds) how long the results of a pre-flight request can
- * be cached in a pre-flight result cache.
+ * Indicates (in seconds) how long the results of a pre-flight request can be cached in a pre-flight result cache.
*/
private long preflightMaxAge;
@@ -140,11 +125,9 @@ public class CorsFilter extends GenericFilter {
@Override
- public void doFilter(final ServletRequest servletRequest,
- final ServletResponse servletResponse, final FilterChain filterChain)
- throws IOException, ServletException {
- if (!(servletRequest instanceof HttpServletRequest) ||
- !(servletResponse instanceof HttpServletResponse)) {
+ public void doFilter(final ServletRequest servletRequest, final ServletResponse servletResponse,
+ final FilterChain filterChain) throws IOException, ServletException {
+ if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)) {
throw new ServletException(sm.getString("corsFilter.onlyHttp"));
}
@@ -160,53 +143,47 @@ public class CorsFilter extends GenericFilter {
CorsFilter.decorateCORSProperties(request, requestType);
}
switch (requestType) {
- case SIMPLE:
- // Handles a Simple CORS request.
- case ACTUAL:
- // Handles an Actual CORS request.
- this.handleSimpleCORS(request, response, filterChain);
- break;
- case PRE_FLIGHT:
- // Handles a Pre-flight CORS request.
- this.handlePreflightCORS(request, response, filterChain);
- break;
- case NOT_CORS:
- // Handles a Normal request that is not a cross-origin request.
- this.handleNonCORS(request, response, filterChain);
- break;
- default:
- // Handles a CORS request that violates specification.
- this.handleInvalidCORS(request, response, filterChain);
- break;
+ case SIMPLE:
+ // Handles a Simple CORS request.
+ case ACTUAL:
+ // Handles an Actual CORS request.
+ this.handleSimpleCORS(request, response, filterChain);
+ break;
+ case PRE_FLIGHT:
+ // Handles a Pre-flight CORS request.
+ this.handlePreflightCORS(request, response, filterChain);
+ break;
+ case NOT_CORS:
+ // Handles a Normal request that is not a cross-origin request.
+ this.handleNonCORS(request, response, filterChain);
+ break;
+ default:
+ // Handles a CORS request that violates specification.
+ this.handleInvalidCORS(request, response, filterChain);
+ break;
}
}
@Override
public void init() throws ServletException {
- parseAndStore(
- getInitParameter(PARAM_CORS_ALLOWED_ORIGINS, DEFAULT_ALLOWED_ORIGINS),
- getInitParameter(PARAM_CORS_ALLOWED_METHODS, DEFAULT_ALLOWED_HTTP_METHODS),
- getInitParameter(PARAM_CORS_ALLOWED_HEADERS, DEFAULT_ALLOWED_HTTP_HEADERS),
- getInitParameter(PARAM_CORS_EXPOSED_HEADERS, DEFAULT_EXPOSED_HEADERS),
+ parseAndStore(getInitParameter(PARAM_CORS_ALLOWED_ORIGINS, DEFAULT_ALLOWED_ORIGINS),
+ getInitParameter(PARAM_CORS_ALLOWED_METHODS, DEFAULT_ALLOWED_HTTP_METHODS),
+ getInitParameter(PARAM_CORS_ALLOWED_HEADERS, DEFAULT_ALLOWED_HTTP_HEADERS),
+ getInitParameter(PARAM_CORS_EXPOSED_HEADERS, DEFAULT_EXPOSED_HEADERS),
getInitParameter(PARAM_CORS_SUPPORT_CREDENTIALS, DEFAULT_SUPPORTS_CREDENTIALS),
- getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE, DEFAULT_PREFLIGHT_MAXAGE),
- getInitParameter(PARAM_CORS_REQUEST_DECORATE, DEFAULT_DECORATE_REQUEST)
- );
+ getInitParameter(PARAM_CORS_PREFLIGHT_MAXAGE, DEFAULT_PREFLIGHT_MAXAGE),
+ getInitParameter(PARAM_CORS_REQUEST_DECORATE, DEFAULT_DECORATE_REQUEST));
}
/**
- * This method returns the parameter's value if it exists, or defaultValue
- * if not.
+ * This method returns the parameter's value if it exists, or defaultValue if not.
*
- * @param name The parameter's name
+ * @param name The parameter's name
+ * @param defaultValue The default value to return if the parameter does not exist
*
- * @param defaultValue The default value to return if the parameter does
- * not exist
- *
- * @return The parameter's value or the default value if the parameter does
- * not exist
+ * @return The parameter's value or the default value if the parameter does not exist
*/
private String getInitParameter(String name, String defaultValue) {
@@ -222,25 +199,23 @@ public class CorsFilter extends GenericFilter {
/**
* Handles a CORS request of type {@link CORSRequestType}.SIMPLE.
*
- * @param request The {@link HttpServletRequest} object.
- * @param response The {@link HttpServletResponse} object.
+ * @param request The {@link HttpServletRequest} object.
+ * @param response The {@link HttpServletResponse} object.
* @param filterChain The {@link FilterChain} object.
- * @throws IOException an IO error occurred
+ *
+ * @throws IOException an IO error occurred
* @throws ServletException Servlet error propagation
- * @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple
- * Cross-Origin Request, Actual Request, and Redirects</a>
+ *
+ * @see <a href="http://www.w3.org/TR/cors/#resource-requests">Simple Cross-Origin Request, Actual Request, and
+ * Redirects</a>
*/
- protected void handleSimpleCORS(final HttpServletRequest request,
- final HttpServletResponse response, final FilterChain filterChain)
- throws IOException, ServletException {
+ protected void handleSimpleCORS(final HttpServletRequest request, final HttpServletResponse response,
+ final FilterChain filterChain) throws IOException, ServletException {
CorsFilter.CORSRequestType requestType = checkRequestType(request);
- if (!(requestType == CorsFilter.CORSRequestType.SIMPLE ||
- requestType == CorsFilter.CORSRequestType.ACTUAL)) {
- throw new IllegalArgumentException(
- sm.getString("corsFilter.wrongType2",
- CorsFilter.CORSRequestType.SIMPLE,
- CorsFilter.CORSRequestType.ACTUAL));
+ if (!(requestType == CorsFilter.CORSRequestType.SIMPLE || requestType == CorsFilter.CORSRequestType.ACTUAL)) {
+ throw new IllegalArgumentException(sm.getString("corsFilter.wrongType2", CorsFilter.CORSRequestType.SIMPLE,
+ CorsFilter.CORSRequestType.ACTUAL));
}
final String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
@@ -267,15 +242,15 @@ public class CorsFilter extends GenericFilter {
/**
* Handles CORS pre-flight request.
*
- * @param request The {@link HttpServletRequest} object.
- * @param response The {@link HttpServletResponse} object.
+ * @param request The {@link HttpServletRequest} object.
+ * @param response The {@link HttpServletResponse} object.
* @param filterChain The {@link FilterChain} object.
- * @throws IOException an IO error occurred
+ *
+ * @throws IOException an IO error occurred
* @throws ServletException Servlet error propagation
*/
- protected void handlePreflightCORS(final HttpServletRequest request,
- final HttpServletResponse response, final FilterChain filterChain)
- throws IOException, ServletException {
+ protected void handlePreflightCORS(final HttpServletRequest request, final HttpServletResponse response,
+ final FilterChain filterChain) throws IOException, ServletException {
CORSRequestType requestType = checkRequestType(request);
if (requestType != CORSRequestType.PRE_FLIGHT) {
@@ -292,8 +267,7 @@ public class CorsFilter extends GenericFilter {
}
// Section 6.2.3
- String accessControlRequestMethod = request.getHeader(
- CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+ String accessControlRequestMethod = request.getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
if (accessControlRequestMethod == null) {
handleInvalidCORS(request, response, filterChain);
return;
@@ -302,11 +276,10 @@ public class CorsFilter extends GenericFilter {
}
// Section 6.2.4
- String accessControlRequestHeadersHeader = request.getHeader(
- CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+ String accessControlRequestHeadersHeader = request
+ .getHeader(CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
List<String> accessControlRequestHeaders = new ArrayList<>();
- if (accessControlRequestHeadersHeader != null &&
- !accessControlRequestHeadersHeader.trim().isEmpty()) {
+ if (accessControlRequestHeadersHeader != null && !accessControlRequestHeadersHeader.trim().isEmpty()) {
String[] headers = accessControlRequestHeadersHeader.trim().split(",");
for (String header : headers) {
accessControlRequestHeaders.add(header.trim().toLowerCase(Locale.ENGLISH));
@@ -336,19 +309,18 @@ public class CorsFilter extends GenericFilter {
/**
- * Handles a request, that's not a CORS request, but is a valid request i.e.
- * it is not a cross-origin request. This implementation, just forwards the
- * request down the filter chain.
+ * Handles a request, that's not a CORS request, but is a valid request i.e. it is not a cross-origin request. This
+ * implementation, just forwards the request down the filter chain.
*
- * @param request The {@link HttpServletRequest} object.
- * @param response The {@link HttpServletResponse} object.
+ * @param request The {@link HttpServletRequest} object.
+ * @param response The {@link HttpServletResponse} object.
* @param filterChain The {@link FilterChain} object.
- * @throws IOException an IO error occurred
+ *
+ * @throws IOException an IO error occurred
* @throws ServletException Servlet error propagation
*/
- private void handleNonCORS(final HttpServletRequest request,
- final HttpServletResponse response, final FilterChain filterChain)
- throws IOException, ServletException {
+ private void handleNonCORS(final HttpServletRequest request, final HttpServletResponse response,
+ final FilterChain filterChain) throws IOException, ServletException {
addStandardHeaders(request, response);
@@ -360,16 +332,15 @@ public class CorsFilter extends GenericFilter {
/**
* Handles a CORS request that violates specification.
*
- * @param request The {@link HttpServletRequest} object.
- * @param response The {@link HttpServletResponse} object.
+ * @param request The {@link HttpServletRequest} object.
+ * @param response The {@link HttpServletResponse} object.
* @param filterChain The {@link FilterChain} object.
*/
- private void handleInvalidCORS(final HttpServletRequest request,
- final HttpServletResponse response, final FilterChain filterChain) {
+ private void handleInvalidCORS(final HttpServletRequest request, final HttpServletResponse response,
+ final FilterChain filterChain) {
String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
String method = request.getMethod();
- String accessControlRequestHeaders = request.getHeader(
- REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+ String accessControlRequestHeaders = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
@@ -391,11 +362,9 @@ public class CorsFilter extends GenericFilter {
/*
- * Sets a standard set of headers to reduce response variation which in turn
- * is intended to aid caching.
+ * Sets a standard set of headers to reduce response variation which in turn is intended to aid caching.
*/
- private void addStandardHeaders(final HttpServletRequest request,
- final HttpServletResponse response) {
+ private void addStandardHeaders(final HttpServletRequest request, final HttpServletResponse response) {
final String method = request.getMethod();
final String origin = request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN);
@@ -439,18 +408,15 @@ public class CorsFilter extends GenericFilter {
Collection<String> exposedHeaders = getExposedHeaders();
if ((exposedHeaders != null) && (exposedHeaders.size() > 0)) {
String exposedHeadersString = join(exposedHeaders, ",");
- response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS,
- exposedHeadersString);
+ response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS, exposedHeadersString);
}
if ("OPTIONS".equals(method)) {
// For an OPTIONS request, the response will vary based on the
// value or absence of the following headers. Hence they need be be
// included in the Vary header.
- ResponseUtil.addVaryFieldName(
- response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
- ResponseUtil.addVaryFieldName(
- response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+ ResponseUtil.addVaryFieldName(response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+ ResponseUtil.addVaryFieldName(response, CorsFilter.REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
// CORS PRE_FLIGHT (OPTIONS) requests set the following headers although
// non-CORS OPTIONS requests do not need to. The headers are always set
@@ -460,17 +426,14 @@ public class CorsFilter extends GenericFilter {
// is overridden.
long preflightMaxAge = getPreflightMaxAge();
if (preflightMaxAge > 0) {
- response.addHeader(
- CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE,
- String.valueOf(preflightMaxAge));
+ response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE, String.valueOf(preflightMaxAge));
}
// Local copy to avoid concurrency issues if getAllowedHttpMethods()
// is overridden.
Collection<String> allowedHttpMethods = getAllowedHttpMethods();
- if ((allowedHttpMethods != null) && (!allowedHttpMethods.isEmpty())) {
- response.addHeader(
- CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS,
+ if ((allowedHttpMethods != null) && (!allowedHttpMethods.isEmpty())) {
+ response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS,
join(allowedHttpMethods, ","));
}
@@ -478,8 +441,7 @@ public class CorsFilter extends GenericFilter {
// is overridden.
Collection<String> allowedHttpHeaders = getAllowedHttpHeaders();
if ((allowedHttpHeaders != null) && (!allowedHttpHeaders.isEmpty())) {
- response.addHeader(
- CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS,
+ response.addHeader(CorsFilter.RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS,
join(allowedHttpHeaders, ","));
}
}
@@ -489,22 +451,19 @@ public class CorsFilter extends GenericFilter {
/**
* Decorates the {@link HttpServletRequest}, with CORS attributes.
* <ul>
- * <li><b>cors.isCorsRequest:</b> Flag to determine if request is a CORS
- * request. Set to <code>true</code> if CORS request; <code>false</code>
- * otherwise.</li>
+ * <li><b>cors.isCorsRequest:</b> Flag to determine if request is a CORS request. Set to <code>true</code> if CORS
+ * request; <code>false</code> otherwise.</li>
* <li><b>cors.request.origin:</b> The Origin URL.</li>
- * <li><b>cors.request.type:</b> Type of request. Values:
- * <code>simple</code> or <code>preflight</code> or <code>not_cors</code> or
- * <code>invalid_cors</code></li>
- * <li><b>cors.request.headers:</b> Request headers sent as
- * 'Access-Control-Request-Headers' header, for pre-flight request.</li>
+ * <li><b>cors.request.type:</b> Type of request. Values: <code>simple</code> or <code>preflight</code> or
+ * <code>not_cors</code> or <code>invalid_cors</code></li>
+ * <li><b>cors.request.headers:</b> Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight
+ * request.</li>
* </ul>
*
- * @param request The {@link HttpServletRequest} object.
+ * @param request The {@link HttpServletRequest} object.
* @param corsRequestType The {@link CORSRequestType} object.
*/
- protected static void decorateCORSProperties(
- final HttpServletRequest request,
+ protected static void decorateCORSProperties(final HttpServletRequest request,
final CORSRequestType corsRequestType) {
if (request == null) {
throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
@@ -515,56 +474,45 @@ public class CorsFilter extends GenericFilter {
}
switch (corsRequestType) {
- case SIMPLE:
- case ACTUAL:
- request.setAttribute(
- CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.TRUE);
- request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
- request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
- request.setAttribute(
- CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
- corsRequestType.name().toLowerCase(Locale.ENGLISH));
- break;
- case PRE_FLIGHT:
- request.setAttribute(
- CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST,
- Boolean.TRUE);
- request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
- request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
- request.setAttribute(
- CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
- corsRequestType.name().toLowerCase(Locale.ENGLISH));
- String headers = request.getHeader(
- REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
- if (headers == null) {
- headers = "";
- }
- request.setAttribute(
- CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS, headers);
- break;
- case NOT_CORS:
- request.setAttribute(
- CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST,
- Boolean.FALSE);
- break;
- default:
- // Don't set any attributes
- break;
+ case SIMPLE:
+ case ACTUAL:
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.TRUE);
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
+ request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
+ corsRequestType.name().toLowerCase(Locale.ENGLISH));
+ break;
+ case PRE_FLIGHT:
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.TRUE);
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_ORIGIN,
+ request.getHeader(CorsFilter.REQUEST_HEADER_ORIGIN));
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE,
+ corsRequestType.name().toLowerCase(Locale.ENGLISH));
+ String headers = request.getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS);
+ if (headers == null) {
+ headers = "";
+ }
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS, headers);
+ break;
+ case NOT_CORS:
+ request.setAttribute(CorsFilter.HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST, Boolean.FALSE);
+ break;
+ default:
+ // Don't set any attributes
+ break;
}
}
/**
- * Joins elements of {@link Set} into a string, where each element is
- * separated by the provided separator.
+ * Joins elements of {@link Set} into a string, where each element is separated by the provided separator.
*
- * @param elements The {@link Set} containing elements to join together.
+ * @param elements The {@link Set} containing elements to join together.
* @param joinSeparator The character to be used for separating elements.
- * @return The joined {@link String}; <code>null</code> if elements
- * {@link Set} is null.
+ *
+ * @return The joined {@link String}; <code>null</code> if elements {@link Set} is null.
*/
- protected static String join(final Collection<String> elements,
- final String joinSeparator) {
+ protected static String join(final Collection<String> elements, final String joinSeparator) {
String separator = ",";
if (elements == null) {
return null;
@@ -594,13 +542,13 @@ public class CorsFilter extends GenericFilter {
* Determines the request type.
*
* @param request The HTTP Servlet request
+ *
* @return the CORS type
*/
protected CORSRequestType checkRequestType(final HttpServletRequest request) {
CORSRequestType requestType = CORSRequestType.INVALID_CORS;
if (request == null) {
- throw new IllegalArgumentException(
- sm.getString("corsFilter.nullRequest"));
+ throw new IllegalArgumentException(sm.getString("corsFilter.nullRequest"));
}
String originHeader = request.getHeader(REQUEST_HEADER_ORIGIN);
// Section 6.1.1 and Section 6.2.1
@@ -615,11 +563,9 @@ public class CorsFilter extends GenericFilter {
String method = request.getMethod();
if (method != null) {
if ("OPTIONS".equals(method)) {
- String accessControlRequestMethodHeader =
- request.getHeader(
- REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
- if (accessControlRequestMethodHeader != null &&
- !accessControlRequestMethodHeader.isEmpty()) {
+ String accessControlRequestMethodHeader = request
+ .getHeader(REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD);
+ if (accessControlRequestMethodHeader != null && !accessControlRequestMethodHeader.isEmpty()) {
requestType = CORSRequestType.PRE_FLIGHT;
} else if (accessControlRequestMethodHeader != null &&
accessControlRequestMethodHeader.isEmpty()) {
@@ -632,8 +578,7 @@ public class CorsFilter extends GenericFilter {
} else if ("POST".equals(method)) {
String mediaType = getMediaType(request.getContentType());
if (mediaType != null) {
- if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES
- .contains(mediaType)) {
+ if (SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES.contains(mediaType)) {
requestType = CORSRequestType.SIMPLE;
} else {
requestType = CORSRequestType.ACTUAL;
@@ -653,8 +598,7 @@ public class CorsFilter extends GenericFilter {
/**
- * Return the lower case, trimmed value of the media type from the content
- * type.
+ * Return the lower case, trimmed value of the media type from the content type.
*/
private String getMediaType(String contentType) {
if (contentType == null) {
@@ -672,10 +616,9 @@ public class CorsFilter extends GenericFilter {
/**
* Checks if the Origin is allowed to make a CORS request.
*
- * @param origin
- * The Origin.
- * @return <code>true</code> if origin is allowed; <code>false</code>
- * otherwise.
+ * @param origin The Origin.
+ *
+ * @return <code>true</code> if origin is allowed; <code>false</code> otherwise.
*/
private boolean isOriginAllowed(final String origin) {
if (isAnyOriginAllowed()) {
@@ -689,30 +632,21 @@ public class CorsFilter extends GenericFilter {
/**
- * Parses each param-value and populates configuration variables. If a param
- * is provided, it overrides the default.
+ * Parses each param-value and populates configuration variables. If a param is provided, it overrides the default.
+ *
+ * @param allowedOrigins A {@link String} of comma separated origins.
+ * @param allowedHttpMethods A {@link String} of comma separated HTTP methods.
+ * @param allowedHttpHeaders A {@link String} of comma separated HTTP headers.
+ * @param exposedHeaders A {@link String} of comma separated headers that needs to be exposed.
+ * @param supportsCredentials "true" if support credentials needs to be enabled.
+ * @param preflightMaxAge The amount of seconds the user agent is allowed to cache the result of the pre-flight
+ * request.
*
- * @param allowedOrigins
- * A {@link String} of comma separated origins.
- * @param allowedHttpMethods
- * A {@link String} of comma separated HTTP methods.
- * @param allowedHttpHeaders
- * A {@link String} of comma separated HTTP headers.
- * @param exposedHeaders
- * A {@link String} of comma separated headers that needs to be
- * exposed.
- * @param supportsCredentials
- * "true" if support credentials needs to be enabled.
- * @param preflightMaxAge
- * The amount of seconds the user agent is allowed to cache the
- * result of the pre-flight request.
* @throws ServletException If the configuration is invalid
*/
- private void parseAndStore(final String allowedOrigins,
- final String allowedHttpMethods, final String allowedHttpHeaders,
- final String exposedHeaders, final String supportsCredentials,
- final String preflightMaxAge, final String decorateRequest)
- throws ServletException {
+ private void parseAndStore(final String allowedOrigins, final String allowedHttpMethods,
+ final String allowedHttpHeaders, final String exposedHeaders, final String supportsCredentials,
+ final String preflightMaxAge, final String decorateRequest) throws ServletException {
if (allowedOrigins.trim().equals("*")) {
this.anyOriginAllowed = true;
@@ -754,8 +688,7 @@ public class CorsFilter extends GenericFilter {
this.preflightMaxAge = 0L;
}
} catch (NumberFormatException e) {
- throw new ServletException(
- sm.getString("corsFilter.invalidPreflightMaxAge"), e);
+ throw new ServletException(sm.getString("corsFilter.invalidPreflightMaxAge"), e);
}
// For any value other than 'true' this will be false.
@@ -765,8 +698,8 @@ public class CorsFilter extends GenericFilter {
/**
* Takes a comma separated list and returns a Set<String>.
*
- * @param data
- * A comma separated list of strings.
+ * @param data A comma separated list of strings.
+ *
* @return Set$lt;String>
*/
private Set<String> parseStringToSet(final String data) {
@@ -812,8 +745,7 @@ public class CorsFilter extends GenericFilter {
/**
* Determines is supports credentials is enabled.
*
- * @return <code>true</code> if the use of credentials is supported
- * otherwise <code>false</code>
+ * @return <code>true</code> if the use of credentials is supported otherwise <code>false</code>
*/
public boolean isSupportsCredentials() {
return supportsCredentials;
@@ -831,8 +763,7 @@ public class CorsFilter extends GenericFilter {
/**
- * Returns the {@link Set} of allowed origins that are allowed to make
- * requests.
+ * Returns the {@link Set} of allowed origins that are allowed to make requests.
*
* @return {@link Set}
*/
@@ -864,8 +795,7 @@ public class CorsFilter extends GenericFilter {
/**
* Should CORS specific attributes be added to the request.
*
- * @return {@code true} if the request should be decorated, otherwise
- * {@code false}
+ * @return {@code true} if the request should be decorated, otherwise {@code false}
*/
public boolean isDecorateRequest() {
return decorateRequest;
@@ -873,9 +803,8 @@ public class CorsFilter extends GenericFilter {
/*
- * Log objects are not Serializable but this Filter is because it extends
- * GenericFilter. Tomcat won't serialize a Filter but in case something else
- * does...
+ * Log objects are not Serializable but this Filter is because it extends GenericFilter. Tomcat won't serialize a
+ * Filter but in case something else does...
*/
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
@@ -886,73 +815,60 @@ public class CorsFilter extends GenericFilter {
// -------------------------------------------------- CORS Response Headers
/**
- * The Access-Control-Allow-Origin header indicates whether a resource can
- * be shared based by returning the value of the Origin request header in
- * the response.
+ * The Access-Control-Allow-Origin header indicates whether a resource can be shared based by returning the value of
+ * the Origin request header in the response.
*/
- public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN =
- "Access-Control-Allow-Origin";
+ public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
/**
- * The Access-Control-Allow-Credentials header indicates whether the
- * response to request can be exposed when the omit credentials flag is
- * unset. When part of the response to a preflight request it indicates that
- * the actual request can include user credentials.
+ * The Access-Control-Allow-Credentials header indicates whether the response to request can be exposed when the
+ * omit credentials flag is unset. When part of the response to a preflight request it indicates that the actual
+ * request can include user credentials.
*/
- public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS =
- "Access-Control-Allow-Credentials";
+ public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
/**
- * The Access-Control-Expose-Headers header indicates which headers are safe
- * to expose to the API of a CORS API specification
+ * The Access-Control-Expose-Headers header indicates which headers are safe to expose to the API of a CORS API
+ * specification
*/
- public static final String RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS =
- "Access-Control-Expose-Headers";
+ public static final String RESPONSE_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
/**
- * The Access-Control-Max-Age header indicates how long the results of a
- * preflight request can be cached in a preflight result cache.
+ * The Access-Control-Max-Age header indicates how long the results of a preflight request can be cached in a
+ * preflight result cache.
*/
- public static final String RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE =
- "Access-Control-Max-Age";
+ public static final String RESPONSE_HEADER_ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
/**
- * The Access-Control-Allow-Methods header indicates, as part of the
- * response to a preflight request, which methods can be used during the
- * actual request.
+ * The Access-Control-Allow-Methods header indicates, as part of the response to a preflight request, which methods
+ * can be used during the actual request.
*/
- public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS =
- "Access-Control-Allow-Methods";
+ public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
/**
- * The Access-Control-Allow-Headers header indicates, as part of the
- * response to a preflight request, which header field names can be used
- * during the actual request.
+ * The Access-Control-Allow-Headers header indicates, as part of the response to a preflight request, which header
+ * field names can be used during the actual request.
*/
- public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS =
- "Access-Control-Allow-Headers";
+ public static final String RESPONSE_HEADER_ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
// -------------------------------------------------- CORS Request Headers
/**
- * The Origin header indicates where the cross-origin request or preflight
- * request originates from.
+ * The Origin header indicates where the cross-origin request or preflight request originates from.
*/
public static final String REQUEST_HEADER_ORIGIN = "Origin";
/**
- * The Access-Control-Request-Method header indicates which method will be
- * used in the actual request as part of the preflight request.
+ * The Access-Control-Request-Method header indicates which method will be used in the actual request as part of the
+ * preflight request.
*/
- public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD =
- "Access-Control-Request-Method";
+ public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
/**
- * The Access-Control-Request-Headers header indicates which headers will be
- * used in the actual request as part of the preflight request.
+ * The Access-Control-Request-Headers header indicates which headers will be used in the actual request as part of
+ * the preflight request.
*/
- public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS =
- "Access-Control-Request-Headers";
+ public static final String REQUEST_HEADER_ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
// ----------------------------------------------------- Request attributes
/**
@@ -963,32 +879,27 @@ public class CorsFilter extends GenericFilter {
/**
* Attribute that contains the origin of the request.
*/
- public static final String HTTP_REQUEST_ATTRIBUTE_ORIGIN =
- HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.origin";
+ public static final String HTTP_REQUEST_ATTRIBUTE_ORIGIN = HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.origin";
/**
* Boolean value, suggesting if the request is a CORS request or not.
*/
- public static final String HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST =
- HTTP_REQUEST_ATTRIBUTE_PREFIX + "isCorsRequest";
+ public static final String HTTP_REQUEST_ATTRIBUTE_IS_CORS_REQUEST = HTTP_REQUEST_ATTRIBUTE_PREFIX + "isCorsRequest";
/**
* Type of CORS request, of type {@link CORSRequestType}.
*/
- public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE =
- HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.type";
+ public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_TYPE = HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.type";
/**
- * Request headers sent as 'Access-Control-Request-Headers' header, for
- * pre-flight request.
+ * Request headers sent as 'Access-Control-Request-Headers' header, for pre-flight request.
*/
- public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS =
- HTTP_REQUEST_ATTRIBUTE_PREFIX + "request.headers";
+ public static final String HTTP_REQUEST_ATTRIBUTE_REQUEST_HEADERS = HTTP_REQUEST_ATTRIBUTE_PREFIX +
+ "request.headers";
// -------------------------------------------------------------- Constants
/**
- * Enumerates varies types of CORS requests. Also, provides utility methods
- * to determine the request type.
+ * Enumerates varies types of CORS requests. Also, provides utility methods to determine the request type.
*/
protected enum CORSRequestType {
/**
@@ -1000,8 +911,7 @@ public class CorsFilter extends GenericFilter {
*/
ACTUAL,
/**
- * A pre-flight CORS request, to get meta information, before a
- * non-simple HTTP request is sent.
+ * A pre-flight CORS request, to get meta information, before a non-simple HTTP request is sent.
*/
PRE_FLIGHT,
/**
@@ -1009,23 +919,19 @@ public class CorsFilter extends GenericFilter {
*/
NOT_CORS,
/**
- * An invalid CORS request, i.e. it qualifies to be a CORS request, but
- * fails to be a valid one.
+ * An invalid CORS request, i.e. it qualifies to be a CORS request, but fails to be a valid one.
*/
INVALID_CORS
}
/**
- * {@link Collection} of media type values for the Content-Type header that
- * will be treated as 'simple'. Note media-type values are compared ignoring
- * parameters and in a case-insensitive manner.
+ * {@link Collection} of media type values for the Content-Type header that will be treated as 'simple'. Note
+ * media-type values are compared ignoring parameters and in a case-insensitive manner.
*
- * @see <a href="http://www.w3.org/TR/cors/#terminology"
- * >http://www.w3.org/TR/cors/#terminology</a>
+ * @see <a href="http://www.w3.org/TR/cors/#terminology" >http://www.w3.org/TR/cors/#terminology</a>
*/
- public static final Collection<String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES =
- Collections.unmodifiableSet(new HashSet<>(Arrays.asList(
- "application/x-www-form-urlencoded", "multipart/form-data", "text/plain")));
+ public static final Collection<String> SIMPLE_HTTP_REQUEST_CONTENT_TYPE_VALUES = Collections.unmodifiableSet(
+ new HashSet<>(Arrays.asList("application/x-www-form-urlencoded", "multipart/form-data", "text/plain")));
// ------------------------------------------------ Configuration Defaults
/**
@@ -1036,8 +942,7 @@ public class CorsFilter extends GenericFilter {
/**
* By default, following methods are supported: GET, POST, HEAD and OPTIONS.
*/
- public static final String DEFAULT_ALLOWED_HTTP_METHODS =
- "GET,POST,HEAD,OPTIONS";
+ public static final String DEFAULT_ALLOWED_HTTP_METHODS = "GET,POST,HEAD,OPTIONS";
/**
* By default, time duration to cache pre-flight response is 30 mins.
@@ -1050,12 +955,10 @@ public class CorsFilter extends GenericFilter {
public static final String DEFAULT_SUPPORTS_CREDENTIALS = "false";
/**
- * By default, following headers are supported:
- * Origin,Accept,X-Requested-With, Content-Type,
+ * By default, following headers are supported: Origin,Accept,X-Requested-With, Content-Type,
* Access-Control-Request-Method, and Access-Control-Request-Headers.
*/
- public static final String DEFAULT_ALLOWED_HTTP_HEADERS =
- "Origin,Accept,X-Requested-With,Content-Type," +
+ public static final String DEFAULT_ALLOWED_HTTP_HEADERS = "Origin,Accept,X-Requested-With,Content-Type," +
"Access-Control-Request-Method,Access-Control-Request-Headers";
/**
@@ -1072,44 +975,35 @@ public class CorsFilter extends GenericFilter {
/**
* Key to retrieve allowed origins from {@link jakarta.servlet.FilterConfig}.
*/
- public static final String PARAM_CORS_ALLOWED_ORIGINS =
- "cors.allowed.origins";
+ public static final String PARAM_CORS_ALLOWED_ORIGINS = "cors.allowed.origins";
/**
- * Key to retrieve support credentials from
- * {@link jakarta.servlet.FilterConfig}.
+ * Key to retrieve support credentials from {@link jakarta.servlet.FilterConfig}.
*/
- public static final String PARAM_CORS_SUPPORT_CREDENTIALS =
- "cors.support.credentials";
+ public static final String PARAM_CORS_SUPPORT_CREDENTIALS = "cors.support.credentials";
/**
* Key to retrieve exposed headers from {@link jakarta.servlet.FilterConfig}.
*/
- public static final String PARAM_CORS_EXPOSED_HEADERS =
- "cors.exposed.headers";
+ public static final String PARAM_CORS_EXPOSED_HEADERS = "cors.exposed.headers";
/**
* Key to retrieve allowed headers from {@link jakarta.servlet.FilterConfig}.
*/
- public static final String PARAM_CORS_ALLOWED_HEADERS =
- "cors.allowed.headers";
+ public static final String PARAM_CORS_ALLOWED_HEADERS = "cors.allowed.headers";
/**
* Key to retrieve allowed methods from {@link jakarta.servlet.FilterConfig}.
*/
- public static final String PARAM_CORS_ALLOWED_METHODS =
- "cors.allowed.methods";
+ public static final String PARAM_CORS_ALLOWED_METHODS = "cors.allowed.methods";
/**
- * Key to retrieve preflight max age from
- * {@link jakarta.servlet.FilterConfig}.
+ * Key to retrieve preflight max age from {@link jakarta.servlet.FilterConfig}.
*/
- public static final String PARAM_CORS_PREFLIGHT_MAXAGE =
- "cors.preflight.maxage";
+ public static final String PARAM_CORS_PREFLIGHT_MAXAGE = "cors.preflight.maxage";
/**
* Key to determine if request should be decorated.
*/
- public static final String PARAM_CORS_REQUEST_DECORATE =
- "cors.request.decorate";
+ public static final String PARAM_CORS_REQUEST_DECORATE = "cors.request.decorate";
}
diff --git a/java/org/apache/catalina/filters/CsrfPreventionFilter.java b/java/org/apache/catalina/filters/CsrfPreventionFilter.java
index e623c9fbab..e018d62989 100644
--- a/java/org/apache/catalina/filters/CsrfPreventionFilter.java
+++ b/java/org/apache/catalina/filters/CsrfPreventionFilter.java
@@ -37,13 +37,11 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
- * Provides basic CSRF protection for a web application. The filter assumes
- * that:
+ * Provides basic CSRF protection for a web application. The filter assumes that:
* <ul>
* <li>The filter is mapped to /*</li>
- * <li>{@link HttpServletResponse#encodeRedirectURL(String)} and
- * {@link HttpServletResponse#encodeURL(String)} are used to encode all URLs
- * returned to the client
+ * <li>{@link HttpServletResponse#encodeRedirectURL(String)} and {@link HttpServletResponse#encodeURL(String)} are used
+ * to encode all URLs returned to the client
* </ul>
*/
public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
@@ -56,14 +54,11 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
private String nonceRequestParameterName = Constants.CSRF_NONCE_REQUEST_PARAM;
/**
- * Entry points are URLs that will not be tested for the presence of a valid
- * nonce. They are used to provide a way to navigate back to a protected
- * application after navigating away from it. Entry points will be limited
- * to HTTP GET requests and should not trigger any security sensitive
- * actions.
+ * Entry points are URLs that will not be tested for the presence of a valid nonce. They are used to provide a way
+ * to navigate back to a protected application after navigating away from it. Entry points will be limited to HTTP
+ * GET requests and should not trigger any security sensitive actions.
*
- * @param entryPoints Comma separated list of URLs to be configured as
- * entry points.
+ * @param entryPoints Comma separated list of URLs to be configured as entry points.
*/
public void setEntryPoints(String entryPoints) {
String values[] = entryPoints.split(",");
@@ -73,13 +68,11 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
}
/**
- * Sets the number of previously issued nonces that will be cached on a LRU
- * basis to support parallel requests, limited use of the refresh and back
- * in the browser and similar behaviors that may result in the submission
- * of a previous nonce rather than the current one. If not set, the default
- * value of 5 will be used.
+ * Sets the number of previously issued nonces that will be cached on a LRU basis to support parallel requests,
+ * limited use of the refresh and back in the browser and similar behaviors that may result in the submission of a
+ * previous nonce rather than the current one. If not set, the default value of 5 will be used.
*
- * @param nonceCacheSize The number of nonces to cache
+ * @param nonceCacheSize The number of nonces to cache
*/
public void setNonceCacheSize(int nonceCacheSize) {
this.nonceCacheSize = nonceCacheSize;
@@ -88,8 +81,7 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
/**
* Sets the request parameter name to use for CSRF nonces.
*
- * @param parameterName The request parameter name to use
- * for CSRF nonces.
+ * @param parameterName The request parameter name to use for CSRF nonces.
*/
public void setNonceRequestParameterName(String parameterName) {
this.nonceRequestParameterName = parameterName;
@@ -101,19 +93,17 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
super.init(filterConfig);
// Put the expected request parameter name into the application scope
- filterConfig.getServletContext().setAttribute(
- Constants.CSRF_NONCE_REQUEST_PARAM_NAME_KEY,
+ filterConfig.getServletContext().setAttribute(Constants.CSRF_NONCE_REQUEST_PARAM_NAME_KEY,
nonceRequestParameterName);
}
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
ServletResponse wResponse = null;
- if (request instanceof HttpServletRequest &&
- response instanceof HttpServletResponse) {
+ if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
@@ -128,10 +118,9 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
if (previousNonce == null) {
if (log.isDebugEnabled()) {
- log.debug("Rejecting request for " + getRequestedPath(req)
- + ", session "
- + (null == session ? "(none)" : session.getId())
- + " with no CSRF nonce found in request");
+ log.debug("Rejecting request for " + getRequestedPath(req) + ", session " +
+ (null == session ? "(none)" : session.getId()) +
+ " with no CSRF nonce found in request");
}
res.sendError(getDenyStatus());
@@ -141,28 +130,25 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
nonceCache = getNonceCache(req, session);
if (nonceCache == null) {
if (log.isDebugEnabled()) {
- log.debug("Rejecting request for " + getRequestedPath(req)
- + ", session "
- + (null == session ? "(none)" : session.getId())
- + " due to empty / missing nonce cache");
+ log.debug("Rejecting request for " + getRequestedPath(req) + ", session " +
+ (null == session ? "(none)" : session.getId()) + " due to empty / missing nonce cache");
}
res.sendError(getDenyStatus());
return;
} else if (!nonceCache.contains(previousNonce)) {
if (log.isDebugEnabled()) {
- log.debug("Rejecting request for " + getRequestedPath(req)
- + ", session "
- + (null == session ? "(none)" : session.getId())
- + " due to invalid nonce " + previousNonce);
+ log.debug("Rejecting request for " + getRequestedPath(req) + ", session " +
+ (null == session ? "(none)" : session.getId()) + " due to invalid nonce " +
+ previousNonce);
}
res.sendError(getDenyStatus());
return;
}
if (log.isTraceEnabled()) {
- log.trace("Allowing request to " + getRequestedPath(req)
- + " with valid CSRF nonce " + previousNonce);
+ log.trace(
+ "Allowing request to " + getRequestedPath(req) + " with valid CSRF nonce " + previousNonce);
}
}
@@ -173,12 +159,13 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
}
if (nonceCache == null) {
if (log.isDebugEnabled()) {
- log.debug("Creating new CSRF nonce cache with size=" + nonceCacheSize + " for session " + (null == session ? "(will create)" : session.getId()));
+ log.debug("Creating new CSRF nonce cache with size=" + nonceCacheSize + " for session " +
+ (null == session ? "(will create)" : session.getId()));
}
if (session == null) {
if (log.isDebugEnabled()) {
- log.debug("Creating new session to store CSRF nonce cache");
+ log.debug("Creating new session to store CSRF nonce cache");
}
session = req.getSession(true);
@@ -224,15 +211,12 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
/**
- * Determines whether a nonce should be created. This method is provided
- * primarily for the benefit of sub-classes that wish to customise this
- * behaviour.
+ * Determines whether a nonce should be created. This method is provided primarily for the benefit of sub-classes
+ * that wish to customise this behaviour.
*
- * @param request The request that triggered the need to potentially
- * create the nonce.
+ * @param request The request that triggered the need to potentially create the nonce.
*
- * @return {@code true} if a nonce should be created, otherwise
- * {@code false}
+ * @return {@code true} if a nonce should be created, otherwise {@code false}
*/
protected boolean skipNonceGeneration(HttpServletRequest request) {
return false;
@@ -240,13 +224,12 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
/**
- * Create a new {@link NonceCache} and store in the {@link HttpSession}.
- * This method is provided primarily for the benefit of sub-classes that
- * wish to customise this behaviour.
+ * Create a new {@link NonceCache} and store in the {@link HttpSession}. This method is provided primarily for the
+ * benefit of sub-classes that wish to customise this behaviour.
*
- * @param request The request that triggered the need to create the nonce
- * cache. Unused by the default implementation.
- * @param session The session associated with the request.
+ * @param request The request that triggered the need to create the nonce cache. Unused by the default
+ * implementation.
+ * @param session The session associated with the request.
*
* @return A newly created {@link NonceCache}
*/
@@ -261,29 +244,26 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
/**
- * Obtain the {@link NonceCache} associated with the request and/or session.
- * This method is provided primarily for the benefit of sub-classes that
- * wish to customise this behaviour.
+ * Obtain the {@link NonceCache} associated with the request and/or session. This method is provided primarily for
+ * the benefit of sub-classes that wish to customise this behaviour.
*
- * @param request The request that triggered the need to obtain the nonce
- * cache. Unused by the default implementation.
- * @param session The session associated with the request.
+ * @param request The request that triggered the need to obtain the nonce cache. Unused by the default
+ * implementation.
+ * @param session The session associated with the request.
*
- * @return The {@link NonceCache} currently associated with the request
- * and/or session
+ * @return The {@link NonceCache} currently associated with the request and/or session
*/
protected NonceCache<String> getNonceCache(HttpServletRequest request, HttpSession session) {
if (session == null) {
return null;
}
@SuppressWarnings("unchecked")
- NonceCache<String> nonceCache =
- (NonceCache<String>) session.getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
+ NonceCache<String> nonceCache = (NonceCache<String>) session
+ .getAttribute(Constants.CSRF_NONCE_SESSION_ATTR_NAME);
return nonceCache;
}
- protected static class CsrfResponseWrapper
- extends HttpServletResponseWrapper {
+ protected static class CsrfResponseWrapper extends HttpServletResponseWrapper {
private final String nonceRequestParameterName;
private final String nonce;
@@ -329,7 +309,7 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
path = path.substring(0, question);
}
StringBuilder sb = new StringBuilder(path);
- if (query.length() >0) {
+ if (query.length() > 0) {
sb.append(query);
sb.append('&');
} else {
@@ -357,13 +337,14 @@ public class CsrfPreventionFilter extends CsrfPreventionFilterBase {
// Although the internal implementation uses a Map, this cache
// implementation is only concerned with the keys.
- private final Map<T,T> cache;
+ private final Map<T, T> cache;
public LruCache(final int cacheSize) {
cache = new LinkedHashMap<>() {
private static final long serialVersionUID = 1L;
+
@Override
- protected boolean removeEldestEntry(Map.Entry<T,T> eldest) {
+ protected boolean removeEldestEntry(Map.Entry<T, T> eldest) {
if (size() > cacheSize) {
return true;
}
diff --git a/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java b/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java
index d843d7021b..e88671263b 100644
--- a/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java
+++ b/java/org/apache/catalina/filters/CsrfPreventionFilterBase.java
@@ -52,22 +52,19 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
}
/**
- * Set response status code that is used to reject denied request. If none
- * set, the default value of 403 will be used.
+ * Set response status code that is used to reject denied request. If none set, the default value of 403 will be
+ * used.
*
- * @param denyStatus
- * HTTP status code
+ * @param denyStatus HTTP status code
*/
public void setDenyStatus(int denyStatus) {
this.denyStatus = denyStatus;
}
/**
- * Specify the class to use to generate the nonces. Must be in instance of
- * {@link Random}.
+ * Specify the class to use to generate the nonces. Must be in instance of {@link Random}.
*
- * @param randomClass
- * The name of the class to use
+ * @param randomClass The name of the class to use
*/
public void setRandomClass(String randomClass) {
this.randomClass = randomClass;
@@ -82,8 +79,8 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
Class<?> clazz = Class.forName(randomClass);
randomSource = (Random) clazz.getConstructor().newInstance();
} catch (ReflectiveOperationException e) {
- ServletException se = new ServletException(sm.getString(
- "csrfPrevention.invalidRandomClass", randomClass), e);
+ ServletException se = new ServletException(sm.getString("csrfPrevention.invalidRandomClass", randomClass),
+ e);
throw se;
}
}
@@ -95,12 +92,10 @@ public abstract class CsrfPreventionFilterBase extends FilterBase {
/**
- * Generate a once time token (nonce) for authenticating subsequent
- * requests. The nonce generation is a simplified version of
- * ManagerBase.generateSessionId().
+ * Generate a once time token (nonce) for authenticating subsequent requests. The nonce generation is a simplified
+ * version of ManagerBase.generateSessionId().
*
- * @param request The request. Unused in this method but present for the
- * the benefit of sub-classes.
+ * @param request The request. Unused in this method but present for the the benefit of sub-classes.
*
* @return the generated nonce
*/
diff --git a/java/org/apache/catalina/filters/ExpiresFilter.java b/java/org/apache/catalina/filters/ExpiresFilter.java
index a8ac4c4117..4ea79d6cbb 100644
--- a/java/org/apache/catalina/filters/ExpiresFilter.java
+++ b/java/org/apache/catalina/filters/ExpiresFilter.java
@@ -47,41 +47,34 @@ import org.apache.juli.logging.LogFactory;
/**
* <p>
- * ExpiresFilter is a Java Servlet API port of <a
- * href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">Apache
- * mod_expires</a> to add '{@code Expires}' and
- * '{@code Cache-Control: max-age=}' headers to HTTP response according to its
- * '{@code Content-Type}'.
+ * ExpiresFilter is a Java Servlet API port of <a href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">Apache
+ * mod_expires</a> to add '{@code Expires}' and '{@code Cache-Control: max-age=}' headers to HTTP response according to
+ * its '{@code Content-Type}'.
* </p>
- *
* <p>
- * Following documentation is inspired by <a
- * href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">mod_expires</a>
+ * Following documentation is inspired by
+ * <a href="https://httpd.apache.org/docs/2.2/mod/mod_expires.html">mod_expires</a>
* </p>
* <h2>Summary</h2>
* <p>
- * This filter controls the setting of the {@code Expires} HTTP header and the
- * {@code max-age} directive of the {@code Cache-Control} HTTP header in
- * server responses. The expiration date can set to be relative to either the
- * time the source file was last modified, or to the time of the client access.
+ * This filter controls the setting of the {@code Expires} HTTP header and the {@code max-age} directive of the
+ * {@code Cache-Control} HTTP header in server responses. The expiration date can set to be relative to either the time
+ * the source file was last modified, or to the time of the client access.
* </p>
* <p>
- * These HTTP headers are an instruction to the client about the document's
- * validity and persistence. If cached, the document may be fetched from the
- * cache rather than from the source until this time has passed. After that, the
- * cache copy is considered "expired" and invalid, and a new copy must
- * be obtained from the source.
+ * These HTTP headers are an instruction to the client about the document's validity and persistence. If cached,
+ * the document may be fetched from the cache rather than from the source until this time has passed. After that, the
+ * cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.
* </p>
* <p>
* To modify {@code Cache-Control} directives other than {@code max-age} (see
- * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9" >RFC
- * 2616 section 14.9</a>), you can use other servlet filters or <a
- * href="https://httpd.apache.org/docs/2.2/mod/mod_headers.html" >Apache Httpd
+ * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.9" >RFC 2616 section 14.9</a>), you can use
+ * other servlet filters or <a href="https://httpd.apache.org/docs/2.2/mod/mod_headers.html" >Apache Httpd
* mod_headers</a> module.
* </p>
- * <h2>Filter Configuration</h2><h3>Basic configuration to add
- * '{@code Expires}' and '{@code Cache-Control: max-age=}'
- * headers to images, CSS and JavaScript</h3>
+ * <h2>Filter Configuration</h2>
+ * <h3>Basic configuration to add '{@code Expires}' and '{@code Cache-Control: max-age=}' headers to images, CSS and
+ * JavaScript</h3>
*
* <pre>
* {@code
@@ -115,21 +108,17 @@ import org.apache.juli.logging.LogFactory;
* </pre>
*
* <h3>Configuration Parameters</h3>
- *
* <h4>{@code ExpiresByType <content-type>}</h4>
* <p>
- * This directive defines the value of the {@code Expires} header and the
- * {@code max-age} directive of the {@code Cache-Control} header generated for
- * documents of the specified type (<i>e.g.</i>, {@code text/html}). The second
- * argument sets the number of seconds that will be added to a base time to
- * construct the expiration date. The {@code Cache-Control: max-age} is
- * calculated by subtracting the request time from the expiration date and
- * expressing the result in seconds.
+ * This directive defines the value of the {@code Expires} header and the {@code max-age} directive of the
+ * {@code Cache-Control} header generated for documents of the specified type (<i>e.g.</i>, {@code text/html}). The
+ * second argument sets the number of seconds that will be added to a base time to construct the expiration date. The
+ * {@code Cache-Control: max-age} is calculated by subtracting the request time from the expiration date and expressing
+ * the result in seconds.
* </p>
* <p>
- * The base time is either the last modification time of the file, or the time
- * of the client's access to the document. Which should be used is
- * specified by the {@code <code>} field; {@code M} means that the
+ * The base time is either the last modification time of the file, or the time of the client's access to the
+ * document. Which should be used is specified by the {@code <code>} field; {@code M} means that the
* file's last modification time should be used as the base time, and
* {@code A} means the client's access time should be used. The duration
* is expressed in seconds. {@code A2592000} stands for
@@ -397,7 +386,6 @@ import org.apache.juli.logging.LogFactory;
* <p>
* Sample of initialization log message :
* </p>
- *
* <code>
* Mar 26, 2010 2:01:41 PM org.apache.catalina.filters.ExpiresFilter init
* FINE: Filter initialized with configuration ExpiresFilter[
@@ -409,19 +397,15 @@ import org.apache.juli.logging.LogFactory;
* application/javascript=ExpiresConfiguration[startingPoint=ACCESS_TIME, duration=[10 MINUTE]]}]
* </code>
* <p>
- * Sample of per-request log message where {@code ExpiresFilter} adds an
- * expiration date
+ * Sample of per-request log message where {@code ExpiresFilter} adds an expiration date
* </p>
- *
* <code>
* Mar 26, 2010 2:09:47 PM org.apache.catalina.filters.ExpiresFilter onBeforeWriteResponseBody
* FINE: Request "/tomcat.gif" with response status "200" content-type "image/gif", set expiration date 3/26/10 2:19 PM
* </code>
* <p>
- * Sample of per-request log message where {@code ExpiresFilter} does not add
- * an expiration date
+ * Sample of per-request log message where {@code ExpiresFilter} does not add an expiration date
* </p>
- *
* <code>
* Mar 26, 2010 2:10:27 PM org.apache.catalina.filters.ExpiresFilter onBeforeWriteResponseBody
* FINE: Request "/docs/config/manager.html" with response status "200" content-type "text/html", no expiration configured
@@ -462,9 +446,9 @@ public class ExpiresFilter extends FilterBase {
* Duration unit
*/
protected enum DurationUnit {
- DAY(Calendar.DAY_OF_YEAR), HOUR(Calendar.HOUR), MINUTE(Calendar.MINUTE), MONTH(
- Calendar.MONTH), SECOND(Calendar.SECOND), WEEK(
- Calendar.WEEK_OF_YEAR), YEAR(Calendar.YEAR);
+ DAY(Calendar.DAY_OF_YEAR), HOUR(Calendar.HOUR), MINUTE(Calendar.MINUTE), MONTH(Calendar.MONTH),
+ SECOND(Calendar.SECOND), WEEK(Calendar.WEEK_OF_YEAR), YEAR(Calendar.YEAR);
+
private final int calendarField;
private DurationUnit(int calendarField) {
@@ -496,8 +480,7 @@ public class ExpiresFilter extends FilterBase {
*/
private final StartingPoint startingPoint;
- public ExpiresConfiguration(StartingPoint startingPoint,
- List<Duration> durations) {
+ public ExpiresConfiguration(StartingPoint startingPoint, List<Duration> durations) {
super();
this.startingPoint = startingPoint;
this.durations = durations;
@@ -513,15 +496,13 @@ public class ExpiresFilter extends FilterBase {
@Override
public String toString() {
- return "ExpiresConfiguration[startingPoint=" + startingPoint +
- ", duration=" + durations + "]";
+ return "ExpiresConfiguration[startingPoint=" + startingPoint + ", duration=" + durations + "]";
}
}
/**
- * Expiration configuration starting point. Either the time the
- * HTML-page/servlet-response was served ({@link StartingPoint#ACCESS_TIME})
- * or the last time the HTML-page/servlet-response was modified (
+ * Expiration configuration starting point. Either the time the HTML-page/servlet-response was served
+ * ({@link StartingPoint#ACCESS_TIME}) or the last time the HTML-page/servlet-response was modified (
* {@link StartingPoint#LAST_MODIFICATION_TIME}).
*/
protected enum StartingPoint {
@@ -530,27 +511,23 @@ public class ExpiresFilter extends FilterBase {
/**
* <p>
- * Wrapping extension of the {@link HttpServletResponse} to yrap the
- * "Start Write Response Body" event.
+ * Wrapping extension of the {@link HttpServletResponse} to yrap the "Start Write Response Body" event.
* </p>
* <p>
- * For performance optimization : this extended response holds the
- * {@link #lastModifiedHeader} and {@link #cacheControlHeader} values access
- * to the slow {@link #getHeader(String)} and to spare the {@code string}
+ * For performance optimization : this extended response holds the {@link #lastModifiedHeader} and
+ * {@link #cacheControlHeader} values access to the slow {@link #getHeader(String)} and to spare the {@code string}
* to {@code date} to {@code long} conversion.
* </p>
*/
public class XHttpServletResponse extends HttpServletResponseWrapper {
/**
- * Value of the {@code Cache-Control} http response header if it has
- * been set.
+ * Value of the {@code Cache-Control} http response header if it has been set.
*/
private String cacheControlHeader;
/**
- * Value of the {@code Last-Modified} http response header if it has
- * been set.
+ * Value of the {@code Last-Modified} http response header if it has been set.
*/
private long lastModifiedHeader;
@@ -563,14 +540,12 @@ public class ExpiresFilter extends FilterBase {
private ServletOutputStream servletOutputStream;
/**
- * Indicates whether calls to write methods ({@code write(...)},
- * {@code print(...)}, etc) of the response body have been called or
- * not.
+ * Indicates whether calls to write methods ({@code write(...)}, {@code print(...)}, etc) of the response body
+ * have been called or not.
*/
private boolean writeResponseBodyStarted;
- public XHttpServletResponse(HttpServletRequest request,
- HttpServletResponse response) {
+ public XHttpServletResponse(HttpServletRequest request, HttpServletResponse response) {
super(response);
this.request = request;
}
@@ -587,8 +562,7 @@ public class ExpiresFilter extends FilterBase {
@Override
public void addHeader(String name, String value) {
super.addHeader(name, value);
- if (HEADER_CACHE_CONTROL.equalsIgnoreCase(name) &&
- cacheControlHeader == null) {
+ if (HEADER_CACHE_CONTROL.equalsIgnoreCase(name) && cacheControlHeader == null) {
cacheControlHeader = value;
}
}
@@ -604,8 +578,7 @@ public class ExpiresFilter extends FilterBase {
@Override
public ServletOutputStream getOutputStream() throws IOException {
if (servletOutputStream == null) {
- servletOutputStream = new XServletOutputStream(
- super.getOutputStream(), request, this);
+ servletOutputStream = new XServletOutputStream(super.getOutputStream(), request, this);
}
return servletOutputStream;
}
@@ -657,8 +630,7 @@ public class ExpiresFilter extends FilterBase {
}
/**
- * Wrapping extension of {@link PrintWriter} to trap the
- * "Start Write Response Body" event.
+ * Wrapping extension of {@link PrintWriter} to trap the "Start Write Response Body" event.
*/
public class XPrintWriter extends PrintWriter {
private final PrintWriter out;
@@ -667,8 +639,7 @@ public class ExpiresFilter extends FilterBase {
private final XHttpServletResponse response;
- public XPrintWriter(PrintWriter out, HttpServletRequest request,
- XHttpServletResponse response) {
+ public XPrintWriter(PrintWriter out, HttpServletRequest request, XHttpServletResponse response) {
super(out);
this.out = out;
this.request = request;
@@ -871,8 +842,7 @@ public class ExpiresFilter extends FilterBase {
}
/**
- * Wrapping extension of {@link ServletOutputStream} to trap the
- * "Start Write Response Body" event.
+ * Wrapping extension of {@link ServletOutputStream} to trap the "Start Write Response Body" event.
*/
public class XServletOutputStream extends ServletOutputStream {
@@ -882,8 +852,8 @@ public class ExpiresFilter extends FilterBase {
private final ServletOutputStream servletOutputStream;
- public XServletOutputStream(ServletOutputStream servletOutputStream,
- HttpServletRequest request, XHttpServletResponse response) {
+ public XServletOutputStream(ServletOutputStream servletOutputStream, HttpServletRequest request,
+ XHttpServletResponse response) {
super();
this.servletOutputStream = servletOutputStream;
this.response = response;
@@ -1035,8 +1005,7 @@ public class ExpiresFilter extends FilterBase {
}
/**
- * {@link Pattern} for a comma delimited string that support whitespace
- * characters
+ * {@link Pattern} for a comma delimited string that support whitespace characters
*/
private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*");
@@ -1059,12 +1028,11 @@ public class ExpiresFilter extends FilterBase {
/**
* Convert a comma delimited list of numbers into an {@code int[]}.
*
- * @param commaDelimitedInts
- * can be {@code null}
+ * @param commaDelimitedInts can be {@code null}
+ *
* @return never {@code null} array
*/
- protected static int[] commaDelimitedListToIntArray(
- String commaDelimitedInts) {
+ protected static int[] commaDelimitedListToIntArray(String commaDelimitedInts) {
String[] intsAsStrings = commaDelimitedListToStringArray(commaDelimitedInts);
int[] ints = new int[intsAsStrings.length];
for (int i = 0; i < intsAsStrings.length; i++) {
@@ -1072,8 +1040,8 @@ public class ExpiresFilter extends FilterBase {
try {
ints[i] = Integer.parseInt(intAsString);
} catch (NumberFormatException e) {
- throw new RuntimeException(sm.getString("expiresFilter.numberError",
- Integer.valueOf(i), commaDelimitedInts));
+ throw new RuntimeException(
+ sm.getString("expiresFilter.numberError", Integer.valueOf(i), commaDelimitedInts));
}
}
return ints;
@@ -1083,18 +1051,18 @@ public class ExpiresFilter extends FilterBase {
* Convert a given comma delimited list of strings into an array of String
*
* @param commaDelimitedStrings the string to be split
+ *
* @return array of patterns (non {@code null})
*/
- protected static String[] commaDelimitedListToStringArray(
- String commaDelimitedStrings) {
+ protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) {
return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0]
: commaSeparatedValuesPattern.split(commaDelimitedStrings);
}
/**
- * @return {@code true} if the given {@code str} contains the given
- * {@code searchStr}.
- * @param str String that will be searched
+ * @return {@code true} if the given {@code str} contains the given {@code searchStr}.
+ *
+ * @param str String that will be searched
* @param searchStr The substring to search
*/
protected static boolean contains(String str, String searchStr) {
@@ -1106,7 +1074,9 @@ public class ExpiresFilter extends FilterBase {
/**
* Convert an array of ints into a comma delimited string
+ *
* @param ints The int array
+ *
* @return a comma separated string
*/
protected static String intsToCommaDelimitedString(int[] ints) {
@@ -1127,8 +1097,8 @@ public class ExpiresFilter extends FilterBase {
/**
* @param str The String to check
- * @return {@code true} if the given {@code str} is
- * {@code null} or has a zero characters length.
+ *
+ * @return {@code true} if the given {@code str} is {@code null} or has a zero characters length.
*/
protected static boolean isEmpty(String str) {
return str == null || str.length() == 0;
@@ -1136,21 +1106,18 @@ public class ExpiresFilter extends FilterBase {
/**
* @param str The String to check
- * @return {@code true} if the given {@code str} has at least one
- * character (can be a whitespace).
+ *
+ * @return {@code true} if the given {@code str} has at least one character (can be a whitespace).
*/
protected static boolean isNotEmpty(String str) {
return !isEmpty(str);
}
/**
- * @return {@code true} if the given {@code string} starts with the
- * given {@code prefix} ignoring case.
+ * @return {@code true} if the given {@code string} starts with the given {@code prefix} ignoring case.
*
- * @param string
- * can be {@code null}
- * @param prefix
- * can be {@code null}
+ * @param string can be {@code null}
+ * @param prefix can be {@code null}
*/
protected static boolean startsWithIgnoreCase(String string, String prefix) {
if (string == null || prefix == null) {
@@ -1164,15 +1131,12 @@ public class ExpiresFilter extends FilterBase {
}
/**
- * @return the subset of the given {@code str} that is before the first
- * occurrence of the given {@code separator}. Return {@code null}
- * if the given {@code str} or the given {@code separator} is
- * null. Return and empty string if the {@code separator} is empty.
+ * @return the subset of the given {@code str} that is before the first occurrence of the given {@code separator}.
+ * Return {@code null} if the given {@code str} or the given {@code separator} is null. Return and empty
+ * string if the {@code separator} is empty.
*
- * @param str
- * can be {@code null}
- * @param separator
- * can be {@code null}
+ * @param str can be {@code null}
+ * @param separator can be {@code null}
*/
protected static String substringBefore(String str, String separator) {
if (str == null || str.isEmpty() || separator == null) {
@@ -1196,8 +1160,7 @@ public class ExpiresFilter extends FilterBase {
private ExpiresConfiguration defaultExpiresConfiguration;
/**
- * list of response status code for which the {@link ExpiresFilter} will not
- * generate expiration headers.
+ * list of response status code for which the {@link ExpiresFilter} will not generate expiration headers.
*/
private int[] excludedResponseStatusCodes = new int[] { HttpServletResponse.SC_NOT_MODIFIED };
@@ -1207,23 +1170,19 @@ public class ExpiresFilter extends FilterBase {
private Map<String, ExpiresConfiguration> expiresConfigurationByContentType = new LinkedHashMap<>();
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- if (request instanceof HttpServletRequest &&
- response instanceof HttpServletResponse) {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
if (response.isCommitted()) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "expiresFilter.responseAlreadyCommitted",
- httpRequest.getRequestURL()));
+ log.debug(sm.getString("expiresFilter.responseAlreadyCommitted", httpRequest.getRequestURL()));
}
chain.doFilter(request, response);
} else {
- XHttpServletResponse xResponse = new XHttpServletResponse(
- httpRequest, httpResponse);
+ XHttpServletResponse xResponse = new XHttpServletResponse(httpRequest, httpResponse);
chain.doFilter(request, xResponse);
if (!xResponse.isWriteResponseBodyStarted()) {
// Empty response, manually trigger
@@ -1250,9 +1209,8 @@ public class ExpiresFilter extends FilterBase {
/**
- * Returns the expiration date of the given {@link XHttpServletResponse} or
- * {@code null} if no expiration date has been configured for the
- * declared content type.
+ * Returns the expiration date of the given {@link XHttpServletResponse} or {@code null} if no expiration date has
+ * been configured for the declared content type.
* <p>
* {@code protected} for extension.
*
@@ -1260,6 +1218,7 @@ public class ExpiresFilter extends FilterBase {
* @param response The wrapped HTTP response
*
* @return the expiration date
+ *
* @see HttpServletResponse#getContentType()
*/
protected Date getExpirationDate(HttpServletRequest request, XHttpServletResponse response) {
@@ -1288,9 +1247,8 @@ public class ExpiresFilter extends FilterBase {
if (configuration != null) {
Date result = getExpirationDate(configuration, response);
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "expiresFilter.useMatchingConfiguration",
- configuration, contentType, contentType, result));
+ log.debug(sm.getString("expiresFilter.useMatchingConfiguration", configuration, contentType,
+ contentType, result));
}
return result;
}
@@ -1303,10 +1261,8 @@ public class ExpiresFilter extends FilterBase {
if (configuration != null) {
Date result = getExpirationDate(configuration, response);
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "expiresFilter.useMatchingConfiguration",
- configuration, contentTypeWithoutCharset,
- contentType, result));
+ log.debug(sm.getString("expiresFilter.useMatchingConfiguration", configuration,
+ contentTypeWithoutCharset, contentType, result));
}
return result;
}
@@ -1319,74 +1275,69 @@ public class ExpiresFilter extends FilterBase {
if (configuration != null) {
Date result = getExpirationDate(configuration, response);
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "expiresFilter.useMatchingConfiguration",
- configuration, majorType, contentType, result));
+ log.debug(sm.getString("expiresFilter.useMatchingConfiguration", configuration, majorType,
+ contentType, result));
}
return result;
}
}
if (defaultExpiresConfiguration != null) {
- Date result = getExpirationDate(defaultExpiresConfiguration,
- response);
+ Date result = getExpirationDate(defaultExpiresConfiguration, response);
if (log.isDebugEnabled()) {
- log.debug(sm.getString("expiresFilter.useDefaultConfiguration",
- defaultExpiresConfiguration, contentType, result));
+ log.debug(sm.getString("expiresFilter.useDefaultConfiguration", defaultExpiresConfiguration,
+ contentType, result));
}
return result;
}
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "expiresFilter.noExpirationConfiguredForContentType",
- contentType));
+ log.debug(sm.getString("expiresFilter.noExpirationConfiguredForContentType", contentType));
}
return null;
}
/**
* <p>
- * Returns the expiration date of the given {@link ExpiresConfiguration},
- * {@link HttpServletRequest} and {@link XHttpServletResponse}.
+ * Returns the expiration date of the given {@link ExpiresConfiguration}, {@link HttpServletRequest} and
+ * {@link XHttpServletResponse}.
* </p>
* <p>
* {@code protected} for extension.
* </p>
+ *
* @param configuration The parsed expires
- * @param response The Servlet response
+ * @param response The Servlet response
+ *
* @return the expiration date
*/
- protected Date getExpirationDate(ExpiresConfiguration configuration,
- XHttpServletResponse response) {
+ protected Date getExpirationDate(ExpiresConfiguration configuration, XHttpServletResponse response) {
Calendar calendar;
switch (configuration.getStartingPoint()) {
- case ACCESS_TIME:
- calendar = Calendar.getInstance();
- break;
- case LAST_MODIFICATION_TIME:
- if (response.isLastModifiedHeaderSet()) {
- try {
- long lastModified = response.getLastModifiedHeader();
- calendar = Calendar.getInstance();
- calendar.setTimeInMillis(lastModified);
- } catch (NumberFormatException e) {
- // default to now
+ case ACCESS_TIME:
+ calendar = Calendar.getInstance();
+ break;
+ case LAST_MODIFICATION_TIME:
+ if (response.isLastModifiedHeaderSet()) {
+ try {
+ long lastModified = response.getLastModifiedHeader();
+ calendar = Calendar.getInstance();
+ calendar.setTimeInMillis(lastModified);
+ } catch (NumberFormatException e) {
+ // default to now
+ calendar = Calendar.getInstance();
+ }
+ } else {
+ // Last-Modified header not found, use now
calendar = Calendar.getInstance();
}
- } else {
- // Last-Modified header not found, use now
- calendar = Calendar.getInstance();
- }
- break;
- default:
- throw new IllegalStateException(sm.getString(
- "expiresFilter.unsupportedStartingPoint",
- configuration.getStartingPoint()));
+ break;
+ default:
+ throw new IllegalStateException(
+ sm.getString("expiresFilter.unsupportedStartingPoint", configuration.getStartingPoint()));
}
for (Duration duration : configuration.getDurations()) {
- calendar.add(duration.getUnit().getCalendardField(),
- duration.getAmount());
+ calendar.add(duration.getUnit().getCalendardField(), duration.getAmount());
}
return calendar.getTime();
@@ -1409,51 +1360,44 @@ public class ExpiresFilter extends FilterBase {
try {
if (name.startsWith(PARAMETER_EXPIRES_BY_TYPE)) {
- String contentType = name.substring(
- PARAMETER_EXPIRES_BY_TYPE.length()).trim().toLowerCase(Locale.ENGLISH);
+ String contentType = name.substring(PARAMETER_EXPIRES_BY_TYPE.length()).trim()
+ .toLowerCase(Locale.ENGLISH);
ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value);
- this.expiresConfigurationByContentType.put(contentType,
- expiresConfiguration);
+ this.expiresConfigurationByContentType.put(contentType, expiresConfiguration);
} else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_DEFAULT)) {
ExpiresConfiguration expiresConfiguration = parseExpiresConfiguration(value);
this.defaultExpiresConfiguration = expiresConfiguration;
} else if (name.equalsIgnoreCase(PARAMETER_EXPIRES_EXCLUDED_RESPONSE_STATUS_CODES)) {
this.excludedResponseStatusCodes = commaDelimitedListToIntArray(value);
} else {
- log.warn(sm.getString(
- "expiresFilter.unknownParameterIgnored", name,
- value));
+ log.warn(sm.getString("expiresFilter.unknownParameterIgnored", name, value));
}
} catch (RuntimeException e) {
- throw new ServletException(sm.getString(
- "expiresFilter.exceptionProcessingParameter", name,
- value), e);
+ throw new ServletException(sm.getString("expiresFilter.exceptionProcessingParameter", name, value), e);
}
}
- log.debug(sm.getString("expiresFilter.filterInitialized",
- this.toString()));
+ log.debug(sm.getString("expiresFilter.filterInitialized", this.toString()));
}
/**
* <p>
* {@code protected} for extension.
* </p>
- * @param request The Servlet request
+ *
+ * @param request The Servlet request
* @param response The Servlet response
+ *
* @return <code>true</code> if an expire header may be added
*/
- protected boolean isEligibleToExpirationHeaderGeneration(
- HttpServletRequest request, XHttpServletResponse response) {
+ protected boolean isEligibleToExpirationHeaderGeneration(HttpServletRequest request,
+ XHttpServletResponse response) {
boolean expirationHeaderHasBeenSet = response.containsHeader(HEADER_EXPIRES) ||
contains(response.getCacheControlHeader(), "max-age");
if (expirationHeaderHasBeenSet) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString(
- "expiresFilter.expirationHeaderAlreadyDefined",
- request.getRequestURI(),
- Integer.valueOf(response.getStatus()),
- response.getContentType()));
+ log.debug(sm.getString("expiresFilter.expirationHeaderAlreadyDefined", request.getRequestURI(),
+ Integer.valueOf(response.getStatus()), response.getContentType()));
}
return false;
}
@@ -1461,10 +1405,8 @@ public class ExpiresFilter extends FilterBase {
for (int skippedStatusCode : this.excludedResponseStatusCodes) {
if (response.getStatus() == skippedStatusCode) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("expiresFilter.skippedStatusCode",
- request.getRequestURI(),
- Integer.valueOf(response.getStatus()),
- response.getContentType()));
+ log.debug(sm.getString("expiresFilter.skippedStatusCode", request.getRequestURI(),
+ Integer.valueOf(response.getStatus()), response.getContentType()));
}
return false;
}
@@ -1475,26 +1417,23 @@ public class ExpiresFilter extends FilterBase {
/**
* <p>
- * If no expiration header has been set by the servlet and an expiration has
- * been defined in the {@link ExpiresFilter} configuration, sets the
- * '{@code Expires}' header and the attribute '{@code max-age}' of the
+ * If no expiration header has been set by the servlet and an expiration has been defined in the
+ * {@link ExpiresFilter} configuration, sets the '{@code Expires}' header and the attribute '{@code max-age}' of the
* '{@code Cache-Control}' header.
* </p>
* <p>
* Must be called on the "Start Write Response Body" event.
* </p>
* <p>
- * Invocations to {@code Logger.debug(...)} are guarded by
- * {@link Log#isDebugEnabled()} because
- * {@link HttpServletRequest#getRequestURI()} and
- * {@link HttpServletResponse#getContentType()} costs {@code String}
+ * Invocations to {@code Logger.debug(...)} are guarded by {@link Log#isDebugEnabled()} because
+ * {@link HttpServletRequest#getRequestURI()} and {@link HttpServletResponse#getContentType()} costs {@code String}
* objects instantiations (as of Tomcat 7).
* </p>
- * @param request The Servlet request
+ *
+ * @param request The Servlet request
* @param response The Servlet response
*/
- public void onBeforeWriteResponseBody(HttpServletRequest request,
- XHttpServletResponse response) {
+ public void onBeforeWriteResponseBody(HttpServletRequest request, XHttpServletResponse response) {
if (!isEligibleToExpirationHeaderGeneration(request, response)) {
return;
@@ -1503,21 +1442,16 @@ public class ExpiresFilter extends FilterBase {
Date expirationDate = getExpirationDate(request, response);
if (expirationDate == null) {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("expiresFilter.noExpirationConfigured",
- request.getRequestURI(),
- Integer.valueOf(response.getStatus()),
- response.getContentType()));
+ log.debug(sm.getString("expiresFilter.noExpirationConfigured", request.getRequestURI(),
+ Integer.valueOf(response.getStatus()), response.getContentType()));
}
} else {
if (log.isDebugEnabled()) {
- log.debug(sm.getString("expiresFilter.setExpirationDate",
- request.getRequestURI(),
- Integer.valueOf(response.getStatus()),
- response.getContentType(), expirationDate));
+ log.debug(sm.getString("expiresFilter.setExpirationDate", request.getRequestURI(),
+ Integer.valueOf(response.getStatus()), response.getContentType(), expirationDate));
}
- String maxAgeDirective = "max-age=" +
- ((expirationDate.getTime() - System.currentTimeMillis()) / 1000);
+ String maxAgeDirective = "max-age=" + ((expirationDate.getTime() - System.currentTimeMillis()) / 1000);
String cacheControlHeader = response.getCacheControlHeader();
String newCacheControlHeader = (cacheControlHeader == null) ? maxAgeDirective
@@ -1529,11 +1463,11 @@ public class ExpiresFilter extends FilterBase {
}
/**
- * Parse configuration lines like
- * '{@code access plus 1 month 15 days 2 hours}' or
+ * Parse configuration lines like '{@code access plus 1 month 15 days 2 hours}' or
* '{@code modification 1 day 2 hours 5 seconds}'
*
* @param inputLine the input
+ *
* @return the parsed expires
*/
protected ExpiresConfiguration parseExpiresConfiguration(String inputLine) {
@@ -1546,38 +1480,30 @@ public class ExpiresFilter extends FilterBase {
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
- throw new IllegalStateException(sm.getString(
- "expiresFilter.startingPointNotFound", line));
+ throw new IllegalStateException(sm.getString("expiresFilter.startingPointNotFound", line));
}
StartingPoint startingPoint;
- if ("access".equalsIgnoreCase(currentToken) ||
- "now".equalsIgnoreCase(currentToken)) {
+ if ("access".equalsIgnoreCase(currentToken) || "now".equalsIgnoreCase(currentToken)) {
startingPoint = StartingPoint.ACCESS_TIME;
} else if ("modification".equalsIgnoreCase(currentToken)) {
startingPoint = StartingPoint.LAST_MODIFICATION_TIME;
- } else if (!tokenizer.hasMoreTokens() &&
- startsWithIgnoreCase(currentToken, "a")) {
+ } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "a")) {
startingPoint = StartingPoint.ACCESS_TIME;
// trick : convert duration configuration from old to new style
- tokenizer = new StringTokenizer(currentToken.substring(1) +
- " seconds", " ");
- } else if (!tokenizer.hasMoreTokens() &&
- startsWithIgnoreCase(currentToken, "m")) {
+ tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " ");
+ } else if (!tokenizer.hasMoreTokens() && startsWithIgnoreCase(currentToken, "m")) {
startingPoint = StartingPoint.LAST_MODIFICATION_TIME;
// trick : convert duration configuration from old to new style
- tokenizer = new StringTokenizer(currentToken.substring(1) +
- " seconds", " ");
+ tokenizer = new StringTokenizer(currentToken.substring(1) + " seconds", " ");
} else {
- throw new IllegalStateException(sm.getString(
- "expiresFilter.startingPointInvalid", currentToken, line));
+ throw new IllegalStateException(sm.getString("expiresFilter.startingPointInvalid", currentToken, line));
}
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
- throw new IllegalStateException(sm.getString(
- "expiresFilter.noDurationFound", line));
+ throw new IllegalStateException(sm.getString("expiresFilter.noDurationFound", line));
}
if ("plus".equalsIgnoreCase(currentToken)) {
@@ -1585,8 +1511,7 @@ public class ExpiresFilter extends FilterBase {
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
- throw new IllegalStateException(sm.getString(
- "expiresFilter.noDurationFound", line));
+ throw new IllegalStateException(sm.getString("expiresFilter.noDurationFound", line));
}
}
@@ -1597,46 +1522,33 @@ public class ExpiresFilter extends FilterBase {
try {
amount = Integer.parseInt(currentToken);
} catch (NumberFormatException e) {
- throw new IllegalStateException(sm.getString(
- "expiresFilter.invalidDurationNumber",
- currentToken, line));
+ throw new IllegalStateException(
+ sm.getString("expiresFilter.invalidDurationNumber", currentToken, line));
}
try {
currentToken = tokenizer.nextToken();
} catch (NoSuchElementException e) {
throw new IllegalStateException(
- sm.getString(
- "expiresFilter.noDurationUnitAfterAmount",
- Integer.valueOf(amount), line));
+ sm.getString("expiresFilter.noDurationUnitAfterAmount", Integer.valueOf(amount), line));
}
DurationUnit durationUnit;
- if ("year".equalsIgnoreCase(currentToken) ||
- "years".equalsIgnoreCase(currentToken)) {
+ if ("year".equalsIgnoreCase(currentToken) || "years".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.YEAR;
- } else if ("month".equalsIgnoreCase(currentToken) ||
- "months".equalsIgnoreCase(currentToken)) {
+ } else if ("month".equalsIgnoreCase(currentToken) || "months".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.MONTH;
- } else if ("week".equalsIgnoreCase(currentToken) ||
- "weeks".equalsIgnoreCase(currentToken)) {
+ } else if ("week".equalsIgnoreCase(currentToken) || "weeks".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.WEEK;
- } else if ("day".equalsIgnoreCase(currentToken) ||
- "days".equalsIgnoreCase(currentToken)) {
+ } else if ("day".equalsIgnoreCase(currentToken) || "days".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.DAY;
- } else if ("hour".equalsIgnoreCase(currentToken) ||
- "hours".equalsIgnoreCase(currentToken)) {
+ } else if ("hour".equalsIgnoreCase(currentToken) || "hours".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.HOUR;
- } else if ("minute".equalsIgnoreCase(currentToken) ||
- "minutes".equalsIgnoreCase(currentToken)) {
+ } else if ("minute".equalsIgnoreCase(currentToken) || "minutes".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.MINUTE;
- } else if ("second".equalsIgnoreCase(currentToken) ||
- "seconds".equalsIgnoreCase(currentToken)) {
+ } else if ("second".equalsIgnoreCase(currentToken) || "seconds".equalsIgnoreCase(currentToken)) {
durationUnit = DurationUnit.SECOND;
} else {
- throw new IllegalStateException(
- sm.getString(
- "expiresFilter.invalidDurationUnit",
- currentToken, line));
+ throw new IllegalStateException(sm.getString("expiresFilter.invalidDurationUnit", currentToken, line));
}
Duration duration = new Duration(amount, durationUnit);
@@ -1652,8 +1564,7 @@ public class ExpiresFilter extends FilterBase {
return new ExpiresConfiguration(startingPoint, durations);
}
- public void setDefaultExpiresConfiguration(
- ExpiresConfiguration defaultExpiresConfiguration) {
+ public void setDefaultExpiresConfiguration(ExpiresConfiguration defaultExpiresConfiguration) {
this.defaultExpiresConfiguration = defaultExpiresConfiguration;
}
@@ -1669,8 +1580,7 @@ public class ExpiresFilter extends FilterBase {
@Override
public String toString() {
return getClass().getSimpleName() + "[excludedResponseStatusCode=[" +
- intsToCommaDelimitedString(this.excludedResponseStatusCodes) +
- "], default=" + this.defaultExpiresConfiguration + ", byType=" +
- this.expiresConfigurationByContentType + "]";
+ intsToCommaDelimitedString(this.excludedResponseStatusCodes) + "], default=" +
+ this.defaultExpiresConfiguration + ", byType=" + this.expiresConfigurationByContentType + "]";
}
}
diff --git a/java/org/apache/catalina/filters/FailedRequestFilter.java b/java/org/apache/catalina/filters/FailedRequestFilter.java
index 41ee200ac2..3e6368faf7 100644
--- a/java/org/apache/catalina/filters/FailedRequestFilter.java
+++ b/java/org/apache/catalina/filters/FailedRequestFilter.java
@@ -30,16 +30,12 @@ import org.apache.juli.logging.LogFactory;
import org.apache.tomcat.util.http.Parameters.FailReason;
/**
- * Filter that will reject requests if there was a failure during parameter
- * parsing. This filter can be used to ensure that none parameter values
- * submitted by client are lost.
- *
+ * Filter that will reject requests if there was a failure during parameter parsing. This filter can be used to ensure
+ * that none parameter values submitted by client are lost.
* <p>
- * Note that parameter parsing may consume the body of an HTTP request, so
- * caution is needed if the servlet protected by this filter uses
- * <code>request.getInputStream()</code> or <code>request.getReader()</code>
- * calls. In general the risk of breaking a web application by adding this
- * filter is not so high, because parameter parsing does check content type
+ * Note that parameter parsing may consume the body of an HTTP request, so caution is needed if the servlet protected by
+ * this filter uses <code>request.getInputStream()</code> or <code>request.getReader()</code> calls. In general the risk
+ * of breaking a web application by adding this filter is not so high, because parameter parsing does check content type
* of the request before consuming the request body.
*/
public class FailedRequestFilter extends FilterBase {
@@ -54,11 +50,10 @@ public class FailedRequestFilter extends FilterBase {
}
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
if (!isGoodRequest(request)) {
- FailReason reason = (FailReason) request.getAttribute(
- Globals.PARAMETER_PARSE_FAILED_REASON_ATTR);
+ FailReason reason = (FailReason) request.getAttribute(Globals.PARAMETER_PARSE_FAILED_REASON_ATTR);
int status;
@@ -75,8 +70,8 @@ public class FailedRequestFilter extends FilterBase {
// and/or URI could be well below any limits set. Use the
// default.
case UNKNOWN: // Assume the client is at fault
- // Various things that the client can get wrong that don't have
- // a specific status code so use the default.
+ // Various things that the client can get wrong that don't have
+ // a specific status code so use the default.
case INVALID_CONTENT_TYPE:
case MULTIPART_CONFIG_INVALID:
case NO_NAME:
diff --git a/java/org/apache/catalina/filters/FilterBase.java b/java/org/apache/catalina/filters/FilterBase.java
index 9ef6c75caf..d2522f3327 100644
--- a/java/org/apache/catalina/filters/FilterBase.java
+++ b/java/org/apache/catalina/filters/FilterBase.java
@@ -27,8 +27,7 @@ import org.apache.tomcat.util.IntrospectionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
- * Base class for filters that provides generic initialisation and a simple
- * no-op destruction.
+ * Base class for filters that provides generic initialisation and a simple no-op destruction.
*/
public abstract class FilterBase implements Filter {
@@ -38,26 +37,21 @@ public abstract class FilterBase implements Filter {
/**
- * Iterates over the configuration parameters and either logs a warning,
- * or throws an exception for any parameter that does not have a matching
- * setter in this filter.
+ * Iterates over the configuration parameters and either logs a warning, or throws an exception for any parameter
+ * that does not have a matching setter in this filter.
*
- * @param filterConfig The configuration information associated with the
- * filter instance being initialised
+ * @param filterConfig The configuration information associated with the filter instance being initialised
*
- * @throws ServletException if {@link #isConfigProblemFatal()} returns
- * {@code true} and a configured parameter does not
- * have a matching setter
+ * @throws ServletException if {@link #isConfigProblemFatal()} returns {@code true} and a configured parameter does
+ * not have a matching setter
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Enumeration<String> paramNames = filterConfig.getInitParameterNames();
while (paramNames.hasMoreElements()) {
String paramName = paramNames.nextElement();
- if (!IntrospectionUtils.setProperty(this, paramName,
- filterConfig.getInitParameter(paramName))) {
- String msg = sm.getString("filterbase.noSuchProperty",
- paramName, this.getClass().getName());
+ if (!IntrospectionUtils.setProperty(this, paramName, filterConfig.getInitParameter(paramName))) {
+ String msg = sm.getString("filterbase.noSuchProperty", paramName, this.getClass().getName());
if (isConfigProblemFatal()) {
throw new ServletException(msg);
} else {
@@ -68,12 +62,10 @@ public abstract class FilterBase implements Filter {
}
/**
- * Determines if an exception when calling a setter or an unknown
- * configuration attribute triggers the failure of the this filter which in
- * turn will prevent the web application from starting.
+ * Determines if an exception when calling a setter or an unknown configuration attribute triggers the failure of
+ * the this filter which in turn will prevent the web application from starting.
*
- * @return <code>true</code> if a problem should trigger the failure of this
- * filter, else <code>false</code>
+ * @return <code>true</code> if a problem should trigger the failure of this filter, else <code>false</code>
*/
protected boolean isConfigProblemFatal() {
return false;
diff --git a/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java b/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java
index ddf420a344..e20ace2d95 100644
--- a/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java
+++ b/java/org/apache/catalina/filters/HttpHeaderSecurityFilter.java
@@ -31,8 +31,8 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
- * Provides a single configuration point for security measures that required the
- * addition of one or more HTTP headers to the response.
+ * Provides a single configuration point for security measures that required the addition of one or more HTTP headers to
+ * the response.
*/
public class HttpHeaderSecurityFilter extends FilterBase {
@@ -91,8 +91,8 @@ public class HttpHeaderSecurityFilter extends FilterBase {
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
if (response instanceof HttpServletResponse) {
HttpServletResponse httpResponse = (HttpServletResponse) response;
@@ -222,8 +222,7 @@ public class HttpHeaderSecurityFilter extends FilterBase {
}
- public void setBlockContentTypeSniffingEnabled(
- boolean blockContentTypeSniffingEnabled) {
+ public void setBlockContentTypeSniffingEnabled(boolean blockContentTypeSniffingEnabled) {
this.blockContentTypeSniffingEnabled = blockContentTypeSniffingEnabled;
}
@@ -250,9 +249,7 @@ public class HttpHeaderSecurityFilter extends FilterBase {
private enum XFrameOption {
- DENY("DENY"),
- SAME_ORIGIN("SAMEORIGIN"),
- ALLOW_FROM("ALLOW-FROM");
+ DENY("DENY"), SAME_ORIGIN("SAMEORIGIN"), ALLOW_FROM("ALLOW-FROM");
private final String headerValue;
diff --git a/java/org/apache/catalina/filters/RemoteAddrFilter.java b/java/org/apache/catalina/filters/RemoteAddrFilter.java
index b179426e07..991bcf8e60 100644
--- a/java/org/apache/catalina/filters/RemoteAddrFilter.java
+++ b/java/org/apache/catalina/filters/RemoteAddrFilter.java
@@ -27,11 +27,10 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
- * Concrete implementation of <code>RequestFilter</code> that filters
- * based on the string representation of the remote client's IP address.
+ * Concrete implementation of <code>RequestFilter</code> that filters based on the string representation of the remote
+ * client's IP address.
*
* @author Craig R. McClanahan
- *
*/
public final class RemoteAddrFilter extends RequestFilter {
@@ -41,21 +40,19 @@ public final class RemoteAddrFilter extends RequestFilter {
/**
- * Extract the desired request property, and pass it (along with the
- * specified request and response objects and associated filter chain) to
- * the protected <code>process()</code> method to perform the actual
- * filtering.
+ * Extract the desired request property, and pass it (along with the specified request and response objects and
+ * associated filter chain) to the protected <code>process()</code> method to perform the actual filtering.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
* @param chain The filter chain for this request
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
process(request.getRemoteAddr(), request, response, chain);
diff --git a/java/org/apache/catalina/filters/RemoteCIDRFilter.java b/java/org/apache/catalina/filters/RemoteCIDRFilter.java
index edbe6d8052..2187c49bec 100644
--- a/java/org/apache/catalina/filters/RemoteCIDRFilter.java
+++ b/java/org/apache/catalina/filters/RemoteCIDRFilter.java
@@ -37,8 +37,8 @@ import org.apache.juli.logging.LogFactory;
public final class RemoteCIDRFilter extends FilterBase {
/**
- * text/plain MIME type: this is the MIME type we return when a
- * {@link ServletResponse} is not an {@link HttpServletResponse}
+ * text/plain MIME type: this is the MIME type we return when a {@link ServletResponse} is not an
+ * {@link HttpServletResponse}
*/
private static final String PLAIN_TEXT_MIME_TYPE = "text/plain";
@@ -61,8 +61,7 @@ public final class RemoteCIDRFilter extends FilterBase {
/**
* Return a string representation of the {@link NetMask} list in #allow.
*
- * @return the #allow list as a string, without the leading '[' and trailing
- * ']'
+ * @return the #allow list as a string, without the leading '[' and trailing ']'
*/
public String getAllow() {
return allow.toString().replace("[", "").replace("]", "");
@@ -70,10 +69,10 @@ public final class RemoteCIDRFilter extends FilterBase {
/**
- * Fill the #allow list with the list of netmasks provided as an argument,
- * if any. Calls #fillFromInput.
+ * Fill the #allow list with the list of netmasks provided as an argument, if any. Calls #fillFromInput.
*
* @param input The list of netmasks, as a comma separated string
+ *
* @throws IllegalArgumentException One or more netmasks are invalid
*/
public void setAllow(final String input) {
@@ -94,8 +93,7 @@ public final class RemoteCIDRFilter extends FilterBase {
/**
* Return a string representation of the {@link NetMask} list in #deny.
*
- * @return the #deny list as string, without the leading '[' and trailing
- * ']'
+ * @return the #deny list as string, without the leading '[' and trailing ']'
*/
public String getDeny() {
return deny.toString().replace("[", "").replace("]", "");
@@ -103,10 +101,10 @@ public final class RemoteCIDRFilter extends FilterBase {
/**
- * Fill the #deny list with the list of netmasks provided as an argument, if
- * any. Calls #fillFromInput.
+ * Fill the #deny list with the list of netmasks provided as an argument, if any. Calls #fillFromInput.
*
* @param input The list of netmasks, as a comma separated string
+ *
* @throws IllegalArgumentException One or more netmasks are invalid
*/
public void setDeny(final String input) {
@@ -124,7 +122,6 @@ public final class RemoteCIDRFilter extends FilterBase {
}
-
@Override
protected boolean isConfigProblemFatal() {
// Failure to configure a security related component should always be
@@ -161,6 +158,7 @@ public final class RemoteCIDRFilter extends FilterBase {
* Test if a remote's IP address is allowed to proceed.
*
* @param property The remote's IP address, as a string
+ *
* @return true if allowed
*/
private boolean isAllowed(final String property) {
@@ -206,11 +204,12 @@ public final class RemoteCIDRFilter extends FilterBase {
/**
- * Fill a {@link NetMask} list from a string input containing a
- * comma-separated list of (hopefully valid) {@link NetMask}s.
+ * Fill a {@link NetMask} list from a string input containing a comma-separated list of (hopefully valid)
+ * {@link NetMask}s.
*
- * @param input The input string
+ * @param input The input string
* @param target The list to fill
+ *
* @return a string list of processing errors (empty when no errors)
*/
private List<String> fillFromInput(final String input, final List<NetMask> target) {
diff --git a/java/org/apache/catalina/filters/RemoteHostFilter.java b/java/org/apache/catalina/filters/RemoteHostFilter.java
index 12318bed01..63c4a931cc 100644
--- a/java/org/apache/catalina/filters/RemoteHostFilter.java
+++ b/java/org/apache/catalina/filters/RemoteHostFilter.java
@@ -27,11 +27,9 @@ import org.apache.juli.logging.Log;
import org.apache.juli.logging.LogFactory;
/**
- * Concrete implementation of <code>RequestFilter</code> that filters
- * based on the remote client's host name.
+ * Concrete implementation of <code>RequestFilter</code> that filters based on the remote client's host name.
*
* @author Craig R. McClanahan
- *
*/
public final class RemoteHostFilter extends RequestFilter {
@@ -41,21 +39,19 @@ public final class RemoteHostFilter extends RequestFilter {
/**
- * Extract the desired request property, and pass it (along with the
- * specified request and response objects and associated filter chain) to
- * the protected <code>process()</code> method to perform the actual
- * filtering.
+ * Extract the desired request property, and pass it (along with the specified request and response objects and
+ * associated filter chain) to the protected <code>process()</code> method to perform the actual filtering.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
* @param chain The filter chain for this request
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
process(request.getRemoteHost(), request, response, chain);
diff --git a/java/org/apache/catalina/filters/RemoteIpFilter.java b/java/org/apache/catalina/filters/RemoteIpFilter.java
index 28c692202d..95dac6e85f 100644
--- a/java/org/apache/catalina/filters/RemoteIpFilter.java
+++ b/java/org/apache/catalina/filters/RemoteIpFilter.java
@@ -57,25 +57,26 @@ import org.apache.tomcat.util.res.StringManager;
* 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").
+ * 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").
+ * 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:
+ * 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>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>
@@ -83,12 +84,13 @@ import org.apache.tomcat.util.res.StringManager;
* <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> (default value <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>
+ * <li>If the request http header named <code>$protocolHeader</code> (default value <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>
@@ -101,52 +103,47 @@ import org.apache.tomcat.util.res.StringManager;
* </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>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>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>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>
+ * 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>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>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>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>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or
+ * <code>Front-End-Https</code></td>
* <td><code>X-Forwarded-Proto</code></td>
* </tr>
* <tr>
@@ -158,14 +155,16 @@ import org.apache.tomcat.util.res.StringManager;
* </tr>
* <tr>
* <td>httpServerPort</td>
- * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</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>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>
@@ -179,11 +178,11 @@ import org.apache.tomcat.util.res.StringManager;
* </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.
+ * <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>
@@ -322,8 +321,9 @@ import org.apache.tomcat.util.res.StringManager;
* </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.
+ * 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>
@@ -383,9 +383,10 @@ import org.apache.tomcat.util.res.StringManager;
* </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.
+ * 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>
@@ -447,8 +448,8 @@ import org.apache.tomcat.util.res.StringManager;
* <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>.
+ * <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>
*/
@@ -698,11 +699,12 @@ public class RemoteIpFilter extends GenericFilter {
* 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);
+ return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0]
+ : commaSeparatedValuesPattern.split(commaDelimitedStrings);
}
/**
@@ -718,15 +720,11 @@ public class RemoteIpFilter extends GenericFilter {
/**
* @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");
+ 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)
@@ -765,13 +763,12 @@ public class RemoteIpFilter extends GenericFilter {
private boolean enableLookups;
- public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
+ public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
- boolean isInternal = internalProxies != null &&
- internalProxies.matcher(request.getRemoteAddr()).matches();
+ boolean isInternal = internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches();
- if (isInternal || (trustedProxies != null &&
- trustedProxies.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();
@@ -793,10 +790,9 @@ public class RemoteIpFilter extends GenericFilter {
for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) {
String currentRemoteIp = remoteIpHeaderValue[idx];
remoteIp = currentRemoteIp;
- if (internalProxies !=null && internalProxies.matcher(currentRemoteIp).matches()) {
+ if (internalProxies != null && internalProxies.matcher(currentRemoteIp).matches()) {
// do nothing, internalProxies IPs are not appended to the
- } else if (trustedProxies != null &&
- trustedProxies.matcher(currentRemoteIp).matches()) {
+ } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) {
proxiesHeaderValue.addFirst(currentRemoteIp);
} else {
idx--; // decrement idx because break statement doesn't do it
@@ -884,34 +880,28 @@ public class RemoteIpFilter extends GenericFilter {
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() +
+ 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()));
+ 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() + "'");
+ log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" +
+ request.getRemoteAddr() + "'");
}
chain.doFilter(request, response);
}
@@ -919,8 +909,7 @@ public class RemoteIpFilter extends GenericFilter {
}
/*
- * Considers the value to be secure if it exclusively holds forwards for
- * {@link #protocolHeaderHttpsValue}.
+ * Considers the value to be secure if it exclusively holds forwards for {@link #protocolHeaderHttpsValue}.
*/
private boolean isForwardedProtoHeaderValueSecure(String protocolHeaderValue) {
if (!protocolHeaderValue.contains(",")) {
@@ -946,8 +935,8 @@ public class RemoteIpFilter extends GenericFilter {
try {
port = Integer.parseInt(portHeaderValue);
} catch (NumberFormatException nfe) {
- log.debug("Invalid port value [" + portHeaderValue +
- "] provided in header [" + getPortHeader() + "]");
+ log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() +
+ "]");
}
}
}
@@ -958,13 +947,14 @@ public class RemoteIpFilter extends GenericFilter {
}
/**
- * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwarded-for</code> is not empty.
- * {@inheritDoc}
+ * 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 {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
- doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain);
+ doFilter((HttpServletRequest) request, (HttpServletResponse) response, chain);
} else {
chain.doFilter(request, response);
}
@@ -1008,8 +998,8 @@ public class RemoteIpFilter extends GenericFilter {
/**
* @see #setRequestAttributesEnabled(boolean)
- * @return <code>true</code> if the attributes will be logged, otherwise
- * <code>false</code>
+ *
+ * @return <code>true</code> if the attributes will be logged, otherwise <code>false</code>
*/
public boolean getRequestAttributesEnabled() {
return requestAttributesEnabled;
@@ -1069,7 +1059,8 @@ public class RemoteIpFilter extends GenericFilter {
try {
setHttpServerPort(Integer.parseInt(getInitParameter(HTTP_SERVER_PORT_PARAMETER)));
} catch (NumberFormatException e) {
- throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber", HTTP_SERVER_PORT_PARAMETER, e.getLocalizedMessage()));
+ throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber", HTTP_SERVER_PORT_PARAMETER,
+ e.getLocalizedMessage()));
}
}
@@ -1077,7 +1068,8 @@ public class RemoteIpFilter extends GenericFilter {
try {
setHttpsServerPort(Integer.parseInt(getInitParameter(HTTPS_SERVER_PORT_PARAMETER)));
} catch (NumberFormatException e) {
- throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber", HTTPS_SERVER_PORT_PARAMETER, e.getLocalizedMessage()));
+ throw new NumberFormatException(sm.getString("remoteIpFilter.invalidNumber",
+ HTTPS_SERVER_PORT_PARAMETER, e.getLocalizedMessage()));
}
}
@@ -1088,14 +1080,14 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * If <code>true</code>, the return values for both {@link
- * ServletRequest#getLocalName()} and {@link ServletRequest#getServerName()}
- * will be modified by this Filter rather than just
+ * If <code>true</code>, the return values for both {@link ServletRequest#getLocalName()} and
+ * {@link ServletRequest#getServerName()} will be modified by this Filter rather than just
* {@link ServletRequest#getServerName()}.
* </p>
* <p>
* Default value : <code>false</code>
* </p>
+ *
* @param changeLocalName The new flag value
*/
public void setChangeLocalName(boolean changeLocalName) {
@@ -1104,14 +1096,14 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * If <code>true</code>, the return values for both {@link
- * ServletRequest#getLocalPort()} and {@link ServletRequest#getServerPort()}
- * will be modified by this Filter rather than just
+ * If <code>true</code>, the return values for both {@link ServletRequest#getLocalPort()} and
+ * {@link ServletRequest#getServerPort()} will be modified by this Filter rather than just
* {@link ServletRequest#getServerPort()}.
* </p>
* <p>
* Default value : <code>false</code>
* </p>
+ *
* @param changeLocalPort The new flag value
*/
public void setChangeLocalPort(boolean changeLocalPort) {
@@ -1120,12 +1112,13 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and
- * has a value different of {@link #protocolHeaderHttpsValue}).
+ * Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and has
+ * a value different of {@link #protocolHeaderHttpsValue}).
* </p>
* <p>
* Default value : 80
* </p>
+ *
* @param httpServerPort The server port to use
*/
public void setHttpServerPort(int httpServerPort) {
@@ -1139,6 +1132,7 @@ public class RemoteIpFilter extends GenericFilter {
* <p>
* Default value : 443
* </p>
+ *
* @param httpsServerPort The server port to use
*/
public void setHttpsServerPort(int httpsServerPort) {
@@ -1150,8 +1144,10 @@ public class RemoteIpFilter extends GenericFilter {
* Regular expression that defines the internal proxies.
* </p>
* <p>
- * Default value : 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}|0:0:0:0:0:0:0:1
+ * Default value :
+ * 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}|0:0:0:0:0:0:0:1
* </p>
+ *
* @param internalProxies The regexp
*/
public void setInternalProxies(String internalProxies) {
@@ -1164,12 +1160,12 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * Header that holds the incoming host, usually named
- * <code>X-Forwarded-Host</code>.
+ * Header that holds the incoming host, usually named <code>X-Forwarded-Host</code>.
* </p>
* <p>
* Default value : <code>null</code>
* </p>
+ *
* @param hostHeader The header name
*/
public void setHostHeader(String hostHeader) {
@@ -1178,13 +1174,13 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * Header that holds the incoming port, usually named
- * <code>X-Forwarded-Port</code>. If <code>null</code>,
+ * Header that holds the incoming port, usually named <code>X-Forwarded-Port</code>. If <code>null</code>,
* {@link #httpServerPort} or {@link #httpsServerPort} will be used.
* </p>
* <p>
* Default value : <code>null</code>
* </p>
+ *
* @param portHeader The header name
*/
public void setPortHeader(String portHeader) {
@@ -1193,12 +1189,13 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * Header that holds the incoming protocol, usually named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and
- * request.secure will not be modified.
+ * Header that holds the incoming protocol, usually named <code>X-Forwarded-Proto</code>. If <code>null</code>,
+ * request.scheme and request.secure will not be modified.
* </p>
* <p>
* Default value : <code>X-Forwarded-Proto</code>
* </p>
+ *
* @param protocolHeader The header name
*/
public void setProtocolHeader(String protocolHeader) {
@@ -1212,6 +1209,7 @@ public class RemoteIpFilter extends GenericFilter {
* <p>
* Default value : <code>https</code>
* </p>
+ *
* @param protocolHeaderHttpsValue The header value
*/
public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) {
@@ -1220,9 +1218,10 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP
- * addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header,
- * while any intermediate RemoteIPInternalProxy addresses are discarded.
+ * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the
+ * intermediate client IP addresses trusted to resolve the actual remote IP. Note that intermediate
+ * RemoteIPTrustedProxy addresses are recorded in this header, while any intermediate RemoteIPInternalProxy
+ * addresses are discarded.
* </p>
* <p>
* Name of the http header that holds the list of trusted proxies that has been traversed by the http request.
@@ -1233,6 +1232,7 @@ public class RemoteIpFilter extends GenericFilter {
* <p>
* Default value : <code>X-Forwarded-By</code>
* </p>
+ *
* @param proxiesHeader The header name
*/
public void setProxiesHeader(String proxiesHeader) {
@@ -1249,6 +1249,7 @@ public class RemoteIpFilter extends GenericFilter {
* <p>
* Default value : <code>X-Forwarded-For</code>
* </p>
+ *
* @param remoteIpHeader The header name
*/
public void setRemoteIpHeader(String remoteIpHeader) {
@@ -1256,12 +1257,9 @@ public class RemoteIpFilter extends GenericFilter {
}
/**
- * Should this filter set request attributes for IP address, Hostname,
- * protocol and port used for the request? This are typically used in
- * conjunction with an {@link AccessLog} which will otherwise log the
- * original values. Default is <code>true</code>.
- *
- * The attributes set are:
+ * Should this filter set request attributes for IP address, Hostname, protocol and port used for the request? This
+ * are typically used in conjunction with an {@link AccessLog} which will otherwise log the original values. Default
+ * is <code>true</code>. The attributes set are:
* <ul>
* <li>org.apache.catalina.AccessLog.RemoteAddr</li>
* <li>org.apache.catalina.AccessLog.RemoteHost</li>
@@ -1270,9 +1268,8 @@ public class RemoteIpFilter extends GenericFilter {
* <li>org.apache.tomcat.remoteAddr</li>
* </ul>
*
- * @param requestAttributesEnabled <code>true</code> causes the attributes
- * to be set, <code>false</code> disables
- * the setting of the attributes.
+ * @param requestAttributesEnabled <code>true</code> causes the attributes to be set, <code>false</code> disables
+ * the setting of the attributes.
*/
public void setRequestAttributesEnabled(boolean requestAttributesEnabled) {
this.requestAttributesEnabled = requestAttributesEnabled;
@@ -1280,12 +1277,12 @@ public class RemoteIpFilter extends GenericFilter {
/**
* <p>
- * Regular expression defining proxies that are trusted when they appear in
- * the {@link #remoteIpHeader} header.
+ * Regular expression defining proxies that are trusted when they appear in the {@link #remoteIpHeader} header.
* </p>
* <p>
* Default value : empty list, no external proxy is trusted.
* </p>
+ *
* @param trustedProxies The trusted proxies regexp
*/
public void setTrustedProxies(String trustedProxies) {
@@ -1301,9 +1298,8 @@ public class RemoteIpFilter extends GenericFilter {
}
/*
- * Log objects are not Serializable but this Filter is because it extends
- * GenericFilter. Tomcat won't serialize a Filter but in case something else
- * does...
+ * Log objects are not Serializable but this Filter is because it extends GenericFilter. Tomcat won't serialize a
+ * Filter but in case something else does...
*/
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
diff --git a/java/org/apache/catalina/filters/RequestDumperFilter.java b/java/org/apache/catalina/filters/RequestDumperFilter.java
index 83adb4ce6b..fc76581a4d 100644
--- a/java/org/apache/catalina/filters/RequestDumperFilter.java
+++ b/java/org/apache/catalina/filters/RequestDumperFilter.java
@@ -36,15 +36,16 @@ import org.apache.juli.logging.LogFactory;
/**
- * <p>Implementation of a Filter that logs interesting contents from the
- * specified Request (before processing) and the corresponding Response
- * (after processing). It is especially useful in debugging problems
- * related to headers and cookies.</p>
- *
- * <p>When using this Filter, it is strongly recommended that the
- * <code>org.apache.catalina.filter.RequestDumperFilter</code> logger is
- * directed to a dedicated file and that the
- * <code>org.apache.juli.VerbatimFormatter</code> is used.</p>
+ * <p>
+ * Implementation of a Filter that logs interesting contents from the specified Request (before processing) and the
+ * corresponding Response (after processing). It is especially useful in debugging problems related to headers and
+ * cookies.
+ * </p>
+ * <p>
+ * When using this Filter, it is strongly recommended that the
+ * <code>org.apache.catalina.filter.RequestDumperFilter</code> logger is directed to a dedicated file and that the
+ * <code>org.apache.juli.VerbatimFormatter</code> is used.
+ * </p>
*
* @author Craig R. McClanahan
*/
@@ -52,10 +53,8 @@ public class RequestDumperFilter extends GenericFilter {
private static final long serialVersionUID = 1L;
- private static final String NON_HTTP_REQ_MSG =
- "Not available. Non-http request.";
- private static final String NON_HTTP_RES_MSG =
- "Not available. Non-http response.";
+ private static final String NON_HTTP_REQ_MSG = "Not available. Non-http request.";
+ private static final String NON_HTTP_RES_MSG = "Not available. Non-http response.";
private static final ThreadLocal<Timestamp> timestamp = ThreadLocal.withInitial(Timestamp::new);
@@ -65,20 +64,19 @@ public class RequestDumperFilter extends GenericFilter {
/**
- * Log the interesting request parameters, invoke the next Filter in the
- * sequence, and log the interesting response parameters.
+ * Log the interesting request parameters, invoke the next Filter in the sequence, and log the interesting response
+ * parameters.
*
* @param request The servlet request to be processed
* @param response The servlet response to be created
* @param chain The filter chain being processed
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain)
- throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
HttpServletRequest hRequest = null;
HttpServletResponse hResponse = null;
@@ -102,8 +100,7 @@ public class RequestDumperFilter extends GenericFilter {
}
doLog(" characterEncoding", request.getCharacterEncoding());
- doLog(" contentLength",
- Long.toString(request.getContentLengthLong()));
+ doLog(" contentLength", Long.toString(request.getContentLengthLong()));
doLog(" contentType", request.getContentType());
if (hRequest == null) {
@@ -115,8 +112,7 @@ public class RequestDumperFilter extends GenericFilter {
Cookie cookies[] = hRequest.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
- doLog(" cookie", cookie.getName() +
- "=" + cookie.getValue());
+ doLog(" cookie", cookie.getName() + "=" + cookie.getValue());
}
}
Enumeration<String> hnames = hRequest.getHeaderNames();
@@ -180,8 +176,7 @@ public class RequestDumperFilter extends GenericFilter {
doLog(" scheme", request.getScheme());
doLog(" serverName", request.getServerName());
- doLog(" serverPort",
- Integer.toString(request.getServerPort()));
+ doLog(" serverPort", Integer.toString(request.getServerPort()));
if (hRequest == null) {
doLog(" servletPath", NON_HTTP_REQ_MSG);
@@ -189,17 +184,14 @@ public class RequestDumperFilter extends GenericFilter {
doLog(" servletPath", hRequest.getServletPath());
}
- doLog(" isSecure",
- Boolean.valueOf(request.isSecure()).toString());
- doLog("------------------",
- "--------------------------------------------");
+ doLog(" isSecure", Boolean.valueOf(request.isSecure()).toString());
+ doLog("------------------", "--------------------------------------------");
// Perform the request
chain.doFilter(request, response);
// Log post-service information
- doLog("------------------",
- "--------------------------------------------");
+ doLog("------------------", "--------------------------------------------");
if (hRequest == null) {
doLog(" authType", NON_HTTP_REQ_MSG);
} else {
@@ -229,13 +221,11 @@ public class RequestDumperFilter extends GenericFilter {
if (hResponse == null) {
doLog(" status", NON_HTTP_RES_MSG);
} else {
- doLog(" status",
- Integer.toString(hResponse.getStatus()));
+ doLog(" status", Integer.toString(hResponse.getStatus()));
}
doLog("END TIME ", getTimestamp());
- doLog("==================",
- "============================================");
+ doLog("==================", "============================================");
}
private void doLog(String attribute, String value) {
@@ -261,9 +251,8 @@ public class RequestDumperFilter extends GenericFilter {
/*
- * Log objects are not Serializable but this Filter is because it extends
- * GenericFilter. Tomcat won't serialize a Filter but in case something else
- * does...
+ * Log objects are not Serializable but this Filter is because it extends GenericFilter. Tomcat won't serialize a
+ * Filter but in case something else does...
*/
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
@@ -273,9 +262,9 @@ public class RequestDumperFilter extends GenericFilter {
private static final class Timestamp {
private final Date date = new Date(0);
- private final SimpleDateFormat format =
- new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
+ private final SimpleDateFormat format = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
private String dateString = format.format(date);
+
private void update() {
dateString = format.format(date);
}
diff --git a/java/org/apache/catalina/filters/RequestFilter.java b/java/org/apache/catalina/filters/RequestFilter.java
index 1fb04cf9d7..de1651caad 100644
--- a/java/org/apache/catalina/filters/RequestFilter.java
+++ b/java/org/apache/catalina/filters/RequestFilter.java
@@ -28,27 +28,21 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
- * Implementation of a Filter that performs filtering based on comparing the
- * appropriate request property (selected based on which subclass you choose
- * to configure into your Container's pipeline) against the regular expressions
+ * Implementation of a Filter that performs filtering based on comparing the appropriate request property (selected
+ * based on which subclass you choose to configure into your Container's pipeline) against the regular expressions
* configured for this Filter.
* <p>
- * This filter is configured by setting the <code>allow</code> and/or
- * <code>deny</code> properties to a regular expressions (in the syntax
- * supported by {@link Pattern}) to which the appropriate request property will
- * be compared. Evaluation proceeds as follows:
+ * This filter is configured by setting the <code>allow</code> and/or <code>deny</code> properties to a regular
+ * expressions (in the syntax supported by {@link Pattern}) to which the appropriate request property will be compared.
+ * Evaluation proceeds as follows:
* <ul>
- * <li>The subclass extracts the request property to be filtered, and
- * calls the common <code>process()</code> method.
- * <li>If there is a deny expression configured, the property will be compared
- * to the expression. If a match is found, this request will be rejected
- * with a "Forbidden" HTTP response.</li>
- * <li>If there is a allow expression configured, the property will be compared
- * to the expression. If a match is found, this request will be allowed to
- * pass through to the next filter in the current pipeline.</li>
- * <li>If a deny expression was specified but no allow expression, allow this
- * request to pass through (because none of the deny expressions matched
- * it).
+ * <li>The subclass extracts the request property to be filtered, and calls the common <code>process()</code> method.
+ * <li>If there is a deny expression configured, the property will be compared to the expression. If a match is found,
+ * this request will be rejected with a "Forbidden" HTTP response.</li>
+ * <li>If there is a allow expression configured, the property will be compared to the expression. If a match is found,
+ * this request will be allowed to pass through to the next filter in the current pipeline.</li>
+ * <li>If a deny expression was specified but no allow expression, allow this request to pass through (because none of
+ * the deny expressions matched it).
* <li>The request will be rejected with a "Forbidden" HTTP response.</li>
* </ul>
*/
@@ -68,8 +62,8 @@ public abstract class RequestFilter extends FilterBase {
protected Pattern deny = null;
/**
- * The HTTP response status code that is used when rejecting denied
- * request. It is 403 by default, but may be changed to be 404.
+ * The HTTP response status code that is used when rejecting denied request. It is 403 by default, but may be
+ * changed to be 404.
*/
protected int denyStatus = HttpServletResponse.SC_FORBIDDEN;
@@ -83,8 +77,8 @@ public abstract class RequestFilter extends FilterBase {
/**
- * @return the regular expression used to test for allowed requests for this
- * Filter, if any; otherwise, return <code>null</code>.
+ * @return the regular expression used to test for allowed requests for this Filter, if any; otherwise, return
+ * <code>null</code>.
*/
public String getAllow() {
if (allow == null) {
@@ -95,8 +89,7 @@ public abstract class RequestFilter extends FilterBase {
/**
- * Set the regular expression used to test for allowed requests for this
- * Filter, if any.
+ * Set the regular expression used to test for allowed requests for this Filter, if any.
*
* @param allow The new allow expression
*/
@@ -110,8 +103,8 @@ public abstract class RequestFilter extends FilterBase {
/**
- * @return the regular expression used to test for denied requests for this
- * Filter, if any; otherwise, return <code>null</code>.
+ * @return the regular expression used to test for denied requests for this Filter, if any; otherwise, return
+ * <code>null</code>.
*/
public String getDeny() {
if (deny == null) {
@@ -122,8 +115,7 @@ public abstract class RequestFilter extends FilterBase {
/**
- * Set the regular expression used to test for denied requests for this
- * Filter, if any.
+ * Set the regular expression used to test for denied requests for this Filter, if any.
*
* @param deny The new deny expression
*/
@@ -158,22 +150,20 @@ public abstract class RequestFilter extends FilterBase {
/**
- * Extract the desired request property, and pass it (along with the
- * specified request and response objects) to the protected
- * <code>process()</code> method to perform the actual filtering.
- * This method must be implemented by a concrete subclass.
+ * Extract the desired request property, and pass it (along with the specified request and response objects) to the
+ * protected <code>process()</code> method to perform the actual filtering. This method must be implemented by a
+ * concrete subclass.
*
- * @param request The servlet request to be processed
+ * @param request The servlet request to be processed
* @param response The servlet response to be created
- * @param chain The filter chain
+ * @param chain The filter chain
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
- public abstract void doFilter(ServletRequest request,
- ServletResponse response, FilterChain chain) throws IOException,
- ServletException;
+ public abstract void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException;
// ------------------------------------------------------ Protected Methods
@@ -186,19 +176,17 @@ public abstract class RequestFilter extends FilterBase {
/**
- * Perform the filtering that has been configured for this Filter, matching
- * against the specified request property.
+ * Perform the filtering that has been configured for this Filter, matching against the specified request property.
*
* @param property The request property on which to filter
- * @param request The servlet request to be processed
+ * @param request The servlet request to be processed
* @param response The servlet response to be processed
- * @param chain The filter chain
+ * @param chain The filter chain
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
- protected void process(String property, ServletRequest request,
- ServletResponse response, FilterChain chain)
+ protected void process(String property, ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
if (isAllowed(property)) {
@@ -206,8 +194,8 @@ public abstract class RequestFilter extends FilterBase {
} else {
if (response instanceof HttpServletResponse) {
if (getLogger().isDebugEnabled()) {
- getLogger().debug(sm.getString("requestFilter.deny",
- ((HttpServletRequest) request).getRequestURI(), property));
+ getLogger().debug(sm.getString("requestFilter.deny", ((HttpServletRequest) request).getRequestURI(),
+ property));
}
((HttpServletResponse) response).sendError(denyStatus);
} else {
@@ -220,9 +208,9 @@ public abstract class RequestFilter extends FilterBase {
/**
* Process the allow and deny rules for the provided property.
*
- * @param property The property to test against the allow and deny lists
- * @return <code>true</code> if this request should be allowed,
- * <code>false</code> otherwise
+ * @param property The property to test against the allow and deny lists
+ *
+ * @return <code>true</code> if this request should be allowed, <code>false</code> otherwise
*/
private boolean isAllowed(String property) {
if (deny != null && deny.matcher(property).matches()) {
@@ -243,8 +231,7 @@ public abstract class RequestFilter extends FilterBase {
return false;
}
- private void sendErrorWhenNotHttp(ServletResponse response)
- throws IOException {
+ private void sendErrorWhenNotHttp(ServletResponse response) throws IOException {
response.setContentType(PLAIN_TEXT_MIME_TYPE);
response.getWriter().write(sm.getString("http.403"));
response.getWriter().flush();
diff --git a/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java b/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java
index a0a0c666e9..f542976f4d 100644
--- a/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java
+++ b/java/org/apache/catalina/filters/RestCsrfPreventionFilter.java
@@ -34,9 +34,8 @@ import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
/**
- * Provides basic CSRF protection for REST APIs. The filter assumes that the
- * clients have adapted the transfer of the nonce through the 'X-CSRF-Token'
- * header.
+ * Provides basic CSRF protection for REST APIs. The filter assumes that the clients have adapted the transfer of the
+ * nonce through the 'X-CSRF-Token' header.
*
* <pre>
* Positive scenario:
@@ -95,8 +94,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
super.init(filterConfig);
// Put the expected request header name into the application scope
- filterConfig.getServletContext().setAttribute(
- Constants.CSRF_REST_NONCE_HEADER_NAME_KEY,
+ filterConfig.getServletContext().setAttribute(Constants.CSRF_REST_NONCE_HEADER_NAME_KEY,
Constants.CSRF_REST_NONCE_HEADER_NAME);
}
@@ -104,8 +102,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
- if (request instanceof HttpServletRequest &&
- response instanceof HttpServletResponse) {
+ if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {
MethodType mType = MethodType.MODIFYING_METHOD;
if (nonModifyingMethods.test(((HttpServletRequest) request).getMethod())) {
mType = MethodType.NON_MODIFYING_METHOD;
@@ -113,12 +110,12 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
RestCsrfPreventionStrategy strategy;
switch (mType) {
- case NON_MODIFYING_METHOD:
- strategy = new FetchRequest();
- break;
- default:
- strategy = new StateChangingRequest();
- break;
+ case NON_MODIFYING_METHOD:
+ strategy = new FetchRequest();
+ break;
+ default:
+ strategy = new StateChangingRequest();
+ break;
}
if (!strategy.apply((HttpServletRequest) request, (HttpServletResponse) response)) {
@@ -131,8 +128,8 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
private static interface RestCsrfPreventionStrategy {
static final NonceSupplier<HttpServletRequest, String> nonceFromRequestHeader = HttpServletRequest::getHeader;
static final NonceSupplier<HttpServletRequest, String[]> nonceFromRequestParams = ServletRequest::getParameterValues;
- static final NonceSupplier<HttpSession, String> nonceFromSession = (s, k) -> Objects
- .isNull(s) ? null : (String) s.getAttribute(k);
+ static final NonceSupplier<HttpSession, String> nonceFromSession = (s, k) -> Objects.isNull(s) ? null
+ : (String) s.getAttribute(k);
static final NonceConsumer<HttpServletResponse> nonceToResponse = HttpServletResponse::setHeader;
static final NonceConsumer<HttpSession> nonceToSession = HttpSession::setAttribute;
@@ -143,8 +140,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
private class StateChangingRequest implements RestCsrfPreventionStrategy {
@Override
- public boolean apply(HttpServletRequest request, HttpServletResponse response)
- throws IOException {
+ public boolean apply(HttpServletRequest request, HttpServletResponse response) throws IOException {
String nonceRequest = extractNonceFromRequest(request);
HttpSession session = request.getSession(false);
@@ -160,23 +156,21 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
if (getLogger().isDebugEnabled()) {
getLogger().debug(sm.getString("restCsrfPreventionFilter.invalidNonce.debug", request.getMethod(),
- request.getRequestURI(), Boolean.valueOf(request.getRequestedSessionId() != null),
- session, Boolean.valueOf(nonceRequest != null), Boolean.valueOf(nonceSession != null)));
+ request.getRequestURI(), Boolean.valueOf(request.getRequestedSessionId() != null), session,
+ Boolean.valueOf(nonceRequest != null), Boolean.valueOf(nonceSession != null)));
}
return false;
}
private boolean isValidStateChangingRequest(String reqNonce, String sessionNonce) {
- return Objects.nonNull(reqNonce) && Objects.nonNull(sessionNonce)
- && Objects.equals(reqNonce, sessionNonce);
+ return Objects.nonNull(reqNonce) && Objects.nonNull(sessionNonce) && Objects.equals(reqNonce, sessionNonce);
}
private String extractNonceFromRequest(HttpServletRequest request) {
- String nonceFromRequest = nonceFromRequestHeader.getNonce(request,
- Constants.CSRF_REST_NONCE_HEADER_NAME);
- if ((Objects.isNull(nonceFromRequest) || Objects.equals("", nonceFromRequest))
- && !getPathsAcceptingParams().isEmpty()
- && getPathsAcceptingParams().contains(getRequestedPath(request))) {
+ String nonceFromRequest = nonceFromRequestHeader.getNonce(request, Constants.CSRF_REST_NONCE_HEADER_NAME);
+ if ((Objects.isNull(nonceFromRequest) || Objects.equals("", nonceFromRequest)) &&
+ !getPathsAcceptingParams().isEmpty() &&
+ getPathsAcceptingParams().contains(getRequestedPath(request))) {
nonceFromRequest = extractNonceFromRequestParams(request);
}
return nonceFromRequest;
@@ -206,8 +200,7 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
@Override
public boolean apply(HttpServletRequest request, HttpServletResponse response) {
- if (fetchRequest.test(
- nonceFromRequestHeader.getNonce(request, Constants.CSRF_REST_NONCE_HEADER_NAME))) {
+ if (fetchRequest.test(nonceFromRequestHeader.getNonce(request, Constants.CSRF_REST_NONCE_HEADER_NAME))) {
String nonceFromSessionStr = nonceFromSession.getNonce(request.getSession(false),
Constants.CSRF_REST_NONCE_SESSION_ATTR_NAME);
if (nonceFromSessionStr == null) {
@@ -215,11 +208,10 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
nonceToSession.setNonce(Objects.requireNonNull(request.getSession(true)),
Constants.CSRF_REST_NONCE_SESSION_ATTR_NAME, nonceFromSessionStr);
}
- nonceToResponse.setNonce(response, Constants.CSRF_REST_NONCE_HEADER_NAME,
- nonceFromSessionStr);
+ nonceToResponse.setNonce(response, Constants.CSRF_REST_NONCE_HEADER_NAME, nonceFromSessionStr);
if (getLogger().isDebugEnabled()) {
- getLogger().debug(sm.getString("restCsrfPreventionFilter.fetch.debug",
- request.getMethod(), request.getRequestURI()));
+ getLogger().debug(sm.getString("restCsrfPreventionFilter.fetch.debug", request.getMethod(),
+ request.getRequestURI()));
}
}
return true;
@@ -238,21 +230,17 @@ public class RestCsrfPreventionFilter extends CsrfPreventionFilterBase {
}
/**
- * A comma separated list of URLs that can accept nonces via request
- * parameter 'X-CSRF-Token'. For use cases when a nonce information cannot
- * be provided via header, one can provide it via request parameters. If
- * there is a X-CSRF-Token header, it will be taken with preference over any
- * parameter with the same name in the request. Request parameters cannot be
- * used to fetch new nonce, only header.
+ * A comma separated list of URLs that can accept nonces via request parameter 'X-CSRF-Token'. For use cases when a
+ * nonce information cannot be provided via header, one can provide it via request parameters. If there is a
+ * X-CSRF-Token header, it will be taken with preference over any parameter with the same name in the request.
+ * Request parameters cannot be used to fetch new nonce, only header.
*
- * @param pathsList
- * Comma separated list of URLs to be configured as paths
- * accepting request parameters with nonce information.
+ * @param pathsList Comma separated list of URLs to be configured as paths accepting request parameters with nonce
+ * information.
*/
public void setPathsAcceptingParams(String pathsList) {
if (Objects.nonNull(pathsList)) {
- Arrays.asList(pathsList.split(pathsDelimiter)).forEach(
- e -> pathsAcceptingParams.add(e.trim()));
+ Arrays.asList(pathsList.split(pathsDelimiter)).forEach(e -> pathsAcceptingParams.add(e.trim()));
}
}
diff --git a/java/org/apache/catalina/filters/SessionInitializerFilter.java b/java/org/apache/catalina/filters/SessionInitializerFilter.java
index 0e4bc9a5ea..db7347cb28 100644
--- a/java/org/apache/catalina/filters/SessionInitializerFilter.java
+++ b/java/org/apache/catalina/filters/SessionInitializerFilter.java
@@ -27,33 +27,30 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
/**
- * A {@link jakarta.servlet.Filter} that initializes the {@link HttpSession} for
- * the {@link HttpServletRequest} by calling its getSession() method.
+ * A {@link jakarta.servlet.Filter} that initializes the {@link HttpSession} for the {@link HttpServletRequest} by
+ * calling its getSession() method.
* <p>
- * This is required for some operations with WebSocket requests, where it is
- * too late to initialize the HttpSession object, and the current Java WebSocket
- * specification does not provide a way to do so.
+ * This is required for some operations with WebSocket requests, where it is too late to initialize the HttpSession
+ * object, and the current Java WebSocket specification does not provide a way to do so.
*/
public class SessionInitializerFilter implements Filter {
/**
- * Calls {@link HttpServletRequest}'s getSession() to initialize the
- * HttpSession and continues processing the chain.
+ * Calls {@link HttpServletRequest}'s getSession() to initialize the HttpSession and continues processing the chain.
*
* @param request The request to process
* @param response The response associated with the request
- * @param chain Provides access to the next filter in the chain for this
- * filter to pass the request and response to for further
- * processing
- * @throws IOException if an I/O error occurs during this filter's
- * processing of the request
+ * @param chain Provides access to the next filter in the chain for this filter to pass the request and response
+ * to for further processing
+ *
+ * @throws IOException if an I/O error occurs during this filter's processing of the request
* @throws ServletException if the processing fails for any other reason
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
- ((HttpServletRequest)request).getSession();
+ ((HttpServletRequest) request).getSession();
chain.doFilter(request, response);
}
diff --git a/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java b/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
index 2bcf743c9d..cb20a20e3a 100644
--- a/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
+++ b/java/org/apache/catalina/filters/SetCharacterEncodingFilter.java
@@ -28,29 +28,26 @@ import org.apache.juli.logging.LogFactory;
/**
- * <p>Example filter that sets the character encoding to be used in parsing the
- * incoming request, either unconditionally or only if the client did not
- * specify a character encoding. Configuration of this filter is based on
- * the following initialization parameters:</p>
+ * <p>
+ * Example filter that sets the character encoding to be used in parsing the incoming request, either unconditionally or
+ * only if the client did not specify a character encoding. Configuration of this filter is based on the following
+ * initialization parameters:
+ * </p>
* <ul>
- * <li><strong>encoding</strong> - The character encoding to be configured
- * for this request, either conditionally or unconditionally based on
- * the <code>ignore</code> initialization parameter. This parameter
- * is required, so there is no default.</li>
- * <li><strong>ignore</strong> - If set to "true", any character encoding
- * specified by the client is ignored, and the value returned by the
- * <code>selectEncoding()</code> method is set. If set to "false,
- * <code>selectEncoding()</code> is called <strong>only</strong> if the
- * client has not already specified an encoding. By default, this
- * parameter is set to "false".</li>
+ * <li><strong>encoding</strong> - The character encoding to be configured for this request, either conditionally or
+ * unconditionally based on the <code>ignore</code> initialization parameter. This parameter is required, so there is no
+ * default.</li>
+ * <li><strong>ignore</strong> - If set to "true", any character encoding specified by the client is ignored, and the
+ * value returned by the <code>selectEncoding()</code> method is set. If set to "false, <code>selectEncoding()</code> is
+ * called <strong>only</strong> if the client has not already specified an encoding. By default, this parameter is set
+ * to "false".</li>
* </ul>
- *
- * <p>Although this filter can be used unchanged, it is also easy to
- * subclass it and make the <code>selectEncoding()</code> method more
- * intelligent about what encoding to choose, based on characteristics of
- * the incoming request (such as the values of the <code>Accept-Language</code>
- * and <code>User-Agent</code> headers, or a value stashed in the current
- * user's session.</p>
+ * <p>
+ * Although this filter can be used unchanged, it is also easy to subclass it and make the <code>selectEncoding()</code>
+ * method more intelligent about what encoding to choose, based on characteristics of the incoming request (such as the
+ * values of the <code>Accept-Language</code> and <code>User-Agent</code> headers, or a value stashed in the current
+ * user's session.
+ * </p>
*/
public class SetCharacterEncodingFilter extends FilterBase {
@@ -62,40 +59,49 @@ public class SetCharacterEncodingFilter extends FilterBase {
// ----------------------------------------------------- Instance Variables
/**
- * The default character encoding to set for requests that pass through
- * this filter.
+ * The default character encoding to set for requests that pass through this filter.
*/
private String encoding = null;
- public void setEncoding(String encoding) { this.encoding = encoding; }
- public String getEncoding() { return encoding; }
+
+ public void setEncoding(String encoding) {
+ this.encoding = encoding;
+ }
+
+ public String getEncoding() {
+ return encoding;
+ }
/**
* Should a character encoding specified by the client be ignored?
*/
private boolean ignore = false;
- public void setIgnore(boolean ignore) { this.ignore = ignore; }
- public boolean isIgnore() { return ignore; }
+
+ public void setIgnore(boolean ignore) {
+ this.ignore = ignore;
+ }
+
+ public boolean isIgnore() {
+ return ignore;
+ }
// --------------------------------------------------------- Public Methods
/**
- * Select and set (if specified) the character encoding to be used to
- * interpret request parameters for this request.
+ * Select and set (if specified) the character encoding to be used to interpret request parameters for this request.
*
- * @param request The servlet request we are processing
+ * @param request The servlet request we are processing
* @param response The servlet response we are creating
- * @param chain The filter chain we are processing
+ * @param chain The filter chain we are processing
*
- * @exception IOException if an input/output error occurs
+ * @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain)
- throws IOException, ServletException {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
// Conditionally select and set the character encoding to be used
if (ignore || (request.getCharacterEncoding() == null)) {
@@ -119,16 +125,14 @@ public class SetCharacterEncodingFilter extends FilterBase {
/**
- * Select an appropriate character encoding to be used, based on the
- * characteristics of the current request and/or filter initialization
- * parameters. If no character encoding should be set, return
- * <code>null</code>.
+ * Select an appropriate character encoding to be used, based on the characteristics of the current request and/or
+ * filter initialization parameters. If no character encoding should be set, return <code>null</code>.
* <p>
- * The default implementation unconditionally returns the value configured
- * by the <strong>encoding</strong> initialization parameter for this
- * filter.
+ * The default implementation unconditionally returns the value configured by the <strong>encoding</strong>
+ * initialization parameter for this filter.
*
* @param request The servlet request we are processing
+ *
* @return the encoding that was configured
*/
protected String selectEncoding(ServletRequest request) {
diff --git a/java/org/apache/catalina/filters/WebdavFixFilter.java b/java/org/apache/catalina/filters/WebdavFixFilter.java
index 72a6843041..7e0c1198c8 100644
--- a/java/org/apache/catalina/filters/WebdavFixFilter.java
+++ b/java/org/apache/catalina/filters/WebdavFixFilter.java
@@ -29,33 +29,27 @@ import jakarta.servlet.http.HttpServletResponse;
import org.apache.tomcat.util.res.StringManager;
/**
- * Filter that attempts to force MS WebDAV clients connecting on port 80 to use
- * a WebDAV client that actually works. Other workarounds that might help
- * include:
+ * Filter that attempts to force MS WebDAV clients connecting on port 80 to use a WebDAV client that actually works.
+ * Other workarounds that might help include:
* <ul>
- * <li>Specifying the port, even if it is port 80, when trying to
- * connect.</li>
- * <li>Cancelling the first authentication dialog box and then trying to
- * reconnect.</li>
+ * <li>Specifying the port, even if it is port 80, when trying to connect.</li>
+ * <li>Cancelling the first authentication dialog box and then trying to reconnect.</li>
* </ul>
- *
- * Generally each different version of the MS client has a different set of
- * problems.
+ * Generally each different version of the MS client has a different set of problems.
* <p>
- * TODO: Update this filter to recognise specific MS clients and apply the
- * appropriate workarounds for that particular client
+ * TODO: Update this filter to recognise specific MS clients and apply the appropriate workarounds for that particular
+ * client
* <p>
- * As a filter, this is configured in web.xml like any other Filter. You usually
- * want to map this filter to whatever your WebDAV servlet is mapped to.
+ * As a filter, this is configured in web.xml like any other Filter. You usually want to map this filter to whatever
+ * your WebDAV servlet is mapped to.
* <p>
- * In addition to the issues fixed by this Filter, the following issues have
- * also been observed that cannot be fixed by this filter. Where possible the
- * filter will add an message to the logs.
+ * In addition to the issues fixed by this Filter, the following issues have also been observed that cannot be fixed by
+ * this filter. Where possible the filter will add an message to the logs.
* <p>
* XP x64 SP2 (MiniRedir Version 3790)
* <ul>
- * <li>Only connects to port 80</li>
- * <li>Unknown issue means it doesn't work</li>
+ * <li>Only connects to port 80</li>
+ * <li>Unknown issue means it doesn't work</li>
* </ul>
*/
public class WebdavFixFilter extends GenericFilter {
@@ -64,25 +58,21 @@ public class WebdavFixFilter extends GenericFilter {
protected static final StringManager sm = StringManager.getManager(WebdavFixFilter.class);
/* Start string for all versions */
- private static final String UA_MINIDIR_START =
- "Microsoft-WebDAV-MiniRedir";
+ private static final String UA_MINIDIR_START = "Microsoft-WebDAV-MiniRedir";
/* XP 32-bit SP3 */
- private static final String UA_MINIDIR_5_1_2600 =
- "Microsoft-WebDAV-MiniRedir/5.1.2600";
+ private static final String UA_MINIDIR_5_1_2600 = "Microsoft-WebDAV-MiniRedir/5.1.2600";
/* XP 64-bit SP2 */
- private static final String UA_MINIDIR_5_2_3790 =
- "Microsoft-WebDAV-MiniRedir/5.2.3790";
+ private static final String UA_MINIDIR_5_2_3790 = "Microsoft-WebDAV-MiniRedir/5.2.3790";
/**
- * Check for the broken MS WebDAV client and if detected issue a re-direct
- * that hopefully will cause the non-broken client to be used.
+ * Check for the broken MS WebDAV client and if detected issue a re-direct that hopefully will cause the non-broken
+ * client to be used.
*/
@Override
- public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
- if (!(request instanceof HttpServletRequest) ||
- !(response instanceof HttpServletResponse)) {
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
+ throws IOException, ServletException {
+ if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
chain.doFilter(request, response);
return;
}
@@ -90,8 +80,7 @@ public class WebdavFixFilter extends GenericFilter {
HttpServletResponse httpResponse = ((HttpServletResponse) response);
String ua = httpRequest.getHeader("User-Agent");
- if (ua == null || ua.length() == 0 ||
- !ua.startsWith(UA_MINIDIR_START)) {
+ if (ua == null || ua.length() == 0 || !ua.startsWith(UA_MINIDIR_START)) {
// No UA or starts with non MS value
// Hope everything just works...
chain.doFilter(request, response);
@@ -117,8 +106,7 @@ public class WebdavFixFilter extends GenericFilter {
}
private String buildRedirect(HttpServletRequest request) {
- StringBuilder location =
- new StringBuilder(request.getRequestURL().length());
+ StringBuilder location = new StringBuilder(request.getRequestURL().length());
location.append(request.getScheme());
location.append("://");
location.append(request.getServerName());
---------------------------------------------------------------------
To unsubscribe, e-mail: dev-unsubscribe@tomcat.apache.org
For additional commands, e-mail: dev-help@tomcat.apache.org