The Unified and Autonomous Development Platform
midwork
Robin Shen9cfebbce6f6a
diff --git a/server-core/src/main/java/org/eclipse/jetty/server/Response.java b/server-core/src/main/java/org/eclipse/jetty/server/Response.javaindex be239bc653..8ec5387ccf 100644--- a/server-core/src/main/java/org/eclipse/jetty/server/Response.java+++ b/server-core/src/main/java/org/eclipse/jetty/server/Response.java@@ -1,6 +1,6 @@//// ========================================================================-// Copyright (c) 1995-2018 Mort Bay Consulting Pty. Ltd.+// Copyright (c) 1995-2019 Mort Bay Consulting Pty. Ltd.// ------------------------------------------------------------------------// All rights reserved. This program and the accompanying materials// are made available under the terms of the Eclipse Public License v1.0@@ -24,21 +24,25 @@ import java.nio.channels.IllegalSelectorException;import java.util.Collection;import java.util.Collections;import java.util.EnumSet;-import java.util.List;+import java.util.Iterator;+import java.util.ListIterator;import java.util.Locale;-import java.util.concurrent.atomic.AtomicInteger;-import java.util.stream.Collectors;+import java.util.function.Supplier;-import javax.servlet.RequestDispatcher;-import javax.servlet.ServletException;import javax.servlet.ServletOutputStream;+import javax.servlet.ServletResponse;+import javax.servlet.ServletResponseWrapper;import javax.servlet.http.Cookie;import javax.servlet.http.HttpServletResponse;+import javax.servlet.http.HttpServletResponseWrapper;import javax.servlet.http.HttpSession;+import org.eclipse.jetty.http.CookieCompliance;import org.eclipse.jetty.http.DateGenerator;import org.eclipse.jetty.http.HttpContent;import org.eclipse.jetty.http.HttpCookie;+import org.eclipse.jetty.http.HttpCookie.SameSite;+import org.eclipse.jetty.http.HttpCookie.SetCookieHttpField;import org.eclipse.jetty.http.HttpField;import org.eclipse.jetty.http.HttpFields;import org.eclipse.jetty.http.HttpGenerator;@@ -52,36 +56,20 @@ import org.eclipse.jetty.http.MetaData;import org.eclipse.jetty.http.MimeTypes;import org.eclipse.jetty.http.PreEncodedHttpField;import org.eclipse.jetty.io.RuntimeIOException;-import org.eclipse.jetty.server.handler.ErrorHandler;-import org.eclipse.jetty.util.ByteArrayISO8859Writer;-import org.eclipse.jetty.util.QuotedStringTokenizer;+import org.eclipse.jetty.server.session.SessionHandler;+import org.eclipse.jetty.util.AtomicBiInteger;+import org.eclipse.jetty.util.Callback;import org.eclipse.jetty.util.StringUtil;import org.eclipse.jetty.util.URIUtil;-import org.eclipse.jetty.util.log.Log;-import org.eclipse.jetty.util.log.Logger;/*** <p>{@link Response} provides the implementation for {@link HttpServletResponse}.</p>*/public class Response implements HttpServletResponse{- private static final Logger LOG = Log.getLogger(Response.class);- private static final String __COOKIE_DELIM="\",;\\ \t";- private final static String __01Jan1970_COOKIE = DateGenerator.formatCookieDate(0).trim();- private final static int __MIN_BUFFER_SIZE = 1;- private final static HttpField __EXPIRES_01JAN1970 = new PreEncodedHttpField(HttpHeader.EXPIRES,DateGenerator.__01Jan1970);--- // Cookie building buffer. Reduce garbage for cookie using applications- private static final ThreadLocal<StringBuilder> __cookieBuilder = new ThreadLocal<StringBuilder>()- {- @Override- protected StringBuilder initialValue()- {- return new StringBuilder(128);- }- };-+ private static final int __MIN_BUFFER_SIZE = 1;+ private static final HttpField __EXPIRES_01JAN1970 = new PreEncodedHttpField(HttpHeader.EXPIRES, DateGenerator.__01Jan1970);+public enum OutputType{NONE, STREAM, WRITER@@ -92,32 +80,31 @@ public class Response implements HttpServletResponse* can be set during include using only {@link #setHeader(String, String)} or* {@link #addHeader(String, String)}.*/- public final static String SET_INCLUDE_HEADER_PREFIX = "org.eclipse.jetty.server.include.";-- /**- * If this string is found within the comment of a cookie added with {@link #addCookie(Cookie)}, then the cookie- * will be set as HTTP ONLY.- */- public final static String HTTP_ONLY_COMMENT = "__HTTP_ONLY__";+ public static final String SET_INCLUDE_HEADER_PREFIX = "org.eclipse.jetty.server.include.";private final HttpChannel _channel;private final HttpFields _fields = new HttpFields();- private final AtomicInteger _include = new AtomicInteger();+ private final AtomicBiInteger _errorSentAndIncludes = new AtomicBiInteger(); // hi is errorSent flag, lo is include countprivate final HttpOutput _out;private int _status = HttpStatus.OK_200;private String _reason;private Locale _locale;private MimeTypes.Type _mimeType;private String _characterEncoding;- private EncodingFrom _encodingFrom=EncodingFrom.NOT_SET;+ private EncodingFrom _encodingFrom = EncodingFrom.NOT_SET;private String _contentType;private OutputType _outputType = OutputType.NONE;private ResponseWriter _writer;private long _contentLength = -1;-- private enum EncodingFrom { NOT_SET, INFERRED, SET_LOCALE, SET_CONTENT_TYPE, SET_CHARACTER_ENCODING };- private static final EnumSet<EncodingFrom> __localeOverride = EnumSet.of(EncodingFrom.NOT_SET,EncodingFrom.INFERRED);-+ private Supplier<HttpFields> _trailers;++ private enum EncodingFrom+ {+ NOT_SET, INFERRED, SET_LOCALE, SET_CONTENT_TYPE, SET_CHARACTER_ENCODING+ }++ private static final EnumSet<EncodingFrom> __localeOverride = EnumSet.of(EncodingFrom.NOT_SET, EncodingFrom.INFERRED);+ private static final EnumSet<EncodingFrom> __explicitCharset = EnumSet.of(EncodingFrom.SET_LOCALE, EncodingFrom.SET_CHARACTER_ENCODING);public Response(HttpChannel channel, HttpOutput out){@@ -142,27 +129,52 @@ public class Response implements HttpServletResponse_contentLength = -1;_out.recycle();_fields.clear();- _encodingFrom=EncodingFrom.NOT_SET;+ _encodingFrom = EncodingFrom.NOT_SET;}-+public HttpOutput getHttpOutput(){return _out;}+ public void reopen()+ {+ setErrorSent(false);+ _out.reopen();+ }++ public void closedBySendError()+ {+ setErrorSent(true);+ _out.closedBySendError();+ }++ /**+ * @return true if the response is mutable, ie not errorSent and not included+ */+ private boolean isMutable()+ {+ return _errorSentAndIncludes.get() == 0;+ }++ private void setErrorSent(boolean errorSent)+ {+ _errorSentAndIncludes.getAndSetHi(errorSent ? 1 : 0);+ }+public boolean isIncluding(){- return _include.get() > 0;+ return _errorSentAndIncludes.getLo() > 0;}public void include(){- _include.incrementAndGet();+ _errorSentAndIncludes.add(0, 1);}public void included(){- _include.decrementAndGet();+ _errorSentAndIncludes.add(0, -1);if (_outputType == OutputType.WRITER){_writer.reopen();@@ -172,195 +184,91 @@ public class Response implements HttpServletResponsepublic void addCookie(HttpCookie cookie){- addSetCookie(- cookie.getName(),- cookie.getValue(),- cookie.getDomain(),- cookie.getPath(),- cookie.getMaxAge(),- cookie.getComment(),- cookie.isSecure(),- cookie.isHttpOnly(),- cookie.getVersion());;- }+ if (StringUtil.isBlank(cookie.getName()))+ throw new IllegalArgumentException("Cookie.name cannot be blank/null");- @Override- public void addCookie(Cookie cookie)- {- String comment = cookie.getComment();- boolean httpOnly = false;+ // add the set cookie+ _fields.add(new SetCookieHttpField(cookie, getHttpChannel().getHttpConfiguration().getResponseCookieCompliance()));- if (comment != null)- {- int i = comment.indexOf(HTTP_ONLY_COMMENT);- if (i >= 0)- {- httpOnly = true;- comment = comment.replace(HTTP_ONLY_COMMENT, "").trim();- if (comment.length() == 0)- comment = null;- }- }- addSetCookie(cookie.getName(),- cookie.getValue(),- cookie.getDomain(),- cookie.getPath(),- cookie.getMaxAge(),- comment,- cookie.getSecure(),- httpOnly || cookie.isHttpOnly(),- cookie.getVersion());+ // Expire responses with set-cookie headers so they do not get cached.+ _fields.put(__EXPIRES_01JAN1970);}-/**- * Format a set cookie value+ * Replace (or add) a cookie.+ * Using name, path and domain, look for a matching set-cookie header and replace it.*- * @param name the name- * @param value the value- * @param domain the domain- * @param path the path- * @param maxAge the maximum age- * @param comment the comment (only present on versions > 0)- * @param isSecure true if secure cookie- * @param isHttpOnly true if for http only- * @param version version of cookie logic to use (0 == default behavior)+ * @param cookie The cookie to add/replace*/- public void addSetCookie(- final String name,- final String value,- final String domain,- final String path,- final long maxAge,- final String comment,- final boolean isSecure,- final boolean isHttpOnly,- int version)- {- // Check arguments- if (name == null || name.length() == 0)- throw new IllegalArgumentException("Bad cookie name");-- // Format value and params- StringBuilder buf = __cookieBuilder.get();- buf.setLength(0);-- // Name is checked for legality by servlet spec, but can also be passed directly so check again for quoting- boolean quote_name=isQuoteNeededForCookie(name);- quoteOnlyOrAppend(buf,name,quote_name);-- buf.append('=');-- // Append the value- boolean quote_value=isQuoteNeededForCookie(value);- quoteOnlyOrAppend(buf,value,quote_value);-- // Look for domain and path fields and check if they need to be quoted- boolean has_domain = domain!=null && domain.length()>0;- boolean quote_domain = has_domain && isQuoteNeededForCookie(domain);- boolean has_path = path!=null && path.length()>0;- boolean quote_path = has_path && isQuoteNeededForCookie(path);-- // Upgrade the version if we have a comment or we need to quote value/path/domain or if they were already quoted- if (version==0 && ( comment!=null || quote_name || quote_value || quote_domain || quote_path ||- QuotedStringTokenizer.isQuoted(name) || QuotedStringTokenizer.isQuoted(value) ||- QuotedStringTokenizer.isQuoted(path) || QuotedStringTokenizer.isQuoted(domain)))- version=1;-- // Append version- if (version==1)- buf.append (";Version=1");- else if (version>1)- buf.append (";Version=").append(version);-- // Append path- if (has_path)- {- buf.append(";Path=");- quoteOnlyOrAppend(buf,path,quote_path);- }-- // Append domain- if (has_domain)+ public void replaceCookie(HttpCookie cookie)+ {+ for (ListIterator<HttpField> i = _fields.listIterator(); i.hasNext(); ){- buf.append(";Domain=");- quoteOnlyOrAppend(buf,domain,quote_domain);- }+ HttpField field = i.next();- // Handle max-age and/or expires- if (maxAge >= 0)- {- // Always use expires- // This is required as some browser (M$ this means you!) don't handle max-age even with v1 cookies- buf.append(";Expires=");- if (maxAge == 0)- buf.append(__01Jan1970_COOKIE);- else- DateGenerator.formatCookieDate(buf, System.currentTimeMillis() + 1000L * maxAge);-- // for v1 cookies, also send max-age- if (version>=1)+ if (field.getHeader() == HttpHeader.SET_COOKIE){- buf.append(";Max-Age=");- buf.append(maxAge);- }- }+ CookieCompliance compliance = getHttpChannel().getHttpConfiguration().getResponseCookieCompliance();- // add the other fields- if (isSecure)- buf.append(";Secure");- if (isHttpOnly)- buf.append(";HttpOnly");- if (comment != null)- {- buf.append(";Comment=");- quoteOnlyOrAppend(buf,comment,isQuoteNeededForCookie(comment));- }-- // add the set cookie- _fields.add(HttpHeader.SET_COOKIE, buf.toString());+ HttpCookie oldCookie;+ if (field instanceof SetCookieHttpField)+ oldCookie = ((SetCookieHttpField)field).getHttpCookie();+ else+ oldCookie = new HttpCookie(field.getValue());- // Expire responses with set-cookie headers so they do not get cached.- _fields.put(__EXPIRES_01JAN1970);- }+ if (!cookie.getName().equals(oldCookie.getName()))+ continue;+ if (cookie.getDomain() == null)+ {+ if (oldCookie.getDomain() != null)+ continue;+ }+ else if (!cookie.getDomain().equalsIgnoreCase(oldCookie.getDomain()))+ continue;- /* ------------------------------------------------------------ */- /** Does a cookie value need to be quoted?- * @param s value string- * @return true if quoted;- * @throws IllegalArgumentException If there a control characters in the string- */- private static boolean isQuoteNeededForCookie(String s)- {- if (s==null || s.length()==0)- return true;-- if (QuotedStringTokenizer.isQuoted(s))- return false;+ if (cookie.getPath() == null)+ {+ if (oldCookie.getPath() != null)+ continue;+ }+ else if (!cookie.getPath().equals(oldCookie.getPath()))+ continue;- for (int i=0;i<s.length();i++)- {- char c = s.charAt(i);- if (__COOKIE_DELIM.indexOf(c)>=0)- return true;-- if (c<0x20 || c>=0x7f)- throw new IllegalArgumentException("Illegal character in cookie value");+ i.set(new SetCookieHttpField(cookie, compliance));+ return;+ }}- return false;+ // Not replaced, so add normally+ addCookie(cookie);}--- private static void quoteOnlyOrAppend(StringBuilder buf, String s, boolean quote)++ @Override+ public void addCookie(Cookie cookie){- if (quote)- QuotedStringTokenizer.quoteOnly(buf,s);- else- buf.append(s);+ if (StringUtil.isBlank(cookie.getName()))+ throw new IllegalArgumentException("Cookie.name cannot be blank/null");++ String comment = cookie.getComment();+ // HttpOnly was supported as a comment in cookie flags before the java.net.HttpCookie implementation so need to check that+ boolean httpOnly = cookie.isHttpOnly() || HttpCookie.isHttpOnlyInComment(comment);+ SameSite sameSite = HttpCookie.getSameSiteFromComment(comment);+ comment = HttpCookie.getCommentWithoutAttributes(comment);++ addCookie(new HttpCookie(+ cookie.getName(),+ cookie.getValue(),+ cookie.getDomain(),+ cookie.getPath(),+ (long)cookie.getMaxAge(),+ httpOnly,+ cookie.getSecure(),+ comment,+ cookie.getVersion(),+ sameSite));}-+@Overridepublic boolean containsHeader(String name){@@ -371,7 +279,8 @@ public class Response implements HttpServletResponsepublic String encodeURL(String url){final Request request = _channel.getRequest();- SessionManager sessionManager = request.getSessionManager();+ SessionHandler sessionManager = request.getSessionHandler();+if (sessionManager == null)return url;@@ -384,7 +293,7 @@ public class Response implements HttpServletResponseint port = uri.getPort();if (port < 0)port = HttpScheme.HTTPS.asString().equalsIgnoreCase(uri.getScheme()) ? 443 : 80;-+// Is it the same server?if (!request.getServerName().equalsIgnoreCase(uri.getHost()))return url;@@ -402,7 +311,7 @@ public class Response implements HttpServletResponsereturn null;// should not encode if cookies in evidence- if ((sessionManager.isUsingCookies() && request.isRequestedSessionIdFromCookie()) || !sessionManager.isUsingURLs())+ if ((sessionManager.isUsingCookies() && request.isRequestedSessionIdFromCookie()) || !sessionManager.isUsingURLs()){int prefix = url.indexOf(sessionURLPrefix);if (prefix != -1)@@ -429,12 +338,11 @@ public class Response implements HttpServletResponseif (!sessionManager.isValid(session))return url;- String id = sessionManager.getNodeId(session);+ String id = sessionManager.getExtendedId(session);if (uri == null)uri = new HttpURI(url);-// Already encodedint prefix = url.indexOf(sessionURLPrefix);if (prefix != -1)@@ -446,7 +354,7 @@ public class Response implements HttpServletResponseif (suffix <= prefix)return url.substring(0, prefix + sessionURLPrefix.length()) + id;return url.substring(0, prefix + sessionURLPrefix.length()) + id +- url.substring(suffix);+ url.substring(suffix);}// edit the session@@ -456,14 +364,13 @@ public class Response implements HttpServletResponseif (suffix < 0){return url +- ((HttpScheme.HTTPS.is(uri.getScheme()) || HttpScheme.HTTP.is(uri.getScheme())) && uri.getPath() == null ? "/" : "") + //if no path, insert the root path- sessionURLPrefix + id;+ ((HttpScheme.HTTPS.is(uri.getScheme()) || HttpScheme.HTTP.is(uri.getScheme())) && uri.getPath() == null ? "/" : "") + //if no path, insert the root path+ sessionURLPrefix + id;}-return url.substring(0, suffix) +- ((HttpScheme.HTTPS.is(uri.getScheme()) || HttpScheme.HTTP.is(uri.getScheme())) && uri.getPath() == null ? "/" : "") + //if no path so insert the root path- sessionURLPrefix + id + url.substring(suffix);+ ((HttpScheme.HTTPS.is(uri.getScheme()) || HttpScheme.HTTP.is(uri.getScheme())) && uri.getPath() == null ? "/" : "") + //if no path so insert the root path+ sessionURLPrefix + id + url.substring(suffix);}@Override@@ -492,126 +399,44 @@ public class Response implements HttpServletResponsesendError(sc, null);}+ /**+ * Send an error response.+ * <p>In addition to the servlet standard handling, this method supports some additional codes:</p>+ * <dl>+ * <dt>102</dt><dd>Send a partial PROCESSING response and allow additional responses</dd>+ * <dt>-1</dt><dd>Abort the HttpChannel and close the connection/stream</dd>+ * </dl>+ * @param code The error code+ * @param message The message+ * @throws IOException If an IO problem occurred sending the error response.+ */@Overridepublic void sendError(int code, String message) throws IOException{if (isIncluding())return;- if (isCommitted())- {- if (LOG.isDebugEnabled())- LOG.debug("Aborting on sendError on committed response {} {}",code,message);- code=-1;- }-- switch(code)+ switch (code){case -1:- _channel.abort(new IOException());- return;- case 102:+ _channel.abort(new IOException(message));+ break;+ case HttpStatus.PROCESSING_102:sendProcessing();- return;+ break;default:+ _channel.getState().sendError(code, message);+ break;}-- if (isCommitted())- LOG.warn("cannot sendError("+code+", "+message+") response already committed");- else- resetBuffer();-- _characterEncoding=null;- setHeader(HttpHeader.EXPIRES,null);- setHeader(HttpHeader.LAST_MODIFIED,null);- setHeader(HttpHeader.CACHE_CONTROL,null);- setHeader(HttpHeader.CONTENT_TYPE,null);- setHeader(HttpHeader.CONTENT_LENGTH,null);-- _outputType = OutputType.NONE;- setStatus(code);- _reason=message;-- Request request = _channel.getRequest();- Throwable cause = (Throwable)request.getAttribute(Dispatcher.ERROR_EXCEPTION);- if (message==null)- message=cause==null?HttpStatus.getMessage(code):cause.toString();-- // If we are allowed to have a body- if (code!=SC_NO_CONTENT &&- code!=SC_NOT_MODIFIED &&- code!=SC_PARTIAL_CONTENT &&- code>=SC_OK)- {- ErrorHandler error_handler = ErrorHandler.getErrorHandler(_channel.getServer(),request.getContext()==null?null:request.getContext().getContextHandler());- if (error_handler!=null)- {- request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE,new Integer(code));- request.setAttribute(RequestDispatcher.ERROR_MESSAGE, message);- request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, request.getRequestURI());- request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME,request.getServletName());- try {- error_handler.handle(null,_channel.getRequest(),_channel.getRequest(),this );- } catch (ServletException e) {- throw new RuntimeException(e);- }- }- else- {- setHeader(HttpHeader.CACHE_CONTROL, "must-revalidate,no-cache,no-store");- setContentType(MimeTypes.Type.TEXT_HTML_8859_1.toString());- try (ByteArrayISO8859Writer writer= new ByteArrayISO8859Writer(2048);)- {- message=StringUtil.sanitizeXmlString(message);- String uri= request.getRequestURI();- uri=StringUtil.sanitizeXmlString(uri);-- writer.write("<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\"/>\n");- writer.write("<title>Error ");- writer.write(Integer.toString(code));- writer.write(' ');- if (message==null)- writer.write(message);- writer.write("</title>\n</head>\n<body>\n<h2>HTTP ERROR: ");- writer.write(Integer.toString(code));- writer.write("</h2>\n<p>Problem accessing ");- writer.write(uri);- writer.write(". Reason:\n<pre> ");- writer.write(message);- writer.write("</pre>");- writer.write("</p>\n<hr />");-- getHttpChannel().getHttpConfiguration().writePoweredBy(writer,null,"<hr/>");- writer.write("\n</body>\n</html>\n");-- writer.flush();- setContentLength(writer.size());- try (ServletOutputStream outputStream = getOutputStream())- {- writer.writeTo(outputStream);- writer.destroy();- }- }- }- }- else if (code!=SC_PARTIAL_CONTENT)- {- // TODO work out why this is required?- _channel.getRequest().getHttpFields().remove(HttpHeader.CONTENT_TYPE);- _channel.getRequest().getHttpFields().remove(HttpHeader.CONTENT_LENGTH);- _characterEncoding=null;- _mimeType=null;- }-- closeOutput();}/*** Sends a 102-Processing response.- * If the connection is a HTTP connection, the version is 1.1 and the+ * If the connection is an HTTP connection, the version is 1.1 and the* request has a Expect header starting with 102, then a 102 response is* sent. This indicates that the request still be processed and real response* can still be sent. This method is called by sendError if it is passed 102.+ ** @throws IOException if unable to send the 102 response* @see javax.servlet.http.HttpServletResponse#sendError(int)*/@@ -622,19 +447,20 @@ public class Response implements HttpServletResponse_channel.sendResponse(HttpGenerator.PROGRESS_102_INFO, null, true);}}-+/*** Sends a response with one of the 300 series redirection codes.+ ** @param code the redirect status code- * @param location the location to send in <code>Location</code> headers+ * @param location the location to send in {@code Location} headers* @throws IOException if unable to send the redirect*/public void sendRedirect(int code, String location) throws IOException{if ((code < HttpServletResponse.SC_MULTIPLE_CHOICES) || (code >= HttpServletResponse.SC_BAD_REQUEST))throw new IllegalArgumentException("Not a 3xx redirect code");-- if (isIncluding())++ if (!isMutable())return;if (location == null)@@ -648,32 +474,31 @@ public class Response implements HttpServletResponse*//*- if (!URIUtil.hasScheme(location))+ if (!URIUtil.hasScheme(location)){StringBuilder buf = _channel.getRequest().getRootURL();if (location.startsWith("/")){// absolute in context- location=URIUtil.canonicalPath(location);+ location = URIUtil.canonicalEncodedPath(location);}else{// relative to request- String path=_channel.getRequest().getRequestURI();- String parent=(path.endsWith("/"))?path:URIUtil.parentPath(path);- location=URIUtil.canonicalPath(URIUtil.addEncodedPaths(parent,location));- if (!location.startsWith("/"))+ String path = _channel.getRequest().getRequestURI();+ String parent = (path.endsWith("/")) ? path : URIUtil.parentPath(path);+ location = URIUtil.canonicalEncodedPath(URIUtil.addEncodedPaths(parent, location));+ if (location != null && !location.startsWith("/"))buf.append('/');}-- if(location==null)++ if (location == null)throw new IllegalStateException("path cannot be above root");buf.append(location);-- location=buf.toString();++ location = buf.toString();}- */-+ */resetBuffer();setHeader(HttpHeader.LOCATION, location);setStatus(code);@@ -689,34 +514,34 @@ public class Response implements HttpServletResponse@Overridepublic void setDateHeader(String name, long date){- if (!isIncluding())+ if (isMutable())_fields.putDateField(name, date);}@Overridepublic void addDateHeader(String name, long date){- if (!isIncluding())+ if (isMutable())_fields.addDateField(name, date);}public void setHeader(HttpHeader name, String value){- if (HttpHeader.CONTENT_TYPE == name)- setContentType(value);- else+ if (isMutable()){- if (isIncluding())- return;-- _fields.put(name, value);-- if (HttpHeader.CONTENT_LENGTH == name)+ if (HttpHeader.CONTENT_TYPE == name)+ setContentType(value);+ else{- if (value == null)- _contentLength = -1l;- else- _contentLength = Long.parseLong(value);+ _fields.put(name, value);++ if (HttpHeader.CONTENT_LENGTH == name)+ {+ if (value == null)+ _contentLength = -1L;+ else+ _contentLength = Long.parseLong(value);+ }}}}@@ -724,22 +549,26 @@ public class Response implements HttpServletResponse@Overridepublic void setHeader(String name, String value){+ long biInt = _errorSentAndIncludes.get();+ if (biInt != 0)+ {+ boolean errorSent = AtomicBiInteger.getHi(biInt) != 0;+ boolean including = AtomicBiInteger.getLo(biInt) > 0;+ if (!errorSent && including && name.startsWith(SET_INCLUDE_HEADER_PREFIX))+ name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());+ else+ return;+ }+if (HttpHeader.CONTENT_TYPE.is(name))setContentType(value);else{- if (isIncluding())- {- if (name.startsWith(SET_INCLUDE_HEADER_PREFIX))- name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());- else- return;- }_fields.put(name, value);if (HttpHeader.CONTENT_LENGTH.is(name)){if (value == null)- _contentLength = -1l;+ _contentLength = -1L;else_contentLength = Long.parseLong(value);}@@ -749,8 +578,7 @@ public class Response implements HttpServletResponse@Overridepublic Collection<String> getHeaderNames(){- final HttpFields fields = _fields;- return fields.getFieldNamesCollection();+ return _fields.getFieldNamesCollection();}@Override@@ -762,8 +590,7 @@ public class Response implements HttpServletResponse@Overridepublic Collection<String> getHeaders(String name){- final HttpFields fields = _fields;- Collection<String> i = fields.getValuesList(name);+ Collection<String> i = _fields.getValuesList(name);if (i == null)return Collections.emptyList();return i;@@ -772,9 +599,12 @@ public class Response implements HttpServletResponse@Overridepublic void addHeader(String name, String value){- if (isIncluding())+ long biInt = _errorSentAndIncludes.get();+ if (biInt != 0){- if (name.startsWith(SET_INCLUDE_HEADER_PREFIX))+ boolean errorSent = AtomicBiInteger.getHi(biInt) != 0;+ boolean including = AtomicBiInteger.getLo(biInt) > 0;+ if (!errorSent && including && name.startsWith(SET_INCLUDE_HEADER_PREFIX))name = name.substring(SET_INCLUDE_HEADER_PREFIX.length());elsereturn;@@ -785,20 +615,20 @@ public class Response implements HttpServletResponsesetContentType(value);return;}-+if (HttpHeader.CONTENT_LENGTH.is(name)){- setHeader(name,value);+ setHeader(name, value);return;}-+_fields.add(name, value);}@Overridepublic void setIntHeader(String name, int value){- if (!isIncluding())+ if (isMutable()){_fields.putLongField(name, value);if (HttpHeader.CONTENT_LENGTH.is(name))@@ -809,23 +639,26 @@ public class Response implements HttpServletResponse@Overridepublic void addIntHeader(String name, int value){- if (!isIncluding())+ if (isMutable()){_fields.add(name, Integer.toString(value));if (HttpHeader.CONTENT_LENGTH.is(name))_contentLength = value;}}-+@Overridepublic void setStatus(int sc){if (sc <= 0)throw new IllegalArgumentException();- if (!isIncluding())+ if (isMutable()){+ // Null the reason only if the status is different. This allows+ // a specific reason to be sent with setStatusWithReason followed by sendError.+ if (_status != sc)+ _reason = null;_status = sc;- _reason = null;}}@@ -833,14 +666,14 @@ public class Response implements HttpServletResponse@Deprecatedpublic void setStatus(int sc, String sm){- setStatusWithReason(sc,sm);+ setStatusWithReason(sc, sm);}-+public void setStatusWithReason(int sc, String sm){if (sc <= 0)throw new IllegalArgumentException();- if (!isIncluding())+ if (isMutable()){_status = sc;_reason = sm;@@ -853,10 +686,10 @@ public class Response implements HttpServletResponseif (_characterEncoding == null){String encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);- if (encoding!=null)+ if (encoding != null)return encoding;encoding = MimeTypes.getCharsetInferredFromContentType(_contentType);- if (encoding!=null)+ if (encoding != null)return encoding;return StringUtil.__ISO_8859_1;}@@ -883,6 +716,16 @@ public class Response implements HttpServletResponsereturn _outputType == OutputType.WRITER;}+ public boolean isStreaming()+ {+ return _outputType == OutputType.STREAM;+ }++ public boolean isWritingOrStreaming()+ {+ return isWriting() || isStreaming();+ }+@Overridepublic PrintWriter getWriter() throws IOException{@@ -895,8 +738,8 @@ public class Response implements HttpServletResponseString encoding = _characterEncoding;if (encoding == null){- if (_mimeType!=null && _mimeType.isCharsetAssumed())- encoding=_mimeType.getCharsetString();+ if (_mimeType != null && _mimeType.isCharsetAssumed())+ encoding = _mimeType.getCharsetString();else{encoding = MimeTypes.getCharsetAssumedFromContentType(_contentType);@@ -905,25 +748,25 @@ public class Response implements HttpServletResponseencoding = MimeTypes.getCharsetInferredFromContentType(_contentType);if (encoding == null)encoding = StringUtil.__ISO_8859_1;- setCharacterEncoding(encoding,EncodingFrom.INFERRED);+ setCharacterEncoding(encoding, EncodingFrom.INFERRED);}}}-+Locale locale = getLocale();-- if (_writer != null && _writer.isFor(locale,encoding))++ if (_writer != null && _writer.isFor(locale, encoding))_writer.reopen();else{if (StringUtil.__ISO_8859_1.equalsIgnoreCase(encoding))- _writer = new ResponseWriter(new Iso88591HttpWriter(_out),locale,encoding);+ _writer = new ResponseWriter(new Iso88591HttpWriter(_out), locale, encoding);else if (StringUtil.__UTF8.equalsIgnoreCase(encoding))- _writer = new ResponseWriter(new Utf8HttpWriter(_out),locale,encoding);+ _writer = new ResponseWriter(new Utf8HttpWriter(_out), locale, encoding);else- _writer = new ResponseWriter(new EncodingHttpWriter(_out, encoding),locale,encoding);+ _writer = new ResponseWriter(new EncodingHttpWriter(_out, encoding), locale, encoding);}-+// Set the output type at the end, because setCharacterEncoding() checks for it_outputType = OutputType.WRITER;}@@ -936,16 +779,16 @@ public class Response implements HttpServletResponse// Protect from setting after committed as default handling// of a servlet HEAD request ALWAYS sets _content length, even// if the getHandling committed the response!- if (isCommitted() || isIncluding())+ if (isCommitted() || !isMutable())return;- _contentLength = len;- if (_contentLength > 0)+ if (len > 0){long written = _out.getWritten();if (written > len)throw new IllegalArgumentException("setContentLength(" + len + ") when already written " + written);-++ _contentLength = len;_fields.putLongField(HttpHeader.CONTENT_LENGTH, len);if (isAllContentWritten(written)){@@ -953,23 +796,27 @@ public class Response implements HttpServletResponse{closeOutput();}- catch(IOException e)+ catch (IOException e){throw new RuntimeIOException(e);}}}- else if (_contentLength==0)+ else if (len == 0){long written = _out.getWritten();if (written > 0)throw new IllegalArgumentException("setContentLength(0) when already written " + written);+ _contentLength = len;_fields.put(HttpHeader.CONTENT_LENGTH, "0");}else+ {+ _contentLength = len;_fields.remove(HttpHeader.CONTENT_LENGTH);+ }}-+public long getContentLength(){return _contentLength;@@ -980,21 +827,22 @@ public class Response implements HttpServletResponsereturn (_contentLength >= 0 && written >= _contentLength);}+ public boolean isContentComplete(long written)+ {+ return (_contentLength < 0 || written >= _contentLength);+ }+public void closeOutput() throws IOException{- switch (_outputType)- {- case WRITER:- _writer.close();- if (!_out.isClosed())- _out.close();- break;- case STREAM:- getOutputStream().close();- break;- default:- _out.close();- }+ if (_outputType == OutputType.WRITER)+ _writer.close();+ if (!_out.isClosed())+ _out.close();+ }++ public void closeOutput(Callback callback)+ {+ _out.close((_outputType == OutputType.WRITER) ? _writer : _out, callback);}public long getLongContentLength()@@ -1007,12 +855,12 @@ public class Response implements HttpServletResponse// Protect from setting after committed as default handling// of a servlet HEAD request ALWAYS sets _content length, even// if the getHandling committed the response!- if (isCommitted() || isIncluding())+ if (isCommitted() || !isMutable())return;_contentLength = len;_fields.putLongField(HttpHeader.CONTENT_LENGTH.toString(), len);}-+@Overridepublic void setContentLengthLong(long length){@@ -1022,29 +870,29 @@ public class Response implements HttpServletResponse@Overridepublic void setCharacterEncoding(String encoding){- setCharacterEncoding(encoding,EncodingFrom.SET_CHARACTER_ENCODING);+ setCharacterEncoding(encoding, EncodingFrom.SET_CHARACTER_ENCODING);}-+private void setCharacterEncoding(String encoding, EncodingFrom from){- if (isIncluding() || isWriting())+ if (!isMutable() || isWriting())return;if (_outputType != OutputType.WRITER && !isCommitted()){if (encoding == null){- _encodingFrom=EncodingFrom.NOT_SET;-+ _encodingFrom = EncodingFrom.NOT_SET;+// Clear any encoding.if (_characterEncoding != null){_characterEncoding = null;-- if (_mimeType!=null)++ if (_mimeType != null){- _mimeType=_mimeType.getBaseType();- _contentType=_mimeType.asString();+ _mimeType = _mimeType.getBaseType();+ _contentType = _mimeType.asString();_fields.put(_mimeType.getContentTypeField());}else if (_contentType != null)@@ -1058,12 +906,12 @@ public class Response implements HttpServletResponse{// No, so just add this one to the mimetype_encodingFrom = from;- _characterEncoding = HttpGenerator.__STRICT?encoding:StringUtil.normalizeCharset(encoding);- if (_mimeType!=null)+ _characterEncoding = HttpGenerator.__STRICT ? encoding : StringUtil.normalizeCharset(encoding);+ if (_mimeType != null){- _contentType=_mimeType.getBaseType().asString()+ ";charset=" + _characterEncoding;+ _contentType = _mimeType.getBaseType().asString() + ";charset=" + _characterEncoding;_mimeType = MimeTypes.CACHE.get(_contentType);- if (_mimeType==null || HttpGenerator.__STRICT)+ if (_mimeType == null || HttpGenerator.__STRICT)_fields.put(HttpHeader.CONTENT_TYPE, _contentType);else_fields.put(_mimeType.getContentTypeField());@@ -1076,11 +924,11 @@ public class Response implements HttpServletResponse}}}-+@Overridepublic void setContentType(String contentType){- if (isCommitted() || isIncluding())+ if (isCommitted() || !isMutable())return;if (contentType == null)@@ -1098,10 +946,10 @@ public class Response implements HttpServletResponse{_contentType = contentType;_mimeType = MimeTypes.CACHE.get(contentType);-+String charset;- if (_mimeType!=null && _mimeType.getCharset()!=null && !_mimeType.isCharsetAssumed())- charset=_mimeType.getCharsetString();+ if (_mimeType != null && _mimeType.getCharset() != null && !_mimeType.isCharsetAssumed())+ charset = _mimeType.getCharsetString();elsecharset = MimeTypes.getCharsetFromContentType(contentType);@@ -1115,13 +963,13 @@ public class Response implements HttpServletResponsecase SET_CONTENT_TYPE:if (isWriting()){- _mimeType=null;+ _mimeType = null;_contentType = _contentType + ";charset=" + _characterEncoding;}else{- _encodingFrom=EncodingFrom.NOT_SET;- _characterEncoding=null;+ _encodingFrom = EncodingFrom.NOT_SET;+ _characterEncoding = null;}break;case SET_LOCALE:@@ -1146,11 +994,11 @@ public class Response implements HttpServletResponse_encodingFrom = EncodingFrom.SET_CONTENT_TYPE;}- if (HttpGenerator.__STRICT || _mimeType==null)+ if (HttpGenerator.__STRICT || _mimeType == null)_fields.put(HttpHeader.CONTENT_TYPE, _contentType);else{- _contentType=_mimeType.asString();+ _contentType = _mimeType.asString();_fields.put(_mimeType.getContentTypeField());}}@@ -1184,66 +1032,93 @@ public class Response implements HttpServletResponse@Overridepublic void reset(){- reset(false);- }-- public void reset(boolean preserveCookies)- {- resetForForward();_status = 200;_reason = null;+ _out.resetBuffer();+ _outputType = OutputType.NONE;_contentLength = -1;-- List<HttpField> cookies = preserveCookies- ?_fields.stream()- .filter(f->f.getHeader()==HttpHeader.SET_COOKIE)- .collect(Collectors.toList()):null;-+ _contentType = null;+ _mimeType = null;+ _characterEncoding = null;+ _encodingFrom = EncodingFrom.NOT_SET;++ // Clear all response headers_fields.clear();- String connection = _channel.getRequest().getHeader(HttpHeader.CONNECTION.asString());- if (connection != null)+ // recreate necessary connection related fields+ for (String value : _channel.getRequest().getHttpFields().getCSV(HttpHeader.CONNECTION, false)){- for (String value: StringUtil.csvSplit(null,connection,0,connection.length()))+ HttpHeaderValue cb = HttpHeaderValue.CACHE.get(value);+ if (cb != null){- HttpHeaderValue cb = HttpHeaderValue.CACHE.get(value);-- if (cb != null)+ switch (cb){- switch (cb)- {- case CLOSE:- _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.toString());- break;-- case KEEP_ALIVE:- if (HttpVersion.HTTP_1_0.is(_channel.getRequest().getProtocol()))- _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.toString());- break;- case TE:- _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.TE.toString());- break;- default:- }+ case CLOSE:+ _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.toString());+ break;+ case KEEP_ALIVE:+ if (HttpVersion.HTTP_1_0.is(_channel.getRequest().getProtocol()))+ _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.toString());+ break;+ case TE:+ _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.TE.toString());+ break;+ default:}}}- if (preserveCookies)- cookies.forEach(f->_fields.add(f));- else+ // recreate session cookies+ Request request = getHttpChannel().getRequest();+ HttpSession session = request.getSession(false);+ if (session != null && session.isNew()){- Request request = getHttpChannel().getRequest();- HttpSession session = request.getSession(false);- if (session!=null && session.isNew())+ SessionHandler sh = request.getSessionHandler();+ if (sh != null){- SessionManager sm = request.getSessionManager();- if (sm!=null)- {- HttpCookie c=sm.getSessionCookie(session,request.getContextPath(),request.isSecure());- if (c!=null)- addCookie(c);- }+ HttpCookie c = sh.getSessionCookie(session, request.getContextPath(), request.isSecure());+ if (c != null)+ addCookie(c);+ }+ }+ }++ public void resetContent()+ {+ _out.resetBuffer();+ _outputType = OutputType.NONE;+ _contentLength = -1;+ _contentType = null;+ _mimeType = null;+ _characterEncoding = null;+ _encodingFrom = EncodingFrom.NOT_SET;++ // remove the content related response headers and keep all others+ for (Iterator<HttpField> i = getHttpFields().iterator(); i.hasNext(); )+ {+ HttpField field = i.next();+ if (field.getHeader() == null)+ continue;++ switch (field.getHeader())+ {+ case CONTENT_TYPE:+ case CONTENT_LENGTH:+ case CONTENT_ENCODING:+ case CONTENT_LANGUAGE:+ case CONTENT_RANGE:+ case CONTENT_MD5:+ case CONTENT_LOCATION:+ case TRANSFER_ENCODING:+ case CACHE_CONTROL:+ case LAST_MODIFIED:+ case EXPIRES:+ case ETAG:+ case DATE:+ case VARY:+ i.remove();+ continue;+ default:}}}@@ -1258,25 +1133,40 @@ public class Response implements HttpServletResponsepublic void resetBuffer(){_out.resetBuffer();+ _out.reopen();+ }++ public void setTrailers(Supplier<HttpFields> trailers)+ {+ this._trailers = trailers;+ }++ public Supplier<HttpFields> getTrailers()+ {+ return _trailers;}protected MetaData.Response newResponseMetaData(){- return new MetaData.Response(_channel.getRequest().getHttpVersion(), getStatus(), getReason(), _fields, getLongContentLength());+ MetaData.Response info = new MetaData.Response(_channel.getRequest().getHttpVersion(), getStatus(), getReason(), _fields, getLongContentLength());+ info.setTrailerSupplier(getTrailers());+ return info;}-- /** Get the MetaData.Response committed for this response.- * This may differ from the meta data in this response for++ /**+ * Get the MetaData.Response committed for this response.+ * This may differ from the meta data in this response for* exceptional responses (eg 4xx and 5xx responses generated- * by the container) and the committedMetaData should be used+ * by the container) and the committedMetaData should be used* for logging purposes.+ ** @return The committed MetaData or a {@link #newResponseMetaData()}* if not yet committed.*/public MetaData.Response getCommittedMetaData(){MetaData.Response meta = _channel.getCommittedMetaData();- if (meta==null)+ if (meta == null)return newResponseMetaData();return meta;}@@ -1284,17 +1174,20 @@ public class Response implements HttpServletResponse@Overridepublic boolean isCommitted(){+ // If we are in sendError state, we pretend to be committed+ if (_channel.isSendError())+ return true;return _channel.isCommitted();}@Overridepublic void setLocale(Locale locale){- if (locale == null || isCommitted() || isIncluding())+ if (locale == null || isCommitted() || !isMutable())return;_locale = locale;- _fields.put(HttpHeader.CONTENT_LANGUAGE, locale.toString().replace('_', '-'));+ _fields.put(HttpHeader.CONTENT_LANGUAGE, StringUtil.replace(locale.toString(), '_', '-'));if (_outputType != OutputType.NONE)return;@@ -1305,7 +1198,7 @@ public class Response implements HttpServletResponseString charset = _channel.getRequest().getContext().getContextHandler().getLocaleEncoding(locale);if (charset != null && charset.length() > 0 && __localeOverride.contains(_encodingFrom))- setCharacterEncoding(charset,EncodingFrom.SET_LOCALE);+ setCharacterEncoding(charset, EncodingFrom.SET_LOCALE);}@Override@@ -1342,75 +1235,97 @@ public class Response implements HttpServletResponse{return String.format("%s %d %s%n%s", _channel.getRequest().getHttpVersion(), _status, _reason == null ? "" : _reason, _fields);}-- public void putHeaders(HttpContent content,long contentLength, boolean etag)+ public void putHeaders(HttpContent content, long contentLength, boolean etag){HttpField lm = content.getLastModified();- if (lm!=null)+ if (lm != null)_fields.put(lm);- if (contentLength==0)+ if (contentLength == 0){_fields.put(content.getContentLength());- _contentLength=content.getContentLengthValue();+ _contentLength = content.getContentLengthValue();}- else if (contentLength>0)+ else if (contentLength > 0){- _fields.putLongField(HttpHeader.CONTENT_LENGTH,contentLength);- _contentLength=contentLength;+ _fields.putLongField(HttpHeader.CONTENT_LENGTH, contentLength);+ _contentLength = contentLength;}- HttpField ct=content.getContentType();- if (ct!=null)+ HttpField ct = content.getContentType();+ if (ct != null){- _fields.put(ct);- _contentType=ct.getValue();- _characterEncoding=content.getCharacterEncoding();- _mimeType=content.getMimeType();+ if (_characterEncoding != null &&+ content.getCharacterEncoding() == null &&+ content.getContentTypeValue() != null &&+ __explicitCharset.contains(_encodingFrom))+ {+ setContentType(MimeTypes.getContentTypeWithoutCharset(content.getContentTypeValue()));+ }+ else+ {+ _fields.put(ct);+ _contentType = ct.getValue();+ _characterEncoding = content.getCharacterEncoding();+ _mimeType = content.getMimeType();+ }}-- HttpField ce=content.getContentEncoding();- if (ce!=null)++ HttpField ce = content.getContentEncoding();+ if (ce != null)_fields.put(ce);-+if (etag){HttpField et = content.getETag();- if (et!=null)+ if (et != null)_fields.put(et);}}-+public static void putHeaders(HttpServletResponse response, HttpContent content, long contentLength, boolean etag)- {- long lml=content.getResource().lastModified();- if (lml>=0)- response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(),lml);-- if (contentLength==0)- contentLength=content.getContentLengthValue();- if (contentLength >=0)+ {+ long lml = content.getResource().lastModified();+ if (lml >= 0)+ response.setDateHeader(HttpHeader.LAST_MODIFIED.asString(), lml);++ if (contentLength == 0)+ contentLength = content.getContentLengthValue();+ if (contentLength >= 0){- if (contentLength<Integer.MAX_VALUE)+ if (contentLength < Integer.MAX_VALUE)response.setContentLength((int)contentLength);else- response.setHeader(HttpHeader.CONTENT_LENGTH.asString(),Long.toString(contentLength));+ response.setHeader(HttpHeader.CONTENT_LENGTH.asString(), Long.toString(contentLength));}- String ct=content.getContentTypeValue();- if (ct!=null && response.getContentType()==null)+ String ct = content.getContentTypeValue();+ if (ct != null && response.getContentType() == null)response.setContentType(ct);- String ce=content.getContentEncodingValue();- if (ce!=null)- response.setHeader(HttpHeader.CONTENT_ENCODING.asString(),ce);-+ String ce = content.getContentEncodingValue();+ if (ce != null)+ response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), ce);+if (etag){- String et=content.getETagValue();- if (et!=null)- response.setHeader(HttpHeader.ETAG.asString(),et);+ String et = content.getETagValue();+ if (et != null)+ response.setHeader(HttpHeader.ETAG.asString(), et);+ }+ }++ public static HttpServletResponse unwrap(ServletResponse servletResponse)+ {+ if (servletResponse instanceof HttpServletResponseWrapper)+ {+ return (HttpServletResponseWrapper)servletResponse;+ }+ if (servletResponse instanceof ServletResponseWrapper)+ {+ return unwrap(((ServletResponseWrapper)servletResponse).getResponse());}+ return (HttpServletResponse)servletResponse;}}