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 3dc4497f8a5d8498d8fb42b1326e214b89e28270 Author: Mark Thomas <ma...@apache.org> AuthorDate: Thu Feb 23 16:47:25 2023 +0000 Clean-up - formatting. No functional change. --- .../coyote/http11/AbstractHttp11Protocol.java | 269 +++++++++++++-------- .../coyote/http11/HeadersTooLargeException.java | 3 +- .../apache/coyote/http11/Http11InputBuffer.java | 165 ++++++------- .../apache/coyote/http11/Http11Nio2Protocol.java | 6 +- .../apache/coyote/http11/Http11NioProtocol.java | 14 +- .../apache/coyote/http11/Http11OutputBuffer.java | 95 ++++---- java/org/apache/coyote/http11/Http11Processor.java | 164 ++++++------- .../org/apache/coyote/http11/HttpOutputBuffer.java | 5 +- java/org/apache/coyote/http11/InputFilter.java | 15 +- java/org/apache/coyote/http11/OutputFilter.java | 5 +- 10 files changed, 376 insertions(+), 365 deletions(-) diff --git a/java/org/apache/coyote/http11/AbstractHttp11Protocol.java b/java/org/apache/coyote/http11/AbstractHttp11Protocol.java index 422943ddab..9ffaeb0c93 100644 --- a/java/org/apache/coyote/http11/AbstractHttp11Protocol.java +++ b/java/org/apache/coyote/http11/AbstractHttp11Protocol.java @@ -55,13 +55,12 @@ import org.apache.tomcat.util.res.StringManager; public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { - protected static final StringManager sm = - StringManager.getManager(AbstractHttp11Protocol.class); + protected static final StringManager sm = StringManager.getManager(AbstractHttp11Protocol.class); private final CompressionConfig compressionConfig = new CompressionConfig(); - public AbstractHttp11Protocol(AbstractEndpoint<S,?> endpoint) { + public AbstractHttp11Protocol(AbstractEndpoint<S, ?> endpoint) { super(endpoint); setConnectionTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT); } @@ -117,7 +116,7 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { * Over-ridden here to make the method visible to nested classes. */ @Override - protected AbstractEndpoint<S,?> getEndpoint() { + protected AbstractEndpoint<S, ?> getEndpoint() { return super.getEndpoint(); } @@ -126,61 +125,70 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { // ------------------------------------------ managed in the ProtocolHandler private ContinueResponseTiming continueResponseTiming = ContinueResponseTiming.IMMEDIATELY; + public String getContinueResponseTiming() { return continueResponseTiming.toString(); } + public void setContinueResponseTiming(String continueResponseTiming) { this.continueResponseTiming = ContinueResponseTiming.fromString(continueResponseTiming); } + public ContinueResponseTiming getContinueResponseTimingInternal() { return continueResponseTiming; } private boolean useKeepAliveResponseHeader = true; + public boolean getUseKeepAliveResponseHeader() { return useKeepAliveResponseHeader; } + public void setUseKeepAliveResponseHeader(boolean useKeepAliveResponseHeader) { this.useKeepAliveResponseHeader = useKeepAliveResponseHeader; } private String relaxedPathChars = null; + public String getRelaxedPathChars() { return relaxedPathChars; } + public void setRelaxedPathChars(String relaxedPathChars) { this.relaxedPathChars = relaxedPathChars; } private String relaxedQueryChars = null; + public String getRelaxedQueryChars() { return relaxedQueryChars; } + public void setRelaxedQueryChars(String relaxedQueryChars) { this.relaxedQueryChars = relaxedQueryChars; } private boolean allowHostHeaderMismatch = false; + /** - * Will Tomcat accept an HTTP 1.1 request where the host header does not - * agree with the host specified (if any) in the request line? + * Will Tomcat accept an HTTP 1.1 request where the host header does not agree with the host specified (if any) in + * the request line? * - * @return {@code true} if Tomcat will allow such requests, otherwise - * {@code false} + * @return {@code true} if Tomcat will allow such requests, otherwise {@code false} */ public boolean getAllowHostHeaderMismatch() { return allowHostHeaderMismatch; } + /** - * Will Tomcat accept an HTTP 1.1 request where the host header does not - * agree with the host specified (if any) in the request line? + * Will Tomcat accept an HTTP 1.1 request where the host header does not agree with the host specified (if any) in + * the request line? * - * @param allowHostHeaderMismatch {@code true} to allow such requests, - * {@code false} to reject them with a 400 + * @param allowHostHeaderMismatch {@code true} to allow such requests, {@code false} to reject them with a 400 */ public void setAllowHostHeaderMismatch(boolean allowHostHeaderMismatch) { this.allowHostHeaderMismatch = allowHostHeaderMismatch; @@ -188,23 +196,23 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private boolean rejectIllegalHeader = true; + /** - * If an HTTP request is received that contains an illegal header name or - * value (e.g. the header name is not a token) will the request be rejected - * (with a 400 response) or will the illegal header be ignored? + * If an HTTP request is received that contains an illegal header name or value (e.g. the header name is not a + * token) will the request be rejected (with a 400 response) or will the illegal header be ignored? * - * @return {@code true} if the request will be rejected or {@code false} if - * the header will be ignored + * @return {@code true} if the request will be rejected or {@code false} if the header will be ignored */ - public boolean getRejectIllegalHeader() { return rejectIllegalHeader; } + public boolean getRejectIllegalHeader() { + return rejectIllegalHeader; + } + /** - * If an HTTP request is received that contains an illegal header name or - * value (e.g. the header name is not a token) should the request be - * rejected (with a 400 response) or should the illegal header be ignored? + * If an HTTP request is received that contains an illegal header name or value (e.g. the header name is not a + * token) should the request be rejected (with a 400 response) or should the illegal header be ignored? * - * @param rejectIllegalHeader {@code true} to reject requests with illegal - * header names or values, {@code false} to - * ignore the header + * @param rejectIllegalHeader {@code true} to reject requests with illegal header names or values, {@code false} to + * ignore the header */ public void setRejectIllegalHeader(boolean rejectIllegalHeader) { this.rejectIllegalHeader = rejectIllegalHeader; @@ -212,19 +220,20 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private int maxSavePostSize = 4 * 1024; + /** - * Return the maximum size of the post which will be saved during FORM or - * CLIENT-CERT authentication. + * Return the maximum size of the post which will be saved during FORM or CLIENT-CERT authentication. * * @return The size in bytes */ - public int getMaxSavePostSize() { return maxSavePostSize; } + public int getMaxSavePostSize() { + return maxSavePostSize; + } + /** - * Set the maximum size of a POST which will be buffered during FORM or - * CLIENT-CERT authentication. When a POST is received where the security - * constraints require a client certificate, the POST body needs to be - * buffered while an SSL handshake takes place to obtain the certificate. A - * similar buffering is required during FORM auth. + * Set the maximum size of a POST which will be buffered during FORM or CLIENT-CERT authentication. When a POST is + * received where the security constraints require a client certificate, the POST body needs to be buffered while an + * SSL handshake takes place to obtain the certificate. A similar buffering is required during FORM auth. * * @param maxSavePostSize The maximum size POST body to buffer in bytes */ @@ -237,8 +246,14 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { * Maximum size of the HTTP message header. */ private int maxHttpHeaderSize = 8 * 1024; - public int getMaxHttpHeaderSize() { return maxHttpHeaderSize; } - public void setMaxHttpHeaderSize(int valueI) { maxHttpHeaderSize = valueI; } + + public int getMaxHttpHeaderSize() { + return maxHttpHeaderSize; + } + + public void setMaxHttpHeaderSize(int valueI) { + maxHttpHeaderSize = valueI; + } /** @@ -270,13 +285,17 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private int connectionUploadTimeout = 300000; + /** - * Specifies a different (usually longer) connection timeout during data - * upload. Default is 5 minutes as in Apache HTTPD server. + * Specifies a different (usually longer) connection timeout during data upload. Default is 5 minutes as in Apache + * HTTPD server. * * @return The timeout in milliseconds */ - public int getConnectionUploadTimeout() { return connectionUploadTimeout; } + public int getConnectionUploadTimeout() { + return connectionUploadTimeout; + } + /** * Set the upload timeout. * @@ -288,20 +307,21 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private boolean disableUploadTimeout = true; + /** - * Get the flag that controls upload time-outs. If true, the - * connectionUploadTimeout will be ignored and the regular socket timeout - * will be used for the full duration of the connection. + * Get the flag that controls upload time-outs. If true, the connectionUploadTimeout will be ignored and the regular + * socket timeout will be used for the full duration of the connection. * * @return {@code true} if the separate upload timeout is disabled */ - public boolean getDisableUploadTimeout() { return disableUploadTimeout; } + public boolean getDisableUploadTimeout() { + return disableUploadTimeout; + } + /** - * Set the flag to control whether a separate connection timeout is used - * during upload of a request body. + * Set the flag to control whether a separate connection timeout is used during upload of a request body. * - * @param isDisabled {@code true} if the separate upload timeout should be - * disabled + * @param isDisabled {@code true} if the separate upload timeout should be disabled */ public void setDisableUploadTimeout(boolean isDisabled) { disableUploadTimeout = isDisabled; @@ -311,9 +331,11 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { public void setCompression(String compression) { compressionConfig.setCompression(compression); } + public String getCompression() { return compressionConfig.getCompression(); } + protected int getCompressionLevel() { return compressionConfig.getCompressionLevel(); } @@ -322,9 +344,11 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { public String getNoCompressionUserAgents() { return compressionConfig.getNoCompressionUserAgents(); } + protected Pattern getNoCompressionUserAgentsPattern() { return compressionConfig.getNoCompressionUserAgentsPattern(); } + public void setNoCompressionUserAgents(String noCompressionUserAgents) { compressionConfig.setNoCompressionUserAgents(noCompressionUserAgents); } @@ -333,9 +357,11 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { public String getCompressibleMimeType() { return compressionConfig.getCompressibleMimeType(); } + public void setCompressibleMimeType(String valueS) { compressionConfig.setCompressibleMimeType(valueS); } + public String[] getCompressibleMimeTypes() { return compressionConfig.getCompressibleMimeTypes(); } @@ -344,6 +370,7 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { public int getCompressionMinSize() { return compressionConfig.getCompressionMinSize(); } + public void setCompressionMinSize(int compressionMinSize) { compressionConfig.setCompressionMinSize(compressionMinSize); } @@ -355,9 +382,10 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private Pattern restrictedUserAgents = null; + /** - * Get the string form of the regular expression that defines the User - * agents which should be restricted to HTTP/1.0 support. + * Get the string form of the regular expression that defines the User agents which should be restricted to HTTP/1.0 + * support. * * @return The regular expression as a String */ @@ -368,16 +396,17 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { return restrictedUserAgents.toString(); } } + protected Pattern getRestrictedUserAgentsPattern() { return restrictedUserAgents; } + /** - * Set restricted user agent list (which will downgrade the connector - * to HTTP/1.0 mode). Regular expression as supported by {@link Pattern}. + * Set restricted user agent list (which will downgrade the connector to HTTP/1.0 mode). Regular expression as + * supported by {@link Pattern}. * - * @param restrictedUserAgents The regular expression as supported by - * {@link Pattern} for the user agents e.g. - * "gorilla|desesplorer|tigrus" + * @param restrictedUserAgents The regular expression as supported by {@link Pattern} for the user agents e.g. + * "gorilla|desesplorer|tigrus" */ public void setRestrictedUserAgents(String restrictedUserAgents) { if (restrictedUserAgents == null || restrictedUserAgents.length() == 0) { @@ -389,7 +418,11 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private String server; - public String getServer() { return server; } + + public String getServer() { + return server; + } + /** * Set the server header name. * @@ -401,15 +434,17 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { private boolean serverRemoveAppProvidedValues = false; + /** - * Should application provider values for the HTTP Server header be removed. - * Note that if {@link #server} is set, any application provided value will - * be over-ridden. + * Should application provider values for the HTTP Server header be removed. Note that if {@link #server} is set, + * any application provided value will be over-ridden. * - * @return {@code true} if application provided values should be removed, - * otherwise {@code false} + * @return {@code true} if application provided values should be removed, otherwise {@code false} */ - public boolean getServerRemoveAppProvidedValues() { return serverRemoveAppProvidedValues; } + public boolean getServerRemoveAppProvidedValues() { + return serverRemoveAppProvidedValues; + } + public void setServerRemoveAppProvidedValues(boolean serverRemoveAppProvidedValues) { this.serverRemoveAppProvidedValues = serverRemoveAppProvidedValues; } @@ -419,7 +454,11 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { * Maximum size of trailing headers in bytes */ private int maxTrailerSize = 8192; - public int getMaxTrailerSize() { return maxTrailerSize; } + + public int getMaxTrailerSize() { + return maxTrailerSize; + } + public void setMaxTrailerSize(int maxTrailerSize) { this.maxTrailerSize = maxTrailerSize; } @@ -429,7 +468,11 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { * Maximum size of extension information in chunked encoding */ private int maxExtensionSize = 8192; - public int getMaxExtensionSize() { return maxExtensionSize; } + + public int getMaxExtensionSize() { + return maxExtensionSize; + } + public void setMaxExtensionSize(int maxExtensionSize) { this.maxExtensionSize = maxExtensionSize; } @@ -439,29 +482,37 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { * Maximum amount of request body to swallow. */ private int maxSwallowSize = 2 * 1024 * 1024; - public int getMaxSwallowSize() { return maxSwallowSize; } + + public int getMaxSwallowSize() { + return maxSwallowSize; + } + public void setMaxSwallowSize(int maxSwallowSize) { this.maxSwallowSize = maxSwallowSize; } /** - * This field indicates if the protocol is treated as if it is secure. This - * normally means https is being used but can be used to fake https e.g - * behind a reverse proxy. + * This field indicates if the protocol is treated as if it is secure. This normally means https is being used but + * can be used to fake https e.g behind a reverse proxy. */ private boolean secure; - public boolean getSecure() { return secure; } + + public boolean getSecure() { + return secure; + } + public void setSecure(boolean b) { secure = b; } /** - * The names of headers that are allowed to be sent via a trailer when using - * chunked encoding. They are stored in lower case. + * The names of headers that are allowed to be sent via a trailer when using chunked encoding. They are stored in + * lower case. */ private Set<String> allowedTrailerHeaders = ConcurrentHashMap.newKeySet(); + public void setAllowedTrailerHeaders(String commaSeparatedHeaders) { // Jump through some hoops so we don't end up with an empty set while // doing updates. @@ -479,23 +530,28 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { allowedTrailerHeaders.removeAll(toRemove); } } + protected Set<String> getAllowedTrailerHeadersInternal() { return allowedTrailerHeaders; } + public boolean isTrailerHeaderAllowed(String headerName) { return allowedTrailerHeaders.contains(headerName); } + public String getAllowedTrailerHeaders() { // Chances of a change during execution of this line are small enough // that a sync is unnecessary. List<String> copy = new ArrayList<>(allowedTrailerHeaders); return StringUtils.join(copy); } + public void addAllowedTrailerHeader(String header) { if (header != null) { allowedTrailerHeaders.add(header.trim().toLowerCase(Locale.ENGLISH)); } } + public void removeAllowedTrailerHeader(String header) { if (header != null) { allowedTrailerHeaders.remove(header.trim().toLowerCase(Locale.ENGLISH)); @@ -507,10 +563,12 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { * The upgrade protocol instances configured. */ private final List<UpgradeProtocol> upgradeProtocols = new ArrayList<>(); + @Override public void addUpgradeProtocol(UpgradeProtocol upgradeProtocol) { upgradeProtocols.add(upgradeProtocol); } + @Override public UpgradeProtocol[] findUpgradeProtocols() { return upgradeProtocols.toArray(new UpgradeProtocol[0]); @@ -518,15 +576,14 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { /** - * The protocols that are available via internal Tomcat support for access - * via HTTP upgrade. + * The protocols that are available via internal Tomcat support for access via HTTP upgrade. */ - private final Map<String,UpgradeProtocol> httpUpgradeProtocols = new HashMap<>(); + private final Map<String, UpgradeProtocol> httpUpgradeProtocols = new HashMap<>(); /** - * The protocols that are available via internal Tomcat support for access - * via ALPN negotiation. + * The protocols that are available via internal Tomcat support for access via ALPN negotiation. */ - private final Map<String,UpgradeProtocol> negotiatedProtocols = new HashMap<>(); + private final Map<String, UpgradeProtocol> negotiatedProtocols = new HashMap<>(); + private void configureUpgradeProtocol(UpgradeProtocol upgradeProtocol) { // HTTP Upgrade String httpUpgradeName = upgradeProtocol.getHttpUpgradeName(getEndpoint().isSSLEnabled()); @@ -534,8 +591,7 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { if (httpUpgradeName != null && httpUpgradeName.length() > 0) { httpUpgradeProtocols.put(httpUpgradeName, upgradeProtocol); httpUpgradeConfigured = true; - getLog().info(sm.getString("abstractHttp11Protocol.httpUpgradeConfigured", - getName(), httpUpgradeName)); + getLog().info(sm.getString("abstractHttp11Protocol.httpUpgradeConfigured", getName(), httpUpgradeName)); } @@ -546,8 +602,7 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { if (getEndpoint().isSSLEnabled()) { negotiatedProtocols.put(alpnName, upgradeProtocol); getEndpoint().addNegotiatedProtocol(alpnName); - getLog().info(sm.getString("abstractHttp11Protocol.alpnConfigured", - getName(), alpnName)); + getLog().info(sm.getString("abstractHttp11Protocol.alpnConfigured", getName(), alpnName)); } else { if (!httpUpgradeConfigured) { // ALPN is not supported by this connector and the upgrade @@ -560,10 +615,12 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { } } } + @Override public UpgradeProtocol getNegotiatedProtocol(String negotiatedName) { return negotiatedProtocols.get(negotiatedName); } + @Override public UpgradeProtocol getUpgradeProtocol(String upgradedName) { return httpUpgradeProtocols.get(upgradedName); @@ -573,12 +630,12 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { /** * Map of upgrade protocol name to {@link UpgradeGroupInfo} instance. * <p> - * HTTP upgrades via {@link HttpServletRequest#upgrade(Class)} do not have - * to depend on an {@code UpgradeProtocol}. To enable basic statistics to be - * made available for these protocols, a map of protocol name to + * HTTP upgrades via {@link HttpServletRequest#upgrade(Class)} do not have to depend on an {@code UpgradeProtocol}. + * To enable basic statistics to be made available for these protocols, a map of protocol name to * {@link UpgradeGroupInfo} instances is maintained here. */ - private final Map<String,UpgradeGroupInfo> upgradeProtocolGroupInfos = new ConcurrentHashMap<>(); + private final Map<String, UpgradeGroupInfo> upgradeProtocolGroupInfos = new ConcurrentHashMap<>(); + public UpgradeGroupInfo getUpgradeGroupInfo(String upgradeProtocol) { if (upgradeProtocol == null) { return null; @@ -632,28 +689,35 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { // ------------------------------------------------ HTTP specific properties // ------------------------------------------ passed through to the EndPoint - public boolean isSSLEnabled() { return getEndpoint().isSSLEnabled();} + public boolean isSSLEnabled() { + return getEndpoint().isSSLEnabled(); + } + public void setSSLEnabled(boolean SSLEnabled) { getEndpoint().setSSLEnabled(SSLEnabled); } - public boolean getUseSendfile() { return getEndpoint().getUseSendfile(); } - public void setUseSendfile(boolean useSendfile) { getEndpoint().setUseSendfile(useSendfile); } + public boolean getUseSendfile() { + return getEndpoint().getUseSendfile(); + } + + public void setUseSendfile(boolean useSendfile) { + getEndpoint().setUseSendfile(useSendfile); + } /** - * @return The maximum number of requests which can be performed over a - * keep-alive connection. The default is the same as for Apache HTTP - * Server (100). + * @return The maximum number of requests which can be performed over a keep-alive connection. The default is the + * same as for Apache HTTP Server (100). */ public int getMaxKeepAliveRequests() { return getEndpoint().getMaxKeepAliveRequests(); } + /** - * Set the maximum number of Keep-Alive requests to allow. - * This is to safeguard from DoS attacks. Setting to a negative - * value disables the limit. + * Set the maximum number of Keep-Alive requests to allow. This is to safeguard from DoS attacks. Setting to a + * negative value disables the limit. * * @param mkar The new maximum number of Keep-Alive requests allowed */ @@ -668,6 +732,7 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { public String getDefaultSSLHostConfigName() { return getEndpoint().getDefaultSSLHostConfigName(); } + public void setDefaultSSLHostConfigName(String defaultSSLHostConfigName) { getEndpoint().setDefaultSSLHostConfigName(defaultSSLHostConfigName); } @@ -699,18 +764,26 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { if (OpenSSLImplementation.class.getName().equals(getSslImplementationName())) { return "openssl"; } - if (getSslImplementationName() != null - && getSslImplementationName().endsWith(".panama.OpenSSLImplementation")) { + if (getSslImplementationName() != null && + getSslImplementationName().endsWith(".panama.OpenSSLImplementation")) { return "opensslforeign"; } return "jsse"; } - public String getSslImplementationName() { return getEndpoint().getSslImplementationName(); } - public void setSslImplementationName(String s) { getEndpoint().setSslImplementationName(s); } + public String getSslImplementationName() { + return getEndpoint().getSslImplementationName(); + } + public void setSslImplementationName(String s) { + getEndpoint().setSslImplementationName(s); + } + + + public int getSniParseLimit() { + return getEndpoint().getSniParseLimit(); + } - public int getSniParseLimit() { return getEndpoint().getSniParseLimit(); } public void setSniParseLimit(int sniParseLimit) { getEndpoint().setSniParseLimit(sniParseLimit); } @@ -723,9 +796,7 @@ public abstract class AbstractHttp11Protocol<S> extends AbstractProtocol<S> { @Override - protected Processor createUpgradeProcessor( - SocketWrapperBase<?> socket, - UpgradeToken upgradeToken) { + protected Processor createUpgradeProcessor(SocketWrapperBase<?> socket, UpgradeToken upgradeToken) { HttpUpgradeHandler httpUpgradeHandler = upgradeToken.getHttpUpgradeHandler(); if (httpUpgradeHandler instanceof InternalHttpUpgradeHandler) { return new UpgradeProcessorInternal(socket, upgradeToken, getUpgradeGroupInfo(upgradeToken.getProtocol())); diff --git a/java/org/apache/coyote/http11/HeadersTooLargeException.java b/java/org/apache/coyote/http11/HeadersTooLargeException.java index 96d5133259..49001d2240 100644 --- a/java/org/apache/coyote/http11/HeadersTooLargeException.java +++ b/java/org/apache/coyote/http11/HeadersTooLargeException.java @@ -17,8 +17,7 @@ package org.apache.coyote.http11; /** - * Exception used to mark the specific error condition of the HTTP headers - * exceeding the maximum permitted size. + * Exception used to mark the specific error condition of the HTTP headers exceeding the maximum permitted size. */ public class HeadersTooLargeException extends IllegalStateException { diff --git a/java/org/apache/coyote/http11/Http11InputBuffer.java b/java/org/apache/coyote/http11/Http11InputBuffer.java index ddd7e2d1e2..e338ef653a 100644 --- a/java/org/apache/coyote/http11/Http11InputBuffer.java +++ b/java/org/apache/coyote/http11/Http11InputBuffer.java @@ -36,8 +36,7 @@ import org.apache.tomcat.util.net.SocketWrapperBase; import org.apache.tomcat.util.res.StringManager; /** - * InputBuffer for HTTP that provides request header parsing as well as transfer - * encoding. + * InputBuffer for HTTP that provides request header parsing as well as transfer encoding. */ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler { @@ -51,8 +50,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler private static final StringManager sm = StringManager.getManager(Http11InputBuffer.class); - private static final byte[] CLIENT_PREFACE_START = - "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n".getBytes(StandardCharsets.ISO_8859_1); + private static final byte[] CLIENT_PREFACE_START = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n" + .getBytes(StandardCharsets.ISO_8859_1); /** * Associated Coyote request. @@ -87,8 +86,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * Pos of the end of the header in the buffer, which is also the - * start of the body. + * Pos of the end of the header in the buffer, which is also the start of the body. */ private int end; @@ -106,8 +104,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * Filter library. - * Note: Filter[Constants.CHUNKED_FILTER] is always the "chunked" filter. + * Filter library. Note: Filter[Constants.CHUNKED_FILTER] is always the "chunked" filter. */ private InputFilter[] filterLibrary; @@ -125,8 +122,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * Parsing state - used for non blocking parsing so that - * when more data arrives, we can pick up where we left off. + * Parsing state - used for non blocking parsing so that when more data arrives, we can pick up where we left off. */ private byte prevChr = 0; private byte chr = 0; @@ -140,8 +136,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler private final HttpParser httpParser; /** - * Maximum allowed size of the HTTP request line plus headers plus any - * leading blank lines. + * Maximum allowed size of the HTTP request line plus headers plus any leading blank lines. */ private final int headerBufferSize; @@ -153,8 +148,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // ----------------------------------------------------------- Constructors - public Http11InputBuffer(Request request, int headerBufferSize, - boolean rejectIllegalHeader, HttpParser httpParser) { + public Http11InputBuffer(Request request, int headerBufferSize, boolean rejectIllegalHeader, + HttpParser httpParser) { this.request = request; headers = request.getMimeHeaders(); @@ -254,8 +249,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // ------------------------------------------------------- Protected Methods /** - * Recycle the input buffer. This should be called when closing the - * connection. + * Recycle the input buffer. This should be called when closing the connection. */ void recycle() { wrapper = null; @@ -287,10 +281,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * End processing of current HTTP request. - * Note: All bytes of the current request should have been already - * consumed. This method only resets all the pointers so that we are ready - * to parse the next HTTP request. + * End processing of current HTTP request. Note: All bytes of the current request should have been already consumed. + * This method only resets all the pointers so that we are ready to parse the next HTTP request. */ void nextRequest() { request.recycle(); @@ -327,19 +319,15 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * Read the request line. This function is meant to be used during the - * HTTP request header parsing. Do NOT attempt to read the request body - * using it. + * Read the request line. This function is meant to be used during the HTTP request header parsing. Do NOT attempt + * to read the request body using it. * - * @throws IOException If an exception occurs during the underlying socket - * read operations, or if the given buffer is not big enough to accommodate - * the whole line. + * @throws IOException If an exception occurs during the underlying socket read operations, or if the given buffer + * is not big enough to accommodate the whole line. * - * @return true if data is properly fed; false if no data is available - * immediately and thread should be freed + * @return true if data is properly fed; false if no data is available immediately and thread should be freed */ - boolean parseRequestLine(boolean keptAlive, int connectionTimeout, int keepAliveTimeout) - throws IOException { + boolean parseRequestLine(boolean keptAlive, int connectionTimeout, int keepAliveTimeout) throws IOException { // check state if (!parsingRequestLine) { @@ -572,8 +560,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler } if ((end - parsingRequestLineStart) > 0) { - request.protocol().setBytes(byteBuffer.array(), parsingRequestLineStart, - end - parsingRequestLineStart); + request.protocol().setBytes(byteBuffer.array(), parsingRequestLineStart, end - parsingRequestLineStart); parsingRequestLinePhase = 7; } // If no protocol is found, the ISE below will be triggered. @@ -610,7 +597,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // limitation to enforce the meaning of headerBufferSize // From the way how buf is allocated and how blank lines are being // read, it should be enough to check (1) only. - if (byteBuffer.position() > headerBufferSize || byteBuffer.capacity() - byteBuffer.position() < socketReadBufferSize) { + if (byteBuffer.position() > headerBufferSize || + byteBuffer.capacity() - byteBuffer.position() < socketReadBufferSize) { throw new IllegalArgumentException(sm.getString("iib.requestheadertoolarge.error")); } } while (status == HeaderParseStatus.HAVE_MORE_HEADERS); @@ -635,7 +623,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler while (buffer.hasRemaining() && b != 0x20) { b = buffer.get(); } - String result = HeaderUtil.toPrintableString(buffer.array(), buffer.arrayOffset() + startPos, buffer.position() - startPos); + String result = HeaderUtil.toPrintableString(buffer.array(), buffer.arrayOffset() + startPos, + buffer.position() - startPos); if (b != 0x20) { // Ran out of buffer rather than found a space result = result + "..."; @@ -665,10 +654,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * Available bytes in the buffers for the current request. - * - * Note that when requests are pipelined, the data in byteBuffer may relate - * to the next request rather than this one. + * Available bytes in the buffers for the current request. Note that when requests are pipelined, the data in + * byteBuffer may relate to the next request rather than this one. */ int available(boolean read) { int available; @@ -686,10 +673,10 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // - the socket wrapper indicates a read is allowed // // Notes: 1. When pipelined requests are being used available may be - // zero even when byteBuffer has data. This is because the data - // in byteBuffer is for the next request. We don't want to - // attempt a read in this case. - // 2. wrapper.hasDataToRead() is present to handle the NIO2 case + // zero even when byteBuffer has data. This is because the data + // in byteBuffer is for the next request. We don't want to + // attempt a read in this case. + // 2. wrapper.hasDataToRead() is present to handle the NIO2 case try { if (available == 0 && read && !byteBuffer.hasRemaining() && wrapper.hasDataToRead()) { fill(false); @@ -709,9 +696,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** - * Has all of the request body been read? There are subtle differences - * between this and available() > 0 primarily because of having to handle - * faking non-blocking reads with the blocking IO connector. + * Has all of the request body been read? There are subtle differences between this and available() > 0 primarily + * because of having to handle faking non-blocking reads with the blocking IO connector. */ boolean isFinished() { // The active filters have the definitive information on whether or not @@ -751,8 +737,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler wrapper = socketWrapper; wrapper.setAppReadBufHandler(this); - int bufLength = headerBufferSize + - wrapper.getSocketBufferHandler().getReadBuffer().capacity(); + int bufLength = headerBufferSize + wrapper.getSocketBufferHandler().getReadBuffer().capacity(); if (byteBuffer == null || byteBuffer.capacity() < bufLength) { byteBuffer = ByteBuffer.allocate(bufLength); byteBuffer.position(0).limit(0); @@ -760,25 +745,20 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler } - // --------------------------------------------------------- Private Methods /** * Attempts to read some data into the input buffer. * - * @return <code>true</code> if more data was added to the input buffer - * otherwise <code>false</code> + * @return <code>true</code> if more data was added to the input buffer otherwise <code>false</code> */ private boolean fill(boolean block) throws IOException { if (log.isDebugEnabled()) { - log.debug("Before fill(): parsingHeader: [" + parsingHeader + - "], parsingRequestLine: [" + parsingRequestLine + - "], parsingRequestLinePhase: [" + parsingRequestLinePhase + - "], parsingRequestLineStart: [" + parsingRequestLineStart + - "], byteBuffer.position(): [" + byteBuffer.position() + - "], byteBuffer.limit(): [" + byteBuffer.limit() + - "], end: [" + end + "]"); + log.debug("Before fill(): parsingHeader: [" + parsingHeader + "], parsingRequestLine: [" + + parsingRequestLine + "], parsingRequestLinePhase: [" + parsingRequestLinePhase + + "], parsingRequestLineStart: [" + parsingRequestLineStart + "], byteBuffer.position(): [" + + byteBuffer.position() + "], byteBuffer.limit(): [" + byteBuffer.limit() + "], end: [" + end + "]"); } if (parsingHeader) { @@ -827,8 +807,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler } if (log.isDebugEnabled()) { - log.debug("Received [" - + new String(byteBuffer.array(), byteBuffer.position(), byteBuffer.remaining(), StandardCharsets.ISO_8859_1) + "]"); + log.debug("Received [" + new String(byteBuffer.array(), byteBuffer.position(), byteBuffer.remaining(), + StandardCharsets.ISO_8859_1) + "]"); } if (nRead > 0) { @@ -845,9 +825,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** * Parse an HTTP header. * - * @return One of {@link HeaderParseStatus#NEED_MORE_DATA}, - * {@link HeaderParseStatus#HAVE_MORE_HEADERS} or - * {@link HeaderParseStatus#DONE}. + * @return One of {@link HeaderParseStatus#NEED_MORE_DATA}, {@link HeaderParseStatus#HAVE_MORE_HEADERS} or + * {@link HeaderParseStatus#DONE}. */ private HeaderParseStatus parseHeader() throws IOException { @@ -905,8 +884,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler chr = byteBuffer.get(); if (chr == Constants.COLON) { headerParsePos = HeaderParsePosition.HEADER_VALUE_START; - headerData.headerValue = headers.addValue(byteBuffer.array(), headerData.start, - pos - headerData.start); + headerData.headerValue = headers.addValue(byteBuffer.array(), headerData.start, pos - headerData.start); pos = byteBuffer.position(); // Mark the current buffer position headerData.start = pos; @@ -938,8 +916,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // while (headerParsePos == HeaderParsePosition.HEADER_VALUE_START || - headerParsePos == HeaderParsePosition.HEADER_VALUE || - headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) { + headerParsePos == HeaderParsePosition.HEADER_VALUE || + headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) { if (headerParsePos == HeaderParsePosition.HEADER_VALUE_START) { // Skipping spaces @@ -1086,9 +1064,8 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler } } if (rejectThisHeader || log.isDebugEnabled()) { - String message = sm.getString("iib.invalidheader", - HeaderUtil.toPrintableString(byteBuffer.array(), headerData.lineStart, - headerData.lastSignificantChar - headerData.lineStart + 1)); + String message = sm.getString("iib.invalidheader", HeaderUtil.toPrintableString(byteBuffer.array(), + headerData.lineStart, headerData.lastSignificantChar - headerData.lineStart + 1)); if (rejectThisHeader) { throw new IllegalArgumentException(message); } @@ -1103,41 +1080,39 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // ----------------------------------------------------------- Inner classes private enum HeaderParseStatus { - DONE, HAVE_MORE_HEADERS, NEED_MORE_DATA + DONE, + HAVE_MORE_HEADERS, + NEED_MORE_DATA } private enum HeaderParsePosition { /** - * Start of a new header. A CRLF here means that there are no more - * headers. Any other character starts a header name. + * Start of a new header. A CRLF here means that there are no more headers. Any other character starts a header + * name. */ HEADER_START, /** - * Reading a header name. All characters of header are HTTP_TOKEN_CHAR. - * Header name is followed by ':'. No whitespace is allowed.<br> - * Any non-HTTP_TOKEN_CHAR (this includes any whitespace) encountered - * before ':' will result in the whole line being ignored. + * Reading a header name. All characters of header are HTTP_TOKEN_CHAR. Header name is followed by ':'. No + * whitespace is allowed.<br> + * Any non-HTTP_TOKEN_CHAR (this includes any whitespace) encountered before ':' will result in the whole line + * being ignored. */ HEADER_NAME, /** - * Skipping whitespace before text of header value starts, either on the - * first line of header value (just after ':') or on subsequent lines - * when it is known that subsequent line starts with SP or HT. + * Skipping whitespace before text of header value starts, either on the first line of header value (just after + * ':') or on subsequent lines when it is known that subsequent line starts with SP or HT. */ HEADER_VALUE_START, /** - * Reading the header value. We are inside the value. Either on the - * first line or on any subsequent line. We come into this state from - * HEADER_VALUE_START after the first non-SP/non-HT byte is encountered - * on the line. + * Reading the header value. We are inside the value. Either on the first line or on any subsequent line. We + * come into this state from HEADER_VALUE_START after the first non-SP/non-HT byte is encountered on the line. */ HEADER_VALUE, /** - * Before reading a new line of a header. Once the next byte is peeked, - * the state changes without advancing our position. The state becomes - * either HEADER_VALUE_START (if that first byte is SP or HT), or - * HEADER_START (otherwise). + * Before reading a new line of a header. Once the next byte is peeked, the state changes without advancing our + * position. The state becomes either HEADER_VALUE_START (if that first byte is SP or HT), or HEADER_START + * (otherwise). */ HEADER_MULTI_LINE, /** @@ -1161,11 +1136,9 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler /** * When parsing header name: not used (stays as 0).<br> * When skipping broken header line: not used (stays as 0).<br> - * When parsing header value: starts as the first character after ':'. - * Then is increased as far as more bytes of the header are harvested. - * Bytes from buf[pos] are copied to buf[realPos]. Thus the string from - * [start] to [realPos-1] is the prepared value of the header, with - * whitespaces removed as needed.<br> + * When parsing header value: starts as the first character after ':'. Then is increased as far as more bytes of + * the header are harvested. Bytes from buf[pos] are copied to buf[realPos]. Thus the string from [start] to + * [realPos-1] is the prepared value of the header, with whitespaces removed as needed.<br> */ int realPos = 0; /** @@ -1175,10 +1148,11 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler */ int lastSignificantChar = 0; /** - * MB that will store the value of the header. It is null while parsing - * header name and is created after the name has been parsed. + * MB that will store the value of the header. It is null while parsing header name and is created after the + * name has been parsed. */ MessageBytes headerValue = null; + public void recycle() { lineStart = 0; start = 0; @@ -1192,8 +1166,7 @@ public class Http11InputBuffer implements InputBuffer, ApplicationBufferHandler // ------------------------------------- InputStreamInputBuffer Inner Class /** - * This class is an input buffer which will read its data from an input - * stream. + * This class is an input buffer which will read its data from an input stream. */ private class SocketInputBuffer implements InputBuffer { diff --git a/java/org/apache/coyote/http11/Http11Nio2Protocol.java b/java/org/apache/coyote/http11/Http11Nio2Protocol.java index 94c271e87f..798c02431c 100644 --- a/java/org/apache/coyote/http11/Http11Nio2Protocol.java +++ b/java/org/apache/coyote/http11/Http11Nio2Protocol.java @@ -42,7 +42,9 @@ public class Http11Nio2Protocol extends AbstractHttp11Protocol<Nio2Channel> { @Override - protected Log getLog() { return log; } + protected Log getLog() { + return log; + } @Override @@ -54,7 +56,7 @@ public class Http11Nio2Protocol extends AbstractHttp11Protocol<Nio2Channel> { @Override protected String getNamePrefix() { if (isSSLEnabled()) { - return "https-" + getSslImplementationShortName()+ "-nio2"; + return "https-" + getSslImplementationShortName() + "-nio2"; } else { return "http-nio2"; } diff --git a/java/org/apache/coyote/http11/Http11NioProtocol.java b/java/org/apache/coyote/http11/Http11NioProtocol.java index 98e4a3352b..57068d795e 100644 --- a/java/org/apache/coyote/http11/Http11NioProtocol.java +++ b/java/org/apache/coyote/http11/Http11NioProtocol.java @@ -42,25 +42,27 @@ public class Http11NioProtocol extends AbstractHttp11Protocol<NioChannel> { @Override - protected Log getLog() { return log; } + protected Log getLog() { + return log; + } // -------------------- Pool setup -------------------- public void setSelectorTimeout(long timeout) { - ((NioEndpoint)getEndpoint()).setSelectorTimeout(timeout); + ((NioEndpoint) getEndpoint()).setSelectorTimeout(timeout); } public long getSelectorTimeout() { - return ((NioEndpoint)getEndpoint()).getSelectorTimeout(); + return ((NioEndpoint) getEndpoint()).getSelectorTimeout(); } public void setPollerThreadPriority(int threadPriority) { - ((NioEndpoint)getEndpoint()).setPollerThreadPriority(threadPriority); + ((NioEndpoint) getEndpoint()).setPollerThreadPriority(threadPriority); } public int getPollerThreadPriority() { - return ((NioEndpoint)getEndpoint()).getPollerThreadPriority(); + return ((NioEndpoint) getEndpoint()).getPollerThreadPriority(); } @@ -73,7 +75,7 @@ public class Http11NioProtocol extends AbstractHttp11Protocol<NioChannel> { @Override protected String getNamePrefix() { if (isSSLEnabled()) { - return "https-" + getSslImplementationShortName()+ "-nio"; + return "https-" + getSslImplementationShortName() + "-nio"; } else { return "http-nio"; } diff --git a/java/org/apache/coyote/http11/Http11OutputBuffer.java b/java/org/apache/coyote/http11/Http11OutputBuffer.java index e7206a50bd..3916a8843b 100644 --- a/java/org/apache/coyote/http11/Http11OutputBuffer.java +++ b/java/org/apache/coyote/http11/Http11OutputBuffer.java @@ -29,10 +29,9 @@ import org.apache.tomcat.util.net.SocketWrapperBase; import org.apache.tomcat.util.res.StringManager; /** - * Provides buffering for the HTTP headers (allowing responses to be reset - * before they have been committed) and the link to the Socket for writing the - * headers (once committed) and the response body. Note that buffering of the - * response body happens at a higher level. + * Provides buffering for the HTTP headers (allowing responses to be reset before they have been committed) and the link + * to the Socket for writing the headers (once committed) and the response body. Note that buffering of the response + * body happens at a higher level. */ public class Http11OutputBuffer implements HttpOutputBuffer { @@ -122,8 +121,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { // ------------------------------------------------------------- Properties /** - * Add an output filter to the filter library. Note that calling this method - * resets the currently active filters to none. + * Add an output filter to the filter library. Note that calling this method resets the currently active filters to + * none. * * @param filter The filter to add */ @@ -152,8 +151,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { * <p> * The filter does not have to be present in {@link #getFilters()}. * <p> - * A filter can only be added to a response once. If the filter has already - * been added to this response then this method will be a NO-OP. + * A filter can only be added to a response once. If the filter has already been added to this response then this + * method will be a NO-OP. * * @param filter The filter to add */ @@ -242,8 +241,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { // --------------------------------------------------------- Public Methods /** - * Reset the header buffer if an error occurs during the writing of the - * headers so the error response can be written. + * Reset the header buffer if an error occurs during the writing of the headers so the error response can be + * written. */ void resetHeaderBuffer() { headerBuffer.position(0).limit(headerBuffer.capacity()); @@ -251,8 +250,7 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** - * Recycle the output buffer. This should be called when closing the - * connection. + * Recycle the output buffer. This should be called when closing the connection. */ public void recycle() { nextRequest(); @@ -261,10 +259,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** - * End processing of current HTTP request. - * Note: All bytes of the current request should have been already - * consumed. This method only resets all the pointers so that we are ready - * to parse the next HTTP request. + * End processing of current HTTP request. Note: All bytes of the current request should have been already consumed. + * This method only resets all the pointers so that we are ready to parse the next HTTP request. */ public void nextRequest() { // Recycle filters @@ -337,17 +333,17 @@ public class Http11OutputBuffer implements HttpOutputBuffer { // Write status code int status = response.getStatus(); switch (status) { - case 200: - write(Constants._200_BYTES); - break; - case 400: - write(Constants._400_BYTES); - break; - case 404: - write(Constants._404_BYTES); - break; - default: - write(status); + case 200: + write(Constants._200_BYTES); + break; + case 400: + write(Constants._400_BYTES); + break; + case 404: + write(Constants._404_BYTES); + break; + default: + write(status); } headerBuffer.put(Constants.SP); @@ -363,7 +359,7 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** * Send a header. * - * @param name Header name + * @param name Header name * @param value Header value */ public void sendHeader(MessageBytes name, MessageBytes value) { @@ -383,9 +379,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** - * This method will write the contents of the specified message bytes - * buffer to the output stream, without filtering. This method is meant to - * be used to write the response header. + * This method will write the contents of the specified message bytes buffer to the output stream, without + * filtering. This method is meant to be used to write the response header. * * @param mb data to be written */ @@ -403,8 +398,7 @@ public class Http11OutputBuffer implements HttpOutputBuffer { // filtered (apart from TAB which is 9). 127 is a control (DEL). // The values 128 to 255 are all OK. Converting those to signed // gives -128 to -1. - if ((buffer[i] > -1 && buffer[i] <= 31 && buffer[i] != 9) || - buffer[i] == 127) { + if ((buffer[i] > -1 && buffer[i] <= 31 && buffer[i] != 9) || buffer[i] == 127) { buffer[i] = ' '; } } @@ -414,9 +408,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** - * This method will write the contents of the specified byte chunk to the - * output stream, without filtering. This method is meant to be used to - * write the response header. + * This method will write the contents of the specified byte chunk to the output stream, without filtering. This + * method is meant to be used to write the response header. * * @param bc data to be written */ @@ -429,9 +422,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** - * This method will write the contents of the specified byte - * buffer to the output stream, without filtering. This method is meant to - * be used to write the response header. + * This method will write the contents of the specified byte buffer to the output stream, without filtering. This + * method is meant to be used to write the response header. * * @param b data to be written */ @@ -444,8 +436,8 @@ public class Http11OutputBuffer implements HttpOutputBuffer { /** - * This method will write the specified integer to the output stream. This - * method is meant to be used to write the response header. + * This method will write the specified integer to the output stream. This method is meant to be used to write the + * response header. * * @param value data to be written */ @@ -455,43 +447,44 @@ public class Http11OutputBuffer implements HttpOutputBuffer { int len = s.length(); checkLengthBeforeWrite(len); for (int i = 0; i < len; i++) { - char c = s.charAt (i); + char c = s.charAt(i); headerBuffer.put((byte) c); } } /** - * Checks to see if there is enough space in the buffer to write the - * requested number of bytes. + * Checks to see if there is enough space in the buffer to write the requested number of bytes. */ private void checkLengthBeforeWrite(int length) { // "+ 4": BZ 57509. Reserve space for CR/LF/COLON/SP characters that // are put directly into the buffer following this write operation. if (headerBuffer.position() + length + 4 > headerBuffer.capacity()) { - throw new HeadersTooLargeException( - sm.getString("iob.responseheadertoolarge.error")); + throw new HeadersTooLargeException(sm.getString("iob.responseheadertoolarge.error")); } } - //------------------------------------------------------ Non-blocking writes + // ------------------------------------------------------ Non-blocking writes /** * Writes any remaining buffered data. * - * @param block Should this method block until the buffer is empty - * @return <code>true</code> if data remains in the buffer (which can only - * happen in non-blocking mode) else <code>false</code>. + * @param block Should this method block until the buffer is empty + * + * @return <code>true</code> if data remains in the buffer (which can only happen in non-blocking mode) else + * <code>false</code>. + * * @throws IOException Error writing data */ - protected boolean flushBuffer(boolean block) throws IOException { + protected boolean flushBuffer(boolean block) throws IOException { return socketWrapper.flush(block); } /** * Is standard Servlet blocking IO being used for output? + * * @return <code>true</code> if this is blocking IO */ protected final boolean isBlocking() { diff --git a/java/org/apache/coyote/http11/Http11Processor.java b/java/org/apache/coyote/http11/Http11Processor.java index ac23d73128..bad930c98c 100644 --- a/java/org/apache/coyote/http11/Http11Processor.java +++ b/java/org/apache/coyote/http11/Http11Processor.java @@ -96,8 +96,8 @@ public class Http11Processor extends AbstractProcessor { /** - * Tracks how many internal filters are in the filter library so they - * are skipped when looking for pluggable filters. + * Tracks how many internal filters are in the filter library so they are skipped when looking for pluggable + * filters. */ private int pluggableFilterIndex = Integer.MAX_VALUE; @@ -109,8 +109,7 @@ public class Http11Processor extends AbstractProcessor { /** - * Flag used to indicate that the socket should be kept open (e.g. for keep - * alive or send file). + * Flag used to indicate that the socket should be kept open (e.g. for keep alive or send file). */ private volatile boolean openSocket = false; @@ -133,15 +132,13 @@ public class Http11Processor extends AbstractProcessor { /** - * Content delimiter for the request (if false, the connection will - * be closed at the end of the request). + * Content delimiter for the request (if false, the connection will be closed at the end of the request). */ private boolean contentDelimitation = true; /** - * Instance of the new protocol to use after the HTTP connection has been - * upgraded. + * Instance of the new protocol to use after the HTTP connection has been upgraded. */ private UpgradeToken upgradeToken = null; @@ -156,8 +153,7 @@ public class Http11Processor extends AbstractProcessor { super(adapter); this.protocol = protocol; - httpParser = new HttpParser(protocol.getRelaxedPathChars(), - protocol.getRelaxedQueryChars()); + httpParser = new HttpParser(protocol.getRelaxedPathChars(), protocol.getRelaxedQueryChars()); inputBuffer = new Http11InputBuffer(request, protocol.getMaxHttpRequestHeaderSize(), protocol.getRejectIllegalHeader(), httpParser); @@ -171,9 +167,9 @@ public class Http11Processor extends AbstractProcessor { outputBuffer.addFilter(new IdentityOutputFilter()); // Create and add the chunked filters. - inputBuffer.addFilter(new ChunkedInputFilter(protocol.getMaxTrailerSize(), - protocol.getAllowedTrailerHeadersInternal(), protocol.getMaxExtensionSize(), - protocol.getMaxSwallowSize())); + inputBuffer.addFilter( + new ChunkedInputFilter(protocol.getMaxTrailerSize(), protocol.getAllowedTrailerHeadersInternal(), + protocol.getMaxExtensionSize(), protocol.getMaxSwallowSize())); outputBuffer.addFilter(new ChunkedOutputFilter()); // Create and add the void filters. @@ -184,7 +180,7 @@ public class Http11Processor extends AbstractProcessor { inputBuffer.addFilter(new BufferedInputFilter(protocol.getMaxSwallowSize())); // Create and add the gzip filters. - //inputBuffer.addFilter(new GzipInputFilter()); + // inputBuffer.addFilter(new GzipInputFilter()); outputBuffer.addFilter(new GzipOutputFilter()); pluggableFilterIndex = inputBuffer.getFilters().length; @@ -192,24 +188,20 @@ public class Http11Processor extends AbstractProcessor { /** - * Determine if we must drop the connection because of the HTTP status - * code. Use the same list of codes as Apache/httpd. + * Determine if we must drop the connection because of the HTTP status code. Use the same list of codes as + * Apache/httpd. */ private static boolean statusDropsConnection(int status) { - return status == 400 /* SC_BAD_REQUEST */ || - status == 408 /* SC_REQUEST_TIMEOUT */ || - status == 411 /* SC_LENGTH_REQUIRED */ || - status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || - status == 414 /* SC_REQUEST_URI_TOO_LONG */ || - status == 500 /* SC_INTERNAL_SERVER_ERROR */ || - status == 503 /* SC_SERVICE_UNAVAILABLE */ || - status == 501 /* SC_NOT_IMPLEMENTED */; + return status == 400 /* SC_BAD_REQUEST */ || status == 408 /* SC_REQUEST_TIMEOUT */ || + status == 411 /* SC_LENGTH_REQUIRED */ || status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || + status == 414 /* SC_REQUEST_URI_TOO_LONG */ || status == 500 /* SC_INTERNAL_SERVER_ERROR */ || + status == 503 /* SC_SERVICE_UNAVAILABLE */ || status == 501 /* SC_NOT_IMPLEMENTED */; } /** - * Add an input filter to the current request. If the encoding is not - * supported, a 501 response will be returned to the client. + * Add an input filter to the current request. If the encoding is not supported, a 501 response will be returned to + * the client. */ private void addInputFilter(InputFilter[] inputFilters, String encodingName) { if (contentDelimitation) { @@ -220,7 +212,7 @@ public class Http11Processor extends AbstractProcessor { setErrorState(ErrorState.CLOSE_CLEAN, null); if (log.isDebugEnabled()) { log.debug(sm.getString("http11processor.request.prepare") + - " Transfer encoding lists chunked before [" + encodingName + "]"); + " Transfer encoding lists chunked before [" + encodingName + "]"); } return; } @@ -241,16 +233,15 @@ public class Http11Processor extends AbstractProcessor { response.setStatus(501); setErrorState(ErrorState.CLOSE_CLEAN, null); if (log.isDebugEnabled()) { - log.debug(sm.getString("http11processor.request.prepare") + - " Unsupported transfer encoding [" + encodingName + "]"); + log.debug(sm.getString("http11processor.request.prepare") + " Unsupported transfer encoding [" + + encodingName + "]"); } } } @Override - public SocketState service(SocketWrapperBase<?> socketWrapper) - throws IOException { + public SocketState service(SocketWrapperBase<?> socketWrapper) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); @@ -355,12 +346,12 @@ public class Http11Processor extends AbstractProcessor { response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); response.setHeader("Connection", "Upgrade"); response.setHeader("Upgrade", requestedProtocol); - action(ActionCode.CLOSE, null); + action(ActionCode.CLOSE, null); getAdapter().log(request, response, 0); // Continue processing using new protocol - InternalHttpUpgradeHandler upgradeHandler = - upgradeProtocol.getInternalUpgradeHandler(socketWrapper, getAdapter(), upgradeRequest); + InternalHttpUpgradeHandler upgradeHandler = upgradeProtocol + .getInternalUpgradeHandler(socketWrapper, getAdapter(), upgradeRequest); UpgradeToken upgradeToken = new UpgradeToken(upgradeHandler, null, null, requestedProtocol); action(ActionCode.UPGRADE, upgradeToken); return SocketState.UPGRADING; @@ -388,8 +379,7 @@ public class Http11Processor extends AbstractProcessor { int maxKeepAliveRequests = protocol.getMaxKeepAliveRequests(); if (maxKeepAliveRequests == 1) { keepAlive = false; - } else if (maxKeepAliveRequests > 0 && - socketWrapper.decrementKeepAlive() <= 0) { + } else if (maxKeepAliveRequests > 0 && socketWrapper.decrementKeepAlive() <= 0) { keepAlive = false; } @@ -399,11 +389,11 @@ public class Http11Processor extends AbstractProcessor { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); getAdapter().service(request, response); // Handle when the response was committed before a serious - // error occurred. Throwing a ServletException should both + // error occurred. Throwing a ServletException should both // set the status to 500 and set the errorException. // If we fail here, then the response is likely already // committed, so we can't try and set headers. - if(keepAlive && !getErrorState().isError() && !isAsync() && + if (keepAlive && !getErrorState().isError() && !isAsync() && statusDropsConnection(response.getStatus())) { setErrorState(ErrorState.CLOSE_CLEAN, null); } @@ -457,7 +447,7 @@ public class Http11Processor extends AbstractProcessor { if (!protocol.getDisableUploadTimeout()) { int connectionTimeout = protocol.getConnectionTimeout(); - if(connectionTimeout > 0) { + if (connectionTimeout > 0) { socketWrapper.setReadTimeout(connectionTimeout); } else { socketWrapper.setReadTimeout(0); @@ -622,8 +612,8 @@ public class Http11Processor extends AbstractProcessor { response.setStatus(505); setErrorState(ErrorState.CLOSE_CLEAN, null); if (log.isDebugEnabled()) { - log.debug(sm.getString("http11processor.request.prepare")+ - " Unsupported HTTP version \""+protocolMB+"\""); + log.debug(sm.getString("http11processor.request.prepare") + " Unsupported HTTP version \"" + + protocolMB + "\""); } } } @@ -662,7 +652,7 @@ public class Http11Processor extends AbstractProcessor { MessageBytes userAgentValueMB = headers.getValue("user-agent"); // Check in the restricted list, and adjust the http11 // and keepAlive flags accordingly - if(userAgentValueMB != null && !userAgentValueMB.isNull()) { + if (userAgentValueMB != null && !userAgentValueMB.isNull()) { String userAgentValue = userAgentValueMB.toString(); if (restrictedUserAgents.matcher(userAgentValue).matches()) { http11 = false; @@ -742,8 +732,7 @@ public class Http11Processor extends AbstractProcessor { if (hostValueMB != null) { // Any host in the request line must be consistent with // the Host header - if (!hostValueMB.getByteChunk().equals( - uriB, uriBCStart + pos, slashPos - pos)) { + if (!hostValueMB.getByteChunk().equals(uriB, uriBCStart + pos, slashPos - pos)) { if (protocol.getAllowHostHeaderMismatch()) { // The requirements of RFC 2616 are being // applied. If the host header and the request @@ -880,8 +869,7 @@ public class Http11Processor extends AbstractProcessor { /** - * When committing the response, we have to validate the set of headers, as - * well as setup the response filters. + * When committing the response, we have to validate the set of headers, as well as setup the response filters. */ @Override protected final void prepareResponse() throws IOException { @@ -899,11 +887,9 @@ public class Http11Processor extends AbstractProcessor { } int statusCode = response.getStatus(); - if (statusCode < 200 || statusCode == 204 || statusCode == 205 || - statusCode == 304) { + if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304) { // No entity body - outputBuffer.addActiveFilter - (outputFilters[Constants.VOID_FILTER]); + outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]); entityBody = false; contentDelimitation = true; if (statusCode == 205) { @@ -919,8 +905,7 @@ public class Http11Processor extends AbstractProcessor { boolean head = methodMB.equals("HEAD"); if (head) { // No entity body - outputBuffer.addActiveFilter - (outputFilters[Constants.VOID_FILTER]); + outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } @@ -944,8 +929,7 @@ public class Http11Processor extends AbstractProcessor { } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { - headers.setValue("Content-Language") - .setString(contentLanguage); + headers.setValue("Content-Language").setString(contentLanguage); } } @@ -979,8 +963,7 @@ public class Http11Processor extends AbstractProcessor { // Add date header unless application has already set one (e.g. in a // Caching Filter) if (headers.getValue("Date") == null) { - headers.addValue("Date").setString( - FastHttpDateFormat.getCurrentDate()); + headers.addValue("Date").setString(FastHttpDateFormat.getCurrentDate()); } // FIXME: Add transfer encoding header @@ -988,7 +971,7 @@ public class Http11Processor extends AbstractProcessor { if ((entityBody) && (!contentDelimitation) || connectionClosePresent) { // Disable keep-alive if: // - there is a response body but way for the client to determine - // the content length information; or + // the content length information; or // - there is a "connection: close" header present // This will cause the "connection: close" header to be added if it // is not already present. @@ -1011,8 +994,7 @@ public class Http11Processor extends AbstractProcessor { if (!keepAlive) { // Avoid adding the close header twice if (!connectionClosePresent) { - headers.addValue(Constants.CONNECTION).setString( - Constants.CLOSE); + headers.addValue(Constants.CONNECTION).setString(Constants.CLOSE); } } else if (!getErrorState().isError()) { if (!http11) { @@ -1020,8 +1002,8 @@ public class Http11Processor extends AbstractProcessor { } if (protocol.getUseKeepAliveResponseHeader()) { - boolean connectionKeepAlivePresent = - isConnectionToken(request.getMimeHeaders(), Constants.KEEP_ALIVE_HEADER_VALUE_TOKEN); + boolean connectionKeepAlivePresent = isConnectionToken(request.getMimeHeaders(), + Constants.KEEP_ALIVE_HEADER_VALUE_TOKEN); if (connectionKeepAlivePresent) { int keepAliveTimeout = protocol.getKeepAliveTimeout(); @@ -1035,10 +1017,11 @@ public class Http11Processor extends AbstractProcessor { // else create the header MessageBytes connectionHeaderValue = headers.getValue(Constants.CONNECTION); if (connectionHeaderValue == null) { - headers.addValue(Constants.CONNECTION).setString(Constants.KEEP_ALIVE_HEADER_VALUE_TOKEN); + headers.addValue(Constants.CONNECTION) + .setString(Constants.KEEP_ALIVE_HEADER_VALUE_TOKEN); } else { - connectionHeaderValue.setString( - connectionHeaderValue.getString() + ", " + Constants.KEEP_ALIVE_HEADER_VALUE_TOKEN); + connectionHeaderValue.setString(connectionHeaderValue.getString() + ", " + + Constants.KEEP_ALIVE_HEADER_VALUE_TOKEN); } } } @@ -1076,8 +1059,8 @@ public class Http11Processor extends AbstractProcessor { outputBuffer.sendHeader(headers.getName(i), headers.getValue(i)); } catch (IllegalArgumentException iae) { // Log the problematic header - log.warn(sm.getString("http11processor.response.invalidHeader", - headers.getName(i), headers.getValue(i)), iae); + log.warn(sm.getString("http11processor.response.invalidHeader", headers.getName(i), + headers.getValue(i)), iae); // Remove the problematic header headers.removeHeader(i); size--; @@ -1112,27 +1095,23 @@ public class Http11Processor extends AbstractProcessor { private void prepareSendfile(OutputFilter[] outputFilters) { - String fileName = (String) request.getAttribute( - org.apache.coyote.Constants.SENDFILE_FILENAME_ATTR); + String fileName = (String) request.getAttribute(org.apache.coyote.Constants.SENDFILE_FILENAME_ATTR); if (fileName == null) { sendfileData = null; } else { // No entity body sent here outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]); contentDelimitation = true; - long pos = ((Long) request.getAttribute( - org.apache.coyote.Constants.SENDFILE_FILE_START_ATTR)).longValue(); - long end = ((Long) request.getAttribute( - org.apache.coyote.Constants.SENDFILE_FILE_END_ATTR)).longValue(); + long pos = ((Long) request.getAttribute(org.apache.coyote.Constants.SENDFILE_FILE_START_ATTR)).longValue(); + long end = ((Long) request.getAttribute(org.apache.coyote.Constants.SENDFILE_FILE_END_ATTR)).longValue(); sendfileData = socketWrapper.createSendfileData(fileName, pos, end - pos); } } /* - * Note: populateHost() is not over-ridden. - * request.serverName() will be set to return the default host name by - * the Mapper. + * Note: populateHost() is not over-ridden. request.serverName() will be set to return the default host name by the + * Mapper. */ @@ -1198,9 +1177,8 @@ public class Http11Processor extends AbstractProcessor { /* - * No more input will be passed to the application. Remaining input will be - * swallowed or the connection dropped depending on the error and - * expectation status. + * No more input will be passed to the application. Remaining input will be swallowed or the connection dropped + * depending on the error and expectation status. */ private void endRequest() { if (getErrorState().isError()) { @@ -1310,20 +1288,18 @@ public class Http11Processor extends AbstractProcessor { // Consume and buffer the request body, so that it does not // interfere with the client's handshake messages InputFilter[] inputFilters = inputBuffer.getFilters(); - ((BufferedInputFilter) inputFilters[Constants.BUFFERED_FILTER]).setLimit( - protocol.getMaxSavePostSize()); + ((BufferedInputFilter) inputFilters[Constants.BUFFERED_FILTER]).setLimit(protocol.getMaxSavePostSize()); inputBuffer.addActiveFilter(inputFilters[Constants.BUFFERED_FILTER]); /* - * Outside the try/catch because we want I/O errors during - * renegotiation to be thrown for the caller to handle since they - * will be fatal to the connection. + * Outside the try/catch because we want I/O errors during renegotiation to be thrown for the caller to + * handle since they will be fatal to the connection. */ socketWrapper.doClientAuth(sslSupport); try { /* - * Errors processing the cert chain do not affect the client - * connection so they can be logged and swallowed here. + * Errors processing the cert chain do not affect the client connection so they can be logged and + * swallowed here. */ Object sslO = sslSupport.getPeerCertificateChain(); if (sslO != null) { @@ -1430,15 +1406,15 @@ public class Http11Processor extends AbstractProcessor { } result = socketWrapper.processSendfile(sendfileData); switch (result) { - case ERROR: - // Write failed - if (log.isDebugEnabled()) { - log.debug(sm.getString("http11processor.sendfile.error")); - } - setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null); - //$FALL-THROUGH$ - default: - sendfileData = null; + case ERROR: + // Write failed + if (log.isDebugEnabled()) { + log.debug(sm.getString("http11processor.sendfile.error")); + } + setErrorState(ErrorState.CLOSE_CONNECTION_NOW, null); + //$FALL-THROUGH$ + default: + sendfileData = null; } } return result; diff --git a/java/org/apache/coyote/http11/HttpOutputBuffer.java b/java/org/apache/coyote/http11/HttpOutputBuffer.java index 6127000ad6..1a66ad7979 100644 --- a/java/org/apache/coyote/http11/HttpOutputBuffer.java +++ b/java/org/apache/coyote/http11/HttpOutputBuffer.java @@ -23,9 +23,8 @@ import org.apache.coyote.OutputBuffer; public interface HttpOutputBuffer extends OutputBuffer { /** - * Finish writing the current response. It is acceptable to write extra - * bytes using {@link #doWrite(java.nio.ByteBuffer)} during the execution of - * this method. + * Finish writing the current response. It is acceptable to write extra bytes using + * {@link #doWrite(java.nio.ByteBuffer)} during the execution of this method. * * @throws IOException If an I/O error occurs while writing to the client */ diff --git a/java/org/apache/coyote/http11/InputFilter.java b/java/org/apache/coyote/http11/InputFilter.java index cc76bed06f..a68ee7a5ef 100644 --- a/java/org/apache/coyote/http11/InputFilter.java +++ b/java/org/apache/coyote/http11/InputFilter.java @@ -46,9 +46,8 @@ public interface InputFilter extends InputBuffer { /** * Get the name of the encoding handled by this filter. * - * @return The encoding name as a byte chunk to facilitate comparison with - * the value read from the HTTP headers which will also be a - * ByteChunk + * @return The encoding name as a byte chunk to facilitate comparison with the value read from the HTTP headers + * which will also be a ByteChunk */ ByteChunk getEncodingName(); @@ -64,10 +63,9 @@ public interface InputFilter extends InputBuffer { /** * End the current request. * - * @return 0 is the expected return value. A positive value indicates that - * too many bytes were read. This method is allowed to use buffer.doRead - * to consume extra bytes. The result of this method can't be negative (if - * an error happens, an IOException should be thrown instead). + * @return 0 is the expected return value. A positive value indicates that too many bytes were read. This method is + * allowed to use buffer.doRead to consume extra bytes. The result of this method can't be negative (if + * an error happens, an IOException should be thrown instead). * * @throws IOException If an error happens */ @@ -77,8 +75,7 @@ public interface InputFilter extends InputBuffer { /** * Has the request body been read fully? * - * @return {@code true} if the request body has been fully read, otherwise - * {@code false} + * @return {@code true} if the request body has been fully read, otherwise {@code false} */ boolean isFinished(); } diff --git a/java/org/apache/coyote/http11/OutputFilter.java b/java/org/apache/coyote/http11/OutputFilter.java index d2481554e0..040ec3bc25 100644 --- a/java/org/apache/coyote/http11/OutputFilter.java +++ b/java/org/apache/coyote/http11/OutputFilter.java @@ -26,9 +26,8 @@ import org.apache.coyote.Response; public interface OutputFilter extends HttpOutputBuffer { /** - * Some filters need additional parameters from the response. All the - * necessary reading can occur in that method, as this method is called - * after the response header processing is complete. + * Some filters need additional parameters from the response. All the necessary reading can occur in that method, as + * this method is called after the response header processing is complete. * * @param response The response to associate with this OutputFilter */ --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org