This is an automated email from the ASF dual-hosted git repository. markt pushed a commit to branch 10.1.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit 969c239e093dea6ce89d86d033704c9726eb00f7 Author: Mark Thomas <ma...@apache.org> AuthorDate: Tue Apr 11 16:43:20 2023 +0100 Code clean-up. No functional change. --- .../tomcat/util/http/ConcurrentDateFormat.java | 5 +- .../apache/tomcat/util/http/CookieProcessor.java | 26 ++- .../tomcat/util/http/CookieProcessorBase.java | 11 +- .../tomcat/util/http/FastHttpDateFormat.java | 16 +- java/org/apache/tomcat/util/http/HeaderUtil.java | 10 +- java/org/apache/tomcat/util/http/MimeHeaders.java | 185 +++++++++++---------- java/org/apache/tomcat/util/http/Parameters.java | 111 ++++++------- java/org/apache/tomcat/util/http/RequestUtil.java | 22 ++- .../tomcat/util/http/Rfc6265CookieProcessor.java | 86 +++++----- java/org/apache/tomcat/util/http/ServerCookie.java | 14 +- .../org/apache/tomcat/util/http/ServerCookies.java | 11 +- 11 files changed, 234 insertions(+), 263 deletions(-) diff --git a/java/org/apache/tomcat/util/http/ConcurrentDateFormat.java b/java/org/apache/tomcat/util/http/ConcurrentDateFormat.java index 02a456f20a..eb678aa5fb 100644 --- a/java/org/apache/tomcat/util/http/ConcurrentDateFormat.java +++ b/java/org/apache/tomcat/util/http/ConcurrentDateFormat.java @@ -25,9 +25,8 @@ import java.util.TimeZone; import java.util.concurrent.ConcurrentLinkedQueue; /** - * A thread safe wrapper around {@link SimpleDateFormat} that does not make use - * of ThreadLocal and - broadly - only creates enough SimpleDateFormat objects - * to satisfy the concurrency requirements. + * A thread safe wrapper around {@link SimpleDateFormat} that does not make use of ThreadLocal and - broadly - only + * creates enough SimpleDateFormat objects to satisfy the concurrency requirements. */ public class ConcurrentDateFormat { diff --git a/java/org/apache/tomcat/util/http/CookieProcessor.java b/java/org/apache/tomcat/util/http/CookieProcessor.java index 6ea0fe9b18..d84cc87099 100644 --- a/java/org/apache/tomcat/util/http/CookieProcessor.java +++ b/java/org/apache/tomcat/util/http/CookieProcessor.java @@ -27,33 +27,27 @@ public interface CookieProcessor { * Parse the provided headers into server cookie objects. * * @param headers The HTTP headers to parse - * @param serverCookies The server cookies object to populate with the - * results of the parsing + * @param serverCookies The server cookies object to populate with the results of the parsing */ void parseCookieHeader(MimeHeaders headers, ServerCookies serverCookies); /** - * Generate the {@code Set-Cookie} HTTP header value for the given Cookie. - * This method receives as parameter the servlet request so that it can make - * decisions based on request properties. One such use-case is decide if the - * SameSite attribute should be added to the cookie based on the User-Agent - * or other request header because there are browser versions incompatible - * with the SameSite attribute. This is described by <a - * href="https://www.chromium.org/updates/same-site/incompatible-clients">the - * Chromium project</a>. + * Generate the {@code Set-Cookie} HTTP header value for the given Cookie. This method receives as parameter the + * servlet request so that it can make decisions based on request properties. One such use-case is decide if the + * SameSite attribute should be added to the cookie based on the User-Agent or other request header because there + * are browser versions incompatible with the SameSite attribute. This is described by + * <a href="https://www.chromium.org/updates/same-site/incompatible-clients">the Chromium project</a>. * * @param request The servlet request + * @param cookie The cookie for which the header will be generated * - * @param cookie The cookie for which the header will be generated - * - * @return The header value in a form that can be added directly to the - * response + * @return The header value in a form that can be added directly to the response */ String generateHeader(Cookie cookie, HttpServletRequest request); /** - * Obtain the character set that will be used when converting between bytes - * and characters when parsing and/or generating HTTP headers for cookies. + * Obtain the character set that will be used when converting between bytes and characters when parsing and/or + * generating HTTP headers for cookies. * * @return The character set used for byte<->character conversions */ diff --git a/java/org/apache/tomcat/util/http/CookieProcessorBase.java b/java/org/apache/tomcat/util/http/CookieProcessorBase.java index 5c3b08bfd9..00c852cc75 100644 --- a/java/org/apache/tomcat/util/http/CookieProcessorBase.java +++ b/java/org/apache/tomcat/util/http/CookieProcessorBase.java @@ -26,12 +26,11 @@ public abstract class CookieProcessorBase implements CookieProcessor { private static final String COOKIE_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z"; - protected static final ThreadLocal<DateFormat> COOKIE_DATE_FORMAT = - ThreadLocal.withInitial(() -> { - DateFormat df = new SimpleDateFormat(COOKIE_DATE_PATTERN, Locale.US); - df.setTimeZone(TimeZone.getTimeZone("GMT")); - return df; - }); + protected static final ThreadLocal<DateFormat> COOKIE_DATE_FORMAT = ThreadLocal.withInitial(() -> { + DateFormat df = new SimpleDateFormat(COOKIE_DATE_PATTERN, Locale.US); + df.setTimeZone(TimeZone.getTimeZone("GMT")); + return df; + }); protected static final String ANCIENT_DATE; diff --git a/java/org/apache/tomcat/util/http/FastHttpDateFormat.java b/java/org/apache/tomcat/util/http/FastHttpDateFormat.java index 83b79a2f8b..f33aa851a3 100644 --- a/java/org/apache/tomcat/util/http/FastHttpDateFormat.java +++ b/java/org/apache/tomcat/util/http/FastHttpDateFormat.java @@ -34,8 +34,8 @@ public final class FastHttpDateFormat { // -------------------------------------------------------------- Variables - private static final int CACHE_SIZE = - Integer.getInteger("org.apache.tomcat.util.http.FastHttpDateFormat.CACHE_SIZE", 1000).intValue(); + private static final int CACHE_SIZE = Integer + .getInteger("org.apache.tomcat.util.http.FastHttpDateFormat.CACHE_SIZE", 1000).intValue(); // HTTP date formats @@ -57,8 +57,8 @@ public final class FastHttpDateFormat { FORMAT_OBSOLETE_RFC850 = new ConcurrentDateFormat(DATE_OBSOLETE_RFC850, Locale.US, tz); FORMAT_OBSOLETE_ASCTIME = new ConcurrentDateFormat(DATE_OBSOLETE_ASCTIME, Locale.US, tz); - httpParseFormats = new ConcurrentDateFormat[] { - FORMAT_RFC5322, FORMAT_OBSOLETE_RFC850, FORMAT_OBSOLETE_ASCTIME }; + httpParseFormats = new ConcurrentDateFormat[] { FORMAT_RFC5322, FORMAT_OBSOLETE_RFC850, + FORMAT_OBSOLETE_ASCTIME }; } /** @@ -90,6 +90,7 @@ public final class FastHttpDateFormat { /** * Get the current date in HTTP format. + * * @return the HTTP date */ public static String getCurrentDate() { @@ -105,7 +106,9 @@ public final class FastHttpDateFormat { /** * Get the HTTP format of the specified date. + * * @param value The date + * * @return the HTTP date */ public static String formatDate(long value) { @@ -123,9 +126,10 @@ public final class FastHttpDateFormat { /** * Try to parse the given date as an HTTP date. + * * @param value The HTTP date - * @return the date as a long or <code>-1</code> if the value cannot be - * parsed + * + * @return the date as a long or <code>-1</code> if the value cannot be parsed */ public static long parseDate(String value) { diff --git a/java/org/apache/tomcat/util/http/HeaderUtil.java b/java/org/apache/tomcat/util/http/HeaderUtil.java index cb40cabede..59f06c4c35 100644 --- a/java/org/apache/tomcat/util/http/HeaderUtil.java +++ b/java/org/apache/tomcat/util/http/HeaderUtil.java @@ -19,17 +19,15 @@ package org.apache.tomcat.util.http; public class HeaderUtil { /** - * Converts an HTTP header line in byte form to a printable String. - * Bytes corresponding to visible ASCII characters will converted to those - * characters. All other bytes (0x00 to 0x1F, 0x7F to OxFF) will be - * represented in 0xNN form. + * Converts an HTTP header line in byte form to a printable String. Bytes corresponding to visible ASCII characters + * will converted to those characters. All other bytes (0x00 to 0x1F, 0x7F to OxFF) will be represented in 0xNN + * form. * * @param bytes Contains an HTTP header line * @param offset The start position of the header line in the array * @param len The length of the HTTP header line * - * @return A String with non-printing characters replaced by the 0xNN - * equivalent + * @return A String with non-printing characters replaced by the 0xNN equivalent */ public static String toPrintableString(byte[] bytes, int offset, int len) { StringBuilder result = new StringBuilder(); diff --git a/java/org/apache/tomcat/util/http/MimeHeaders.java b/java/org/apache/tomcat/util/http/MimeHeaders.java index 89007660a8..f0bb2aef48 100644 --- a/java/org/apache/tomcat/util/http/MimeHeaders.java +++ b/java/org/apache/tomcat/util/http/MimeHeaders.java @@ -65,26 +65,22 @@ import org.apache.tomcat.util.res.StringManager; /** - * Memory-efficient repository for Mime Headers. When the object is recycled, it - * will keep the allocated headers[] and all the MimeHeaderField - no GC is generated. - * <p> - * For input headers it is possible to use the MessageByte for Fields - so no GC - * will be generated. + * Memory-efficient repository for Mime Headers. When the object is recycled, it will keep the allocated headers[] and + * all the MimeHeaderField - no GC is generated. * <p> - * The only garbage is generated when using the String for header names/values - - * this can't be avoided when the servlet calls header methods, but is easy - * to avoid inside tomcat. The goal is to use _only_ MessageByte-based Fields, - * and reduce to 0 the memory overhead of tomcat. - * <p> - * - * TODO: - * <ul> - * <li>one-buffer parsing - for http (other protocols don't need that)</li> - * <li>remove unused methods</li> - * <li>External enumerations, with 0 GC.</li> - * <li>use HeaderName ID</li> - * </ul> - * + * For input headers it is possible to use the MessageByte for Fields - so no GC will be generated. + * <p> + * The only garbage is generated when using the String for header names/values - this can't be avoided when the servlet + * calls header methods, but is easy to avoid inside tomcat. The goal is to use _only_ MessageByte-based Fields, and + * reduce to 0 the memory overhead of tomcat. + * <p> + * TODO: + * <ul> + * <li>one-buffer parsing - for http (other protocols don't need that)</li> + * <li>remove unused methods</li> + * <li>External enumerations, with 0 GC.</li> + * <li>use HeaderName ID</li> + * </ul> * * @author d...@eng.sun.com * @author James Todd [go...@eng.sun.com] @@ -93,19 +89,17 @@ import org.apache.tomcat.util.res.StringManager; */ public class MimeHeaders { /** - * Initial size - should be == average number of headers per request - * XXX make it configurable ( fine-tuning of web-apps ) + * Initial size - should be == average number of headers per request XXX make it configurable ( fine-tuning of + * web-apps ) */ - public static final int DEFAULT_HEADER_SIZE=8; + public static final int DEFAULT_HEADER_SIZE = 8; - private static final StringManager sm = - StringManager.getManager("org.apache.tomcat.util.http"); + private static final StringManager sm = StringManager.getManager("org.apache.tomcat.util.http"); /** * The header fields. */ - private MimeHeaderField[] headers = new - MimeHeaderField[DEFAULT_HEADER_SIZE]; + private MimeHeaderField[] headers = new MimeHeaderField[DEFAULT_HEADER_SIZE]; /** * The current number of header fields. @@ -126,6 +120,7 @@ public class MimeHeaders { /** * Set limit on the number of header fields. + * * @param limit The new limit */ public void setLimit(int limit) { @@ -157,7 +152,7 @@ public class MimeHeaders { } /** - * EXPENSIVE!!! only for debugging. + * EXPENSIVE!!! only for debugging. */ @Override public String toString() { @@ -198,8 +193,9 @@ public class MimeHeaders { /** * @param n The header index - * @return the Nth header name, or null if there is no such header. - * This may be used to iterate through all header fields. + * + * @return the Nth header name, or null if there is no such header. This may be used to iterate through all header + * fields. */ public MessageBytes getName(int n) { return n >= 0 && n < count ? headers[n].getName() : null; @@ -207,8 +203,9 @@ public class MimeHeaders { /** * @param n The header index - * @return the Nth header value, or null if there is no such header. - * This may be used to iterate through all header fields. + * + * @return the Nth header value, or null if there is no such header. This may be used to iterate through all header + * fields. */ public MessageBytes getValue(int n) { return n >= 0 && n < count ? headers[n].getValue() : null; @@ -216,13 +213,15 @@ public class MimeHeaders { /** * Find the index of a header with the given name. - * @param name The header name + * + * @param name The header name * @param starting Index on which to start looking + * * @return the header index */ - public int findHeader( String name, int starting ) { + public int findHeader(String name, int starting) { // We can use a hash - but it's not clear how much - // benefit you can get - there is an overhead + // benefit you can get - there is an overhead // and the number of headers is small (4-5 ?) // Another problem is that we'll pay the overhead // of constructing the hashtable @@ -239,9 +238,9 @@ public class MimeHeaders { // -------------------- -------------------- /** - * Returns an enumeration of strings representing the header field names. - * Field names may appear multiple times in this enumeration, indicating - * that multiple fields with that name exist in this header. + * Returns an enumeration of strings representing the header field names. Field names may appear multiple times in + * this enumeration, indicating that multiple fields with that name exist in this header. + * * @return the enumeration */ public Enumeration<String> names() { @@ -256,13 +255,11 @@ public class MimeHeaders { /** - * Adds a partially constructed field to the header. This - * field has not had its name or value initialized. + * Adds a partially constructed field to the header. This field has not had its name or value initialized. */ private MimeHeaderField createHeader() { if (limit > -1 && count >= limit) { - throw new IllegalStateException(sm.getString( - "headers.maxCountFail", Integer.valueOf(limit))); + throw new IllegalStateException(sm.getString("headers.maxCountFail", Integer.valueOf(limit))); } MimeHeaderField mh; int len = headers.length; @@ -284,43 +281,46 @@ public class MimeHeaders { } /** - * Create a new named header , return the MessageBytes - * container for the new value + * Create a new named header , return the MessageBytes container for the new value + * * @param name The header name + * * @return the message bytes container for the value */ - public MessageBytes addValue( String name ) { + public MessageBytes addValue(String name) { MimeHeaderField mh = createHeader(); mh.getName().setString(name); return mh.getValue(); } /** - * Create a new named header using un-translated byte[]. - * The conversion to chars can be delayed until - * encoding is known. - * @param b The header name bytes + * Create a new named header using un-translated byte[]. The conversion to chars can be delayed until encoding is + * known. + * + * @param b The header name bytes * @param startN Offset - * @param len Length + * @param len Length + * * @return the message bytes container for the value */ public MessageBytes addValue(byte b[], int startN, int len) { - MimeHeaderField mhf=createHeader(); + MimeHeaderField mhf = createHeader(); mhf.getName().setBytes(b, startN, len); return mhf.getValue(); } /** - * Allow "set" operations, which removes all current values - * for this header. + * Allow "set" operations, which removes all current values for this header. + * * @param name The header name + * * @return the message bytes container for the value */ - public MessageBytes setValue( String name ) { - for ( int i = 0; i < count; i++ ) { - if(headers[i].getName().equalsIgnoreCase(name)) { - for ( int j=i+1; j < count; j++ ) { - if(headers[j].getName().equalsIgnoreCase(name)) { + public MessageBytes setValue(String name) { + for (int i = 0; i < count; i++) { + if (headers[i].getName().equalsIgnoreCase(name)) { + for (int j = i + 1; j < count; j++) { + if (headers[j].getName().equalsIgnoreCase(name)) { removeHeader(j--); } } @@ -332,12 +332,13 @@ public class MimeHeaders { return mh.getValue(); } - //-------------------- Getting headers -------------------- + // -------------------- Getting headers -------------------- /** - * Finds and returns a header field with the given name. If no such - * field exists, null is returned. If more than one such field is - * in the header, an arbitrary one is returned. + * Finds and returns a header field with the given name. If no such field exists, null is returned. If more than one + * such field is in the header, an arbitrary one is returned. + * * @param name The header name + * * @return the value */ public MessageBytes getValue(String name) { @@ -350,11 +351,13 @@ public class MimeHeaders { } /** - * Finds and returns a unique header field with the given name. If no such - * field exists, null is returned. If the specified header field is not - * unique then an {@link IllegalArgumentException} is thrown. + * Finds and returns a unique header field with the given name. If no such field exists, null is returned. If the + * specified header field is not unique then an {@link IllegalArgumentException} is thrown. + * * @param name The header name + * * @return the value if unique + * * @throws IllegalArgumentException if the header has multiple values */ public MessageBytes getUniqueValue(String name) { @@ -380,8 +383,8 @@ public class MimeHeaders { // -------------------- Removing -------------------- /** - * Removes a header field with the specified name. Does nothing - * if such a field could not be found. + * Removes a header field with the specified name. Does nothing if such a field could not be found. + * * @param name the name of the header field to be removed */ public void removeHeader(String name) { @@ -397,6 +400,7 @@ public class MimeHeaders { /** * Reset, move to the end and then reduce count by 1. + * * @param idx the index of the header to remove. */ public void removeHeader(int idx) { @@ -411,7 +415,7 @@ public class MimeHeaders { mh.recycle(); // Move the remaining headers - System.arraycopy(headers, idx + 1, headers, idx, count - idx -1); + System.arraycopy(headers, idx + 1, headers, idx, count - idx - 1); // Place the removed header at the end headers[count - 1] = mh; @@ -423,9 +427,8 @@ public class MimeHeaders { } /** - * Enumerate the distinct header names. Each nextElement() is O(n) ( a - * comparison is done with all previous elements ). This is less frequent than - * add() - we want to keep add O(1). + * Enumerate the distinct header names. Each nextElement() is O(n) ( a comparison is done with all previous elements ). + * This is less frequent than add() - we want to keep add O(1). */ class NamesEnumerator implements Enumeration<String> { private int pos; @@ -434,24 +437,24 @@ class NamesEnumerator implements Enumeration<String> { private final MimeHeaders headers; NamesEnumerator(MimeHeaders headers) { - this.headers=headers; - pos=0; + this.headers = headers; + pos = 0; size = headers.size(); findNext(); } private void findNext() { - next=null; - for(; pos< size; pos++ ) { - next=headers.getName( pos ).toString(); - for( int j=0; j<pos ; j++ ) { - if( headers.getName( j ).equalsIgnoreCase( next )) { + next = null; + for (; pos < size; pos++) { + next = headers.getName(pos).toString(); + for (int j = 0; j < pos; j++) { + if (headers.getName(j).equalsIgnoreCase(next)) { // duplicate. - next=null; + next = null; break; } } - if( next!=null ) { + if (next != null) { // it's not a duplicate break; } @@ -463,12 +466,12 @@ class NamesEnumerator implements Enumeration<String> { @Override public boolean hasMoreElements() { - return next!=null; + return next != null; } @Override public String nextElement() { - String current=next; + String current = next; findNext(); return current; } @@ -485,19 +488,19 @@ class ValuesEnumerator implements Enumeration<String> { private final String name; ValuesEnumerator(MimeHeaders headers, String name) { - this.name=name; - this.headers=headers; - pos=0; + this.name = name; + this.headers = headers; + pos = 0; size = headers.size(); findNext(); } private void findNext() { - next=null; - for(; pos< size; pos++ ) { - MessageBytes n1=headers.getName( pos ); - if( n1.equalsIgnoreCase( name )) { - next=headers.getValue( pos ); + next = null; + for (; pos < size; pos++) { + MessageBytes n1 = headers.getName(pos); + if (n1.equalsIgnoreCase(name)) { + next = headers.getValue(pos); break; } } @@ -506,12 +509,12 @@ class ValuesEnumerator implements Enumeration<String> { @Override public boolean hasMoreElements() { - return next!=null; + return next != null; } @Override public String nextElement() { - MessageBytes current=next; + MessageBytes current = next; findNext(); return current.toString(); } diff --git a/java/org/apache/tomcat/util/http/Parameters.java b/java/org/apache/tomcat/util/http/Parameters.java index a3a5046ae8..d4cc5868b1 100644 --- a/java/org/apache/tomcat/util/http/Parameters.java +++ b/java/org/apache/tomcat/util/http/Parameters.java @@ -42,12 +42,10 @@ public final class Parameters { private static final UserDataHelper maxParamCountLog = new UserDataHelper(log); - private static final StringManager sm = - StringManager.getManager("org.apache.tomcat.util.http"); + private static final StringManager sm = StringManager.getManager("org.apache.tomcat.util.http"); - private final Map<String,ArrayList<String>> paramHashValues = - new LinkedHashMap<>(); - private boolean didQueryParameters=false; + private final Map<String, ArrayList<String>> paramHashValues = new LinkedHashMap<>(); + private boolean didQueryParameters = false; private MessageBytes queryMB; @@ -61,8 +59,8 @@ public final class Parameters { private int parameterCount = 0; /** - * Set to the reason for the failure (the first failure if there is more - * than one) if there were failures during parameter parsing. + * Set to the reason for the failure (the first failure if there is more than one) if there were failures during + * parameter parsing. */ private FailReason parseFailedReason = null; @@ -70,8 +68,8 @@ public final class Parameters { // NO-OP } - public void setQuery( MessageBytes queryMB ) { - this.queryMB=queryMB; + public void setQuery(MessageBytes queryMB) { + this.queryMB = queryMB; } public void setLimit(int limit) { @@ -87,7 +85,7 @@ public final class Parameters { charset = DEFAULT_BODY_CHARSET; } this.charset = charset; - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Set encoding to " + charset.name()); } } @@ -98,7 +96,7 @@ public final class Parameters { } this.queryStringCharset = queryStringCharset; - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Set query string encoding to " + queryStringCharset.name()); } } @@ -155,11 +153,11 @@ public final class Parameters { return Collections.enumeration(paramHashValues.keySet()); } - public String getParameter(String name ) { + public String getParameter(String name) { handleQueryParameters(); ArrayList<String> values = paramHashValues.get(name); if (values != null) { - if(values.size() == 0) { + if (values.size() == 0) { return ""; } return values.get(0); @@ -167,6 +165,7 @@ public final class Parameters { return null; } } + // -------------------- Processing -------------------- /** * Process the query string into parameters @@ -182,7 +181,7 @@ public final class Parameters { return; } - if(log.isDebugEnabled()) { + if (log.isDebugEnabled()) { log.debug("Decoding query " + decodedQuery + " " + queryStringCharset.name()); } @@ -196,49 +195,46 @@ public final class Parameters { } - public void addParameter( String key, String value ) - throws IllegalStateException { + public void addParameter(String key, String value) throws IllegalStateException { - if( key==null ) { + if (key == null) { return; } - parameterCount ++; + parameterCount++; if (limit > -1 && parameterCount > limit) { // Processing this parameter will push us over the limit. ISE is // what Request.parseParts() uses for requests that are too big setParseFailedReason(FailReason.TOO_MANY_PARAMETERS); - throw new IllegalStateException(sm.getString( - "parameters.maxCountFail", Integer.valueOf(limit))); + throw new IllegalStateException(sm.getString("parameters.maxCountFail", Integer.valueOf(limit))); } paramHashValues.computeIfAbsent(key, k -> new ArrayList<>(1)).add(value); } - public void setURLDecoder( UDecoder u ) { - urlDec=u; + public void setURLDecoder(UDecoder u) { + urlDec = u; } // -------------------- Parameter parsing -------------------- // we are called from a single thread - we can do it the hard way // if needed - private final ByteChunk tmpName=new ByteChunk(); - private final ByteChunk tmpValue=new ByteChunk(); - private final ByteChunk origName=new ByteChunk(); - private final ByteChunk origValue=new ByteChunk(); + private final ByteChunk tmpName = new ByteChunk(); + private final ByteChunk tmpValue = new ByteChunk(); + private final ByteChunk origName = new ByteChunk(); + private final ByteChunk origValue = new ByteChunk(); private static final Charset DEFAULT_BODY_CHARSET = StandardCharsets.ISO_8859_1; private static final Charset DEFAULT_URI_CHARSET = StandardCharsets.UTF_8; - public void processParameters( byte bytes[], int start, int len ) { + public void processParameters(byte bytes[], int start, int len) { processParameters(bytes, start, len, charset); } private void processParameters(byte bytes[], int start, int len, Charset charset) { - if(log.isDebugEnabled()) { - log.debug(sm.getString("parameters.bytes", - new String(bytes, start, len, DEFAULT_BODY_CHARSET))); + if (log.isDebugEnabled()) { + log.debug(sm.getString("parameters.bytes", new String(bytes, start, len, DEFAULT_BODY_CHARSET))); } int decodeFailCount = 0; @@ -246,7 +242,7 @@ public final class Parameters { int pos = start; int end = start + len; - while(pos < end) { + while (pos < end) { int nameStart = pos; int nameEnd = -1; int valueStart = -1; @@ -258,7 +254,7 @@ public final class Parameters { boolean parameterComplete = false; do { - switch(bytes[pos]) { + switch (bytes[pos]) { case '=': if (parsingName) { // Name finished. Value starts from next character @@ -276,7 +272,7 @@ public final class Parameters { nameEnd = pos; } else { // Value finished - valueEnd = pos; + valueEnd = pos; } parameterComplete = true; pos++; @@ -289,10 +285,10 @@ public final class Parameters { } else { decodeValue = true; } - pos ++; + pos++; break; default: - pos ++; + pos++; break; } } while (!parameterComplete && pos < end); @@ -300,18 +296,17 @@ public final class Parameters { if (pos == end) { if (nameEnd == -1) { nameEnd = pos; - } else if (valueStart > -1 && valueEnd == -1){ + } else if (valueStart > -1 && valueEnd == -1) { valueEnd = pos; } } if (log.isDebugEnabled() && valueStart == -1) { - log.debug(sm.getString("parameters.noequal", - Integer.valueOf(nameStart), Integer.valueOf(nameEnd), - new String(bytes, nameStart, nameEnd-nameStart, DEFAULT_BODY_CHARSET))); + log.debug(sm.getString("parameters.noequal", Integer.valueOf(nameStart), Integer.valueOf(nameEnd), + new String(bytes, nameStart, nameEnd - nameStart, DEFAULT_BODY_CHARSET))); } - if (nameEnd <= nameStart ) { + if (nameEnd <= nameStart) { if (valueStart == -1) { // && if (log.isDebugEnabled()) { @@ -325,13 +320,11 @@ public final class Parameters { if (logMode != null) { String extract; if (valueEnd > nameStart) { - extract = new String(bytes, nameStart, valueEnd - nameStart, - DEFAULT_BODY_CHARSET); + extract = new String(bytes, nameStart, valueEnd - nameStart, DEFAULT_BODY_CHARSET); } else { extract = ""; } - String message = sm.getString("parameters.invalidChunk", - Integer.valueOf(nameStart), + String message = sm.getString("parameters.invalidChunk", Integer.valueOf(nameStart), Integer.valueOf(valueEnd), extract); switch (logMode) { case INFO_THEN_DEBUG: @@ -403,8 +396,7 @@ public final class Parameters { String message = ise.getMessage(); switch (logMode) { case INFO_THEN_DEBUG: - message += sm.getString( - "parameters.maxCountFail.fallToDebug"); + message += sm.getString("parameters.maxCountFail.fallToDebug"); //$FALL-THROUGH$ case INFO: log.info(message); @@ -420,14 +412,14 @@ public final class Parameters { decodeFailCount++; if (decodeFailCount == 1 || log.isDebugEnabled()) { if (log.isDebugEnabled()) { - log.debug(sm.getString("parameters.decodeFail.debug", - origName.toString(), origValue.toString()), e); + log.debug( + sm.getString("parameters.decodeFail.debug", origName.toString(), origValue.toString()), + e); } else if (log.isInfoEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { - String message = sm.getString( - "parameters.decodeFail.info", - tmpName.toString(), tmpValue.toString()); + String message = sm.getString("parameters.decodeFail.info", tmpName.toString(), + tmpValue.toString()); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); @@ -455,9 +447,7 @@ public final class Parameters { if (decodeFailCount > 1 && !log.isDebugEnabled()) { UserDataHelper.Mode logMode = userDataLog.getNextMode(); if (logMode != null) { - String message = sm.getString( - "parameters.multipleDecodingFail", - Integer.valueOf(decodeFailCount)); + String message = sm.getString("parameters.multipleDecodingFail", Integer.valueOf(decodeFailCount)); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString("parameters.fallToDebug"); @@ -472,23 +462,22 @@ public final class Parameters { } } - private void urlDecode(ByteChunk bc) - throws IOException { - if( urlDec==null ) { - urlDec=new UDecoder(); + private void urlDecode(ByteChunk bc) throws IOException { + if (urlDec == null) { + urlDec = new UDecoder(); } urlDec.convert(bc, true); } public void processParameters(MessageBytes data, Charset charset) { - if( data==null || data.isNull() || data.getLength() <= 0 ) { + if (data == null || data.isNull() || data.getLength() <= 0) { return; } - if( data.getType() != MessageBytes.T_BYTES ) { + if (data.getType() != MessageBytes.T_BYTES) { data.toBytes(); } - ByteChunk bc=data.getByteChunk(); + ByteChunk bc = data.getByteChunk(); processParameters(bc.getBytes(), bc.getOffset(), bc.getLength(), charset); } diff --git a/java/org/apache/tomcat/util/http/RequestUtil.java b/java/org/apache/tomcat/util/http/RequestUtil.java index fb14030dd4..1c1ed0de13 100644 --- a/java/org/apache/tomcat/util/http/RequestUtil.java +++ b/java/org/apache/tomcat/util/http/RequestUtil.java @@ -30,15 +30,13 @@ public class RequestUtil { /** - * Normalize a relative URI path that may have relative values ("/./", - * "/../", and so on ) it it. <strong>WARNING</strong> - This method is - * useful only for normalizing application-generated paths. It does not + * Normalize a relative URI path that may have relative values ("/./", "/../", and so on ) it it. + * <strong>WARNING</strong> - This method is useful only for normalizing application-generated paths. It does not * try to perform security checks for malicious input. * * @param path Relative path to be normalized * - * @return The normalized path or <code>null</code> if the path cannot be - * normalized + * @return The normalized path or <code>null</code> if the path cannot be normalized */ public static String normalize(String path) { return normalize(path, true); @@ -46,16 +44,14 @@ public class RequestUtil { /** - * Normalize a relative URI path that may have relative values ("/./", - * "/../", and so on ) it it. <strong>WARNING</strong> - This method is - * useful only for normalizing application-generated paths. It does not + * Normalize a relative URI path that may have relative values ("/./", "/../", and so on ) it it. + * <strong>WARNING</strong> - This method is useful only for normalizing application-generated paths. It does not * try to perform security checks for malicious input. * - * @param path Relative path to be normalized + * @param path Relative path to be normalized * @param replaceBackSlash Should '\\' be replaced with '/' * - * @return The normalized path or <code>null</code> if the path cannot be - * normalized + * @return The normalized path or <code>null</code> if the path cannot be normalized */ public static String normalize(String path, boolean replaceBackSlash) { @@ -106,7 +102,7 @@ public class RequestUtil { break; } if (index == 0) { - return null; // Trying to go outside our context + return null; // Trying to go outside our context } int index2 = normalized.lastIndexOf('/', index - 1); normalized = normalized.substring(0, index2) + normalized.substring(index + 3); @@ -178,7 +174,9 @@ public class RequestUtil { * </ul> * * @param origin The origin URI + * * @return <code>true</code> if the origin was valid + * * @see <a href="http://tools.ietf.org/html/rfc952">RFC952</a> */ public static boolean isValidOrigin(String origin) { diff --git a/java/org/apache/tomcat/util/http/Rfc6265CookieProcessor.java b/java/org/apache/tomcat/util/http/Rfc6265CookieProcessor.java index e6e8a0e702..32440dad4e 100644 --- a/java/org/apache/tomcat/util/http/Rfc6265CookieProcessor.java +++ b/java/org/apache/tomcat/util/http/Rfc6265CookieProcessor.java @@ -38,8 +38,8 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { private static final Log log = LogFactory.getLog(Rfc6265CookieProcessor.class); - private static final StringManager sm = - StringManager.getManager(Rfc6265CookieProcessor.class.getPackage().getName()); + private static final StringManager sm = StringManager + .getManager(Rfc6265CookieProcessor.class.getPackage().getName()); private static final BitSet domainValid = new BitSet(128); @@ -65,8 +65,7 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { @Override - public void parseCookieHeader(MimeHeaders headers, - ServerCookies serverCookies) { + public void parseCookieHeader(MimeHeaders headers, ServerCookies serverCookies) { if (headers == null) { // nothing to process @@ -78,8 +77,8 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { while (pos >= 0) { MessageBytes cookieValue = headers.getValue(pos); - if (cookieValue != null && !cookieValue.isNull() ) { - if (cookieValue.getType() != MessageBytes.T_BYTES ) { + if (cookieValue != null && !cookieValue.isNull()) { + if (cookieValue.getType() != MessageBytes.T_BYTES) { if (log.isDebugEnabled()) { Exception e = new Exception(); // TODO: Review this in light of HTTP/2 @@ -92,8 +91,7 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { } ByteChunk bc = cookieValue.getByteChunk(); - Cookie.parseCookie(bc.getBytes(), bc.getOffset(), bc.getLength(), - serverCookies); + Cookie.parseCookie(bc.getBytes(), bc.getOffset(), bc.getLength(), serverCookies); } // search from the next position @@ -108,11 +106,10 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { // Can't use StringBuilder due to DateFormat StringBuffer header = new StringBuffer(); - /* TODO: Name validation takes place in Cookie and cannot be configured - * per Context. Moving it to here would allow per Context config - * but delay validation until the header is generated. However, - * the spec requires an IllegalArgumentException on Cookie - * generation. + /* + * TODO: Name validation takes place in Cookie and cannot be configured per Context. Moving it to here would + * allow per Context config but delay validation until the header is generated. However, the spec requires an + * IllegalArgumentException on Cookie generation. */ header.append(cookie.getName()); header.append('='); @@ -134,14 +131,12 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { // browsers. See http://tomcat.markmail.org/thread/g6sipbofsjossacn // Wdy, DD-Mon-YY HH:MM:SS GMT ( Expires Netscape format ) - header.append ("; Expires="); + header.append("; Expires="); // To expire immediately we need to set the time in past if (maxAge == 0) { header.append(ANCIENT_DATE); } else { - COOKIE_DATE_FORMAT.get().format( - new Date(System.currentTimeMillis() + maxAge * 1000L), - header, + COOKIE_DATE_FORMAT.get().format(new Date(System.currentTimeMillis() + maxAge * 1000L), header, new FieldPosition(0)); } } @@ -183,24 +178,24 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { } // Add the remaining attributes - for (Map.Entry<String,String> entry : cookie.getAttributes().entrySet()) { + for (Map.Entry<String, String> entry : cookie.getAttributes().entrySet()) { switch (entry.getKey()) { - case Constants.COOKIE_COMMENT_ATTR: - case Constants.COOKIE_DOMAIN_ATTR: - case Constants.COOKIE_MAX_AGE_ATTR: - case Constants.COOKIE_PATH_ATTR: - case Constants.COOKIE_SECURE_ATTR: - case Constants.COOKIE_HTTP_ONLY_ATTR: - case Constants.COOKIE_SAME_SITE_ATTR: - // Handled above so NO-OP - break; - default: { - validateAttribute(entry.getKey(), entry.getValue()); - header.append("; "); - header.append(entry.getKey()); - header.append('='); - header.append(entry.getValue()); - } + case Constants.COOKIE_COMMENT_ATTR: + case Constants.COOKIE_DOMAIN_ATTR: + case Constants.COOKIE_MAX_AGE_ATTR: + case Constants.COOKIE_PATH_ATTR: + case Constants.COOKIE_SECURE_ATTR: + case Constants.COOKIE_HTTP_ONLY_ATTR: + case Constants.COOKIE_SAME_SITE_ATTR: + // Handled above so NO-OP + break; + default: { + validateAttribute(entry.getKey(), entry.getValue()); + header.append("; "); + header.append(entry.getKey()); + header.append('='); + header.append(entry.getValue()); + } } } @@ -221,8 +216,8 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { for (int i = start; i < end; i++) { char c = chars[i]; if (c < 0x21 || c == 0x22 || c == 0x2c || c == 0x3b || c == 0x5c || c == 0x7f) { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidCharInValue", Integer.toString(c))); + throw new IllegalArgumentException( + sm.getString("rfc6265CookieProcessor.invalidCharInValue", Integer.toString(c))); } } } @@ -237,25 +232,21 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { prev = cur; cur = chars[i]; if (!domainValid.get(cur)) { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidDomain", domain)); + throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", domain)); } // labels must start with a letter or number if ((prev == '.' || prev == -1) && (cur == '.' || cur == '-')) { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidDomain", domain)); + throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", domain)); } // labels must end with a letter or number if (prev == '-' && cur == '.') { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidDomain", domain)); + throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", domain)); } i++; } // domain must end with a label if (cur == '.' || cur == '-') { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidDomain", domain)); + throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidDomain", domain)); } } @@ -265,8 +256,7 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { for (char ch : chars) { if (ch < 0x20 || ch > 0x7E || ch == ';') { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidPath", path)); + throw new IllegalArgumentException(sm.getString("rfc6265CookieProcessor.invalidPath", path)); } } } @@ -280,8 +270,8 @@ public class Rfc6265CookieProcessor extends CookieProcessorBase { char[] chars = value.toCharArray(); for (char ch : chars) { if (ch < 0x20 || ch > 0x7E || ch == ';') { - throw new IllegalArgumentException(sm.getString( - "rfc6265CookieProcessor.invalidAttributeValue", name, value)); + throw new IllegalArgumentException( + sm.getString("rfc6265CookieProcessor.invalidAttributeValue", name, value)); } } } diff --git a/java/org/apache/tomcat/util/http/ServerCookie.java b/java/org/apache/tomcat/util/http/ServerCookie.java index 43261fe13f..12f3c0c419 100644 --- a/java/org/apache/tomcat/util/http/ServerCookie.java +++ b/java/org/apache/tomcat/util/http/ServerCookie.java @@ -22,21 +22,19 @@ import org.apache.tomcat.util.buf.MessageBytes; /** - * Server-side cookie representation. - * Allows recycling and uses MessageBytes as low-level - * representation ( and thus the byte -> char conversion can be delayed - * until we know the charset ). + * Server-side cookie representation. Allows recycling and uses MessageBytes as low-level representation ( and thus the + * byte -> char conversion can be delayed until we know the charset ). * <p> - * Tomcat.core uses this recyclable object to represent cookies, - * and the facade will convert it to the external representation. + * Tomcat.core uses this recyclable object to represent cookies, and the facade will convert it to the external + * representation. */ public class ServerCookie implements Serializable { private static final long serialVersionUID = 1L; // RFC 6265 - private final MessageBytes name=MessageBytes.newInstance(); - private final MessageBytes value=MessageBytes.newInstance(); + private final MessageBytes name = MessageBytes.newInstance(); + private final MessageBytes value = MessageBytes.newInstance(); public ServerCookie() { // NOOP diff --git a/java/org/apache/tomcat/util/http/ServerCookies.java b/java/org/apache/tomcat/util/http/ServerCookies.java index 93c9e699d5..f40469f49e 100644 --- a/java/org/apache/tomcat/util/http/ServerCookies.java +++ b/java/org/apache/tomcat/util/http/ServerCookies.java @@ -37,19 +37,18 @@ public class ServerCookies { /** - * Register a new, initialized cookie. Cookies are recycled, and most of the - * time an existing ServerCookie object is returned. The caller can set the - * name/value and attributes for the cookie. + * Register a new, initialized cookie. Cookies are recycled, and most of the time an existing ServerCookie object is + * returned. The caller can set the name/value and attributes for the cookie. + * * @return the new cookie */ public ServerCookie addCookie() { if (limit > -1 && cookieCount >= limit) { - throw new IllegalArgumentException( - sm.getString("cookies.maxCountFail", Integer.valueOf(limit))); + throw new IllegalArgumentException(sm.getString("cookies.maxCountFail", Integer.valueOf(limit))); } if (cookieCount >= serverCookies.length) { - int newSize = limit > -1 ? Math.min(2*cookieCount, limit) : 2*cookieCount; + int newSize = limit > -1 ? Math.min(2 * cookieCount, limit) : 2 * cookieCount; ServerCookie scookiesTmp[] = new ServerCookie[newSize]; System.arraycopy(serverCookies, 0, scookiesTmp, 0, cookieCount); serverCookies = scookiesTmp; --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscr...@tomcat.apache.org For additional commands, e-mail: dev-h...@tomcat.apache.org