issue_id
int64
2.03k
426k
title
stringlengths
9
251
body
stringlengths
1
32.8k
status
stringclasses
6 values
after_fix_sha
stringlengths
7
7
project_name
stringclasses
6 values
repo_url
stringclasses
6 values
repo_name
stringclasses
6 values
language
stringclasses
1 value
issue_url
null
before_fix_sha
null
pull_url
null
commit_datetime
timestamp[us, tz=UTC]
report_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
2
187
file_content
stringlengths
0
368k
54,888
Bug 54888 TagPlugin "ForEach" doesn't support CSV items
null
resolved fixed
d440ae2
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-29T13:24:36Z
2013-04-24T21:46:40Z
test/org/apache/jasper/tagplugins/jstl/core/TestForEach.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.tagplugins.jstl.core; import javax.servlet.http.HttpServletResponse; import org.junit.Assert; import org.junit.Test; import org.apache.tomcat.util.buf.ByteChunk; public class TestForEach extends AbstractTestTag { @Test public void testBug54242() throws Exception { ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug54242.jsp", res, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); String body = res.toString(); Assert.assertTrue(body.contains("OK - 1")); Assert.assertTrue(body.contains("OK - 2")); Assert.assertFalse(body.contains("FAIL")); } }
54,926
Bug 54926 WsFilter performs handshake validation even if it doesn't have a mapped endpoint
WsFilter performs several validations on WebSocket requests before checking if there is a registered Endpoint. I think the check for registered Endponts (and delegation to the next Filter) should take place first and the filter should do no further processing if there is mapped Endpoint for that URL. For example a SockJS protocol test send a POST request with a connection and upgrade headers but no ws version header and expects back a 405 (invalid HTTP method) where WsFilter sends 426 even though it has no Endpoint mapped at that URL.
resolved fixed
2df191f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-04T09:09:39Z
2013-05-04T06:46:40Z
java/org/apache/tomcat/websocket/server/WsFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.server; import java.io.IOException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.HandshakeResponse; import javax.websocket.server.ServerEndpointConfig; import org.apache.tomcat.util.codec.binary.Base64; import org.apache.tomcat.websocket.Constants; import org.apache.tomcat.websocket.WsHandshakeResponse; import org.apache.tomcat.websocket.pojo.PojoEndpointServer; /** * Handles the initial HTTP connection for WebSocket connections. */ public class WsFilter implements Filter { private static final Charset ISO_8859_1; static { ISO_8859_1 = Charset.forName("ISO-8859-1"); } private static final byte[] WS_ACCEPT = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes(ISO_8859_1); private final Queue<MessageDigest> sha1Helpers = new ConcurrentLinkedQueue<>(); @Override public void init(FilterConfig filterConfig) throws ServletException { // NO-OP } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // This filter only needs to handle WebSocket upgrade requests if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse) || !headerContainsToken((HttpServletRequest) request, Constants.UPGRADE_HEADER_NAME, Constants.UPGRADE_HEADER_VALUE)) { // Not an HTTP request that includes a valid upgrade request to // web socket chain.doFilter(request, response); return; } // HTTP request with an upgrade header for WebSocket present // Validate the rest of the headers and reject the request if that // validation fails HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String key; String subProtocol = null; List<Extension> extensions = Collections.emptyList(); if (!headerContainsToken(req, Constants.CONNECTION_HEADER_NAME, Constants.CONNECTION_HEADER_VALUE)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } if (!headerContainsToken(req, Constants.WS_VERSION_HEADER_NAME, Constants.WS_VERSION_HEADER_VALUE)) { resp.setStatus(426); resp.setHeader(Constants.WS_VERSION_HEADER_NAME, Constants.WS_VERSION_HEADER_VALUE); return; } key = req.getHeader(Constants.WS_KEY_HEADER_NAME); if (key == null) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // Need an Endpoint instance to progress this further WsServerContainer sc = WsServerContainer.getServerContainer(); String path; String pathInfo = req.getPathInfo(); if (pathInfo == null) { path = req.getServletPath(); } else { path = req.getServletPath() + pathInfo; } WsMappingResult mappingResult = sc.findMapping(path); if (mappingResult == null) { // No endpoint registered for the requested path. Let the // application handle it (it might redirect or forward for example) chain.doFilter(request, response); return; } ServerEndpointConfig sec = mappingResult.getConfig(); // Origin check String origin = req.getHeader("Origin"); if (!sec.getConfigurator().checkOrigin(origin)) { resp.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // Sub-protocols List<String> subProtocols = getTokensFromHeader(req, "Sec-WebSocket-Protocol"); if (!subProtocols.isEmpty()) { subProtocol = sec.getConfigurator(). getNegotiatedSubprotocol( sec.getSubprotocols(), subProtocols); } // Extensions // Currently no extensions are supported by this implementation // If we got this far, all is good. Accept the connection. resp.setHeader(Constants.UPGRADE_HEADER_NAME, Constants.UPGRADE_HEADER_VALUE); resp.setHeader(Constants.CONNECTION_HEADER_NAME, Constants.CONNECTION_HEADER_VALUE); resp.setHeader(HandshakeResponse.SEC_WEBSOCKET_ACCEPT, getWebSocketAccept(key)); if (subProtocol != null) { resp.setHeader("Sec-WebSocket-Protocol", subProtocol); } if (!extensions.isEmpty()) { StringBuilder sb = new StringBuilder(); Iterator<Extension> iter = extensions.iterator(); // There must be at least one sb.append(iter.next()); while (iter.hasNext()) { sb.append(','); sb.append(iter.next().getName()); } resp.setHeader("Sec-WebSocket-Extensions", sb.toString()); } Endpoint ep; try { Class<?> clazz = sec.getEndpointClass(); if (Endpoint.class.isAssignableFrom(clazz)) { ep = (Endpoint) sec.getConfigurator().getEndpointInstance( clazz); } else { ep = new PojoEndpointServer(); } } catch (InstantiationException e) { throw new ServletException(e); } WsHandshakeRequest wsRequest = new WsHandshakeRequest(req); WsHandshakeResponse wsResponse = new WsHandshakeResponse(); sec.getConfigurator().modifyHandshake(sec, wsRequest, wsResponse); wsRequest.finished(); // Add any additional headers for (Entry<String,List<String>> entry : wsResponse.getHeaders().entrySet()) { for (String headerValue: entry.getValue()) { resp.addHeader(entry.getKey(), headerValue); } } WsHttpUpgradeHandler wsHandler = req.upgrade(WsHttpUpgradeHandler.class); wsHandler.preInit(ep, sec, sc, wsRequest, subProtocol, mappingResult.getPathParams(), req.isSecure()); } @Override public void destroy() { // NO-OP } /* * This only works for tokens. Quoted strings need more sophisticated * parsing. */ private boolean headerContainsToken(HttpServletRequest req, String headerName, String target) { Enumeration<String> headers = req.getHeaders(headerName); while (headers.hasMoreElements()) { String header = headers.nextElement(); String[] tokens = header.split(","); for (String token : tokens) { if (target.equalsIgnoreCase(token.trim())) { return true; } } } return false; } /* * This only works for tokens. Quoted strings need more sophisticated * parsing. */ private List<String> getTokensFromHeader(HttpServletRequest req, String headerName) { List<String> result = new ArrayList<>(); Enumeration<String> headers = req.getHeaders(headerName); while (headers.hasMoreElements()) { String header = headers.nextElement(); String[] tokens = header.split(","); for (String token : tokens) { result.add(token.trim()); } } return result; } private String getWebSocketAccept(String key) throws ServletException { MessageDigest sha1Helper = sha1Helpers.poll(); if (sha1Helper == null) { try { sha1Helper = MessageDigest.getInstance("SHA1"); } catch (NoSuchAlgorithmException e) { throw new ServletException(e); } } sha1Helper.reset(); sha1Helper.update(key.getBytes(ISO_8859_1)); String result = Base64.encodeBase64String(sha1Helper.digest(WS_ACCEPT)); sha1Helpers.add(sha1Helper); return result; } }
54,906
Bug 54906 WebappClassLoader.loadedByThisOrChild can throw ConcurrentModificationException
null
resolved fixed
c06707c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-04T20:59:07Z
2013-04-30T00:00:00Z
java/org/apache/catalina/loader/WebappClassLoader.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.loader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.security.AccessControlException; import java.security.AccessController; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Policy; import java.security.PrivilegedAction; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ThreadPoolExecutor; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.jar.Manifest; import org.apache.catalina.Globals; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.res.StringManager; /** * Specialized web application class loader. * <p> * This class loader is a full reimplementation of the * <code>URLClassLoader</code> from the JDK. It is designed to be fully * compatible with a normal <code>URLClassLoader</code>, although its internal * behavior may be completely different. * <p> * <strong>IMPLEMENTATION NOTE</strong> - By default, this class loader follows * the delegation model required by the specification. The system class * loader will be queried first, then the local repositories, and only then * delegation to the parent class loader will occur. This allows the web * application to override any shared class except the classes from J2SE. * Special handling is provided from the JAXP XML parser interfaces, the JNDI * interfaces, and the classes from the servlet API, which are never loaded * from the webapp repositories. The <code>delegate</code> property * allows an application to modify this behavior to move the parent class loader * ahead of the local repositories. * <p> * <strong>IMPLEMENTATION NOTE</strong> - Due to limitations in Jasper * compilation technology, any repository which contains classes from * the servlet API will be ignored by the class loader. * <p> * <strong>IMPLEMENTATION NOTE</strong> - The class loader generates source * URLs which include the full JAR URL when a class is loaded from a JAR file, * which allows setting security permission at the class level, even when a * class is contained inside a JAR. * <p> * <strong>IMPLEMENTATION NOTE</strong> - Local repositories are searched in * the order they are added via the initial constructor and/or any subsequent * calls to <code>addRepository()</code> or <code>addJar()</code>. * <p> * <strong>IMPLEMENTATION NOTE</strong> - No check for sealing violations or * security is made unless a security manager is present. * <p> * TODO: Is there any requirement to provide a proper Lifecycle implementation * rather than the current stubbed implementation? * * @author Remy Maucherat * @author Craig R. McClanahan * @version $Id$ */ public class WebappClassLoader extends URLClassLoader implements Lifecycle { private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog( WebappClassLoader.class ); private static final Charset CHARSET_UTF8 = Charset.forName("UTF-8"); /** * List of ThreadGroup names to ignore when scanning for web application * started threads that need to be shut down. */ private static final List<String> JVM_THREAD_GROUP_NAMES = new ArrayList<>(); private static final String JVN_THREAD_GROUP_SYSTEM = "system"; static { JVM_THREAD_GROUP_NAMES.add(JVN_THREAD_GROUP_SYSTEM); JVM_THREAD_GROUP_NAMES.add("RMI Runtime"); } protected class PrivilegedFindResourceByName implements PrivilegedAction<ResourceEntry> { protected final String name; protected final String path; PrivilegedFindResourceByName(String name, String path) { this.name = name; this.path = path; } @Override public ResourceEntry run() { return findResourceInternal(name, path); } } protected static final class PrivilegedGetClassLoader implements PrivilegedAction<ClassLoader> { public final Class<?> clazz; public PrivilegedGetClassLoader(Class<?> clazz){ this.clazz = clazz; } @Override public ClassLoader run() { return clazz.getClassLoader(); } } // ------------------------------------------------------- Static Variables /** * The set of trigger classes that will cause a proposed repository not * to be added if this class is visible to the class loader that loaded * this factory class. Typically, trigger classes will be listed for * components that have been integrated into the JDK for later versions, * but where the corresponding JAR files are required to run on * earlier versions. */ protected static final String[] triggers = { "javax.servlet.Servlet", "javax.el.Expression" // Servlet API }; /** * Set of package names which are not allowed to be loaded from a webapp * class loader without delegating first. */ protected static final String[] packageTriggers = { }; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Use anti JAR locking code, which does URL rerouting when accessing * resources. */ boolean antiJARLocking = false; // ----------------------------------------------------------- Constructors /** * Construct a new ClassLoader with no defined repositories and no * parent ClassLoader. */ public WebappClassLoader() { super(new URL[0]); this.parent = getParent(); system = getSystemClassLoader(); securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } } /** * Construct a new ClassLoader with no defined repositories and the given * parent ClassLoader. * <p> * Method is used via reflection - * see {@link WebappLoader#createClassLoader()} * * @param parent Our parent class loader */ public WebappClassLoader(ClassLoader parent) { super(new URL[0], parent); this.parent = getParent(); system = getSystemClassLoader(); securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } } // ----------------------------------------------------- Instance Variables /** * Associated directory context giving access to the resources in this * webapp. */ protected WebResourceRoot resources = null; /** * The cache of ResourceEntry for classes and resources we have loaded, * keyed by resource name. */ protected final HashMap<String, ResourceEntry> resourceEntries = new HashMap<>(); /** * The list of not found resources. */ protected final HashMap<String, String> notFoundResources = new LinkedHashMap<String, String>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry( Map.Entry<String, String> eldest) { return size() > 1000; } }; /** * Should this class loader delegate to the parent class loader * <strong>before</strong> searching its own repositories (i.e. the * usual Java2 delegation model)? If set to <code>false</code>, * this class loader will search its own repositories first, and * delegate to the parent only if the class or resource is not * found locally. Note that the default, <code>false</code>, is * the behavior called for by the servlet specification. */ protected boolean delegate = false; /** * Last time a JAR was accessed. */ protected long lastJarAccessed = 0L; /** * The local repository for locally loaded classes or resources. */ protected String repository = null; /** * Repositories URLs, used to cache the result of getURLs. */ protected URL[] repositoryURLs = null; /** * Repository translated as path in the work directory (for Jasper * originally), but which is used to generate a fake URL should getURLs be * called. */ protected File file = null; /** * The list of JARs, in the order they should be searched * for locally loaded classes or resources. */ protected JarFile[] jarFiles = new JarFile[0]; /** * The list of JARs, in the order they should be searched * for locally loaded classes or resources. */ protected File[] jarRealFiles = new File[0]; /** * The path which will be monitored for added Jar files. */ protected String jarPath = null; /** * The list of JARs, in the order they should be searched * for locally loaded classes or resources. */ protected String[] jarNames = new String[0]; /** * The list of JARs last modified dates, in the order they should be * searched for locally loaded classes or resources. */ protected long[] lastModifiedDates = new long[0]; /** * The list of resources which should be checked when checking for * modifications. */ protected String[] paths = new String[0]; /** * A list of read File and Jndi Permission's required if this loader * is for a web application context. */ protected final ArrayList<Permission> permissionList = new ArrayList<>(); /** * Path where resources loaded from JARs will be extracted. */ protected File loaderDir = null; protected String canonicalLoaderDir = null; /** * The PermissionCollection for each CodeSource for a web * application context. */ protected final HashMap<String, PermissionCollection> loaderPC = new HashMap<>(); /** * Instance of the SecurityManager installed. */ protected final SecurityManager securityManager; /** * The parent class loader. */ protected ClassLoader parent = null; /** * The system class loader. */ protected final ClassLoader system; /** * Has this component been started? */ protected boolean started = false; /** * need conversion for properties files */ protected boolean needConvert = false; /** * All permission. */ protected final Permission allPermission = new java.security.AllPermission(); /** * Should Tomcat attempt to null out any static or final fields from loaded * classes when a web application is stopped as a work around for apparent * garbage collection bugs and application coding errors? There have been * some issues reported with log4j when this option is true. Applications * without memory leaks using recent JVMs should operate correctly with this * option set to <code>false</code>. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStatic = false; /** * Should Tomcat attempt to terminate threads that have been started by the * web application? Stopping threads is performed via the deprecated (for * good reason) <code>Thread.stop()</code> method and is likely to result in * instability. As such, enabling this should be viewed as an option of last * resort in a development environment and is not recommended in a * production environment. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStopThreads = false; /** * Should Tomcat attempt to terminate any {@link java.util.TimerThread}s * that have been started by the web application? If not specified, the * default value of <code>false</code> will be used. */ private boolean clearReferencesStopTimerThreads = false; /** * Should Tomcat call {@link org.apache.juli.logging.LogFactory#release()} * when the class loader is stopped? If not specified, the default value * of <code>true</code> is used. Changing the default setting is likely to * lead to memory leaks and other issues. */ private boolean clearReferencesLogFactoryRelease = true; /** * If an HttpClient keep-alive timer thread has been started by this web * application and is still running, should Tomcat change the context class * loader from the current {@link WebappClassLoader} to * {@link WebappClassLoader#parent} to prevent a memory leak? Note that the * keep-alive timer thread will stop on its own once the keep-alives all * expire however, on a busy system that might not happen for some time. */ private boolean clearReferencesHttpClientKeepAliveThread = true; // ------------------------------------------------------------- Properties /** * Get associated resources. */ public WebResourceRoot getResources() { return this.resources; } /** * Set associated resources. */ public void setResources(WebResourceRoot resources) { this.resources = resources; } /** * Return the context name for this class loader. */ public String getContextName() { if (resources == null) { return "Unknown"; } else { return resources.getContext().getName(); } } /** * Return the "delegate first" flag for this class loader. */ public boolean getDelegate() { return (this.delegate); } /** * Set the "delegate first" flag for this class loader. * If this flag is true, this class loader delegates * to the parent class loader * <strong>before</strong> searching its own repositories, as * in an ordinary (non-servlet) chain of Java class loaders. * If set to <code>false</code> (the default), * this class loader will search its own repositories first, and * delegate to the parent only if the class or resource is not * found locally, as per the servlet specification. * * @param delegate The new "delegate first" flag */ public void setDelegate(boolean delegate) { this.delegate = delegate; } /** * @return Returns the antiJARLocking. */ public boolean getAntiJARLocking() { return antiJARLocking; } /** * @param antiJARLocking The antiJARLocking to set. */ public void setAntiJARLocking(boolean antiJARLocking) { this.antiJARLocking = antiJARLocking; } /** * If there is a Java SecurityManager create a read FilePermission * or JndiPermission for the file directory path. * * @param filepath file directory path */ public void addPermission(String filepath) { if (filepath == null) { return; } String path = filepath; if (securityManager != null) { Permission permission = null; if (!path.endsWith(File.separator)) { permission = new FilePermission(path, "read"); addPermission(permission); path = path + File.separator; } permission = new FilePermission(path + "-", "read"); addPermission(permission); } } /** * If there is a Java SecurityManager create a read FilePermission * or JndiPermission for URL. * * @param url URL for a file or directory on local system */ public void addPermission(URL url) { if (url != null) { addPermission(url.toString()); } } /** * If there is a Java SecurityManager create a Permission. * * @param permission The permission */ public void addPermission(Permission permission) { if ((securityManager != null) && (permission != null)) { permissionList.add(permission); } } /** * Return the JAR path. */ public String getJarPath() { return this.jarPath; } /** * Change the Jar path. */ public void setJarPath(String jarPath) { this.jarPath = jarPath; } /** * Change the work directory. */ public void setWorkDir(File workDir) { this.loaderDir = new File(workDir, "loader"); if (loaderDir == null) { canonicalLoaderDir = null; } else { try { canonicalLoaderDir = loaderDir.getCanonicalPath(); if (!canonicalLoaderDir.endsWith(File.separator)) { canonicalLoaderDir += File.separator; } } catch (IOException ioe) { canonicalLoaderDir = null; } } } /** * Utility method for use in subclasses. * Must be called before Lifecycle methods to have any effect. */ protected void setParentClassLoader(ClassLoader pcl) { parent = pcl; } /** * Return the clearReferencesStatic flag for this Context. */ public boolean getClearReferencesStatic() { return (this.clearReferencesStatic); } /** * Set the clearReferencesStatic feature for this Context. * * @param clearReferencesStatic The new flag value */ public void setClearReferencesStatic(boolean clearReferencesStatic) { this.clearReferencesStatic = clearReferencesStatic; } /** * Return the clearReferencesStopThreads flag for this Context. */ public boolean getClearReferencesStopThreads() { return (this.clearReferencesStopThreads); } /** * Set the clearReferencesStopThreads feature for this Context. * * @param clearReferencesStopThreads The new flag value */ public void setClearReferencesStopThreads( boolean clearReferencesStopThreads) { this.clearReferencesStopThreads = clearReferencesStopThreads; } /** * Return the clearReferencesStopTimerThreads flag for this Context. */ public boolean getClearReferencesStopTimerThreads() { return (this.clearReferencesStopTimerThreads); } /** * Set the clearReferencesStopTimerThreads feature for this Context. * * @param clearReferencesStopTimerThreads The new flag value */ public void setClearReferencesStopTimerThreads( boolean clearReferencesStopTimerThreads) { this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads; } /** * Return the clearReferencesLogFactoryRelease flag for this Context. */ public boolean getClearReferencesLogFactoryRelease() { return (this.clearReferencesLogFactoryRelease); } /** * Set the clearReferencesLogFactoryRelease feature for this Context. * * @param clearReferencesLogFactoryRelease The new flag value */ public void setClearReferencesLogFactoryRelease( boolean clearReferencesLogFactoryRelease) { this.clearReferencesLogFactoryRelease = clearReferencesLogFactoryRelease; } /** * Return the clearReferencesHttpClientKeepAliveThread flag for this * Context. */ public boolean getClearReferencesHttpClientKeepAliveThread() { return (this.clearReferencesHttpClientKeepAliveThread); } /** * Set the clearReferencesHttpClientKeepAliveThread feature for this * Context. * * @param clearReferencesHttpClientKeepAliveThread The new flag value */ public void setClearReferencesHttpClientKeepAliveThread( boolean clearReferencesHttpClientKeepAliveThread) { this.clearReferencesHttpClientKeepAliveThread = clearReferencesHttpClientKeepAliveThread; } // ------------------------------------------------------- Reloader Methods /** * Set the place this ClassLoader can look for classes to be loaded. * * @param repository Name of a source of classes to be loaded, such as a * directory pathname, a JAR file pathname, or a ZIP file pathname * * @exception IllegalArgumentException if the specified repository is * invalid or does not exist */ synchronized void setRepository(String repository, File file) { // Note : There should be only one (of course), but I think we should // keep this a bit generic if (repository == null) return; if (log.isDebugEnabled()) log.debug("addRepository(" + repository + ")"); this.repository = repository; this.file = file; } synchronized void addJar(String jar, JarFile jarFile, File file) throws IOException { if (jar == null) return; if (jarFile == null) return; if (file == null) return; if (log.isDebugEnabled()) log.debug("addJar(" + jar + ")"); int i; if ((jarPath != null) && (jar.startsWith(jarPath))) { String jarName = jar.substring(jarPath.length()); while (jarName.startsWith("/")) jarName = jarName.substring(1); String[] result = new String[jarNames.length + 1]; for (i = 0; i < jarNames.length; i++) { result[i] = jarNames[i]; } result[jarNames.length] = jarName; jarNames = result; } // Register the JAR for tracking long lastModified = resources.getResource(jar).getLastModified(); String[] result = new String[paths.length + 1]; for (i = 0; i < paths.length; i++) { result[i] = paths[i]; } result[paths.length] = jar; paths = result; long[] result3 = new long[lastModifiedDates.length + 1]; for (i = 0; i < lastModifiedDates.length; i++) { result3[i] = lastModifiedDates[i]; } result3[lastModifiedDates.length] = lastModified; lastModifiedDates = result3; // If the JAR currently contains invalid classes, don't actually use it // for classloading if (!validateJarFile(file)) return; JarFile[] result2 = new JarFile[jarFiles.length + 1]; for (i = 0; i < jarFiles.length; i++) { result2[i] = jarFiles[i]; } result2[jarFiles.length] = jarFile; jarFiles = result2; // Add the file to the list File[] result4 = new File[jarRealFiles.length + 1]; for (i = 0; i < jarRealFiles.length; i++) { result4[i] = jarRealFiles[i]; } result4[jarRealFiles.length] = file; jarRealFiles = result4; } /** * Have one or more classes or resources been modified so that a reload * is appropriate? */ public boolean modified() { if (log.isDebugEnabled()) log.debug("modified()"); // Checking for modified loaded resources int length = paths.length; // A rare race condition can occur in the updates of the two arrays // It's totally ok if the latest class added is not checked (it will // be checked the next time int length2 = lastModifiedDates.length; if (length > length2) length = length2; for (int i = 0; i < length; i++) { long lastModified = resources.getResource(paths[i]).getLastModified(); if (lastModified != lastModifiedDates[i]) { if( log.isDebugEnabled() ) log.debug(" Resource '" + paths[i] + "' was modified; Date is now: " + new java.util.Date(lastModified) + " Was: " + new java.util.Date(lastModifiedDates[i])); return true; } } length = jarNames.length; // Check if JARs have been added or removed if (getJarPath() != null) { WebResource[] jars = resources.listResources(getJarPath()); int i = 0; int j = 0; for (; j < jars.length && i < length; j++) { // Ignore non JARs present in the lib folder String name = jars[j].getName(); if (!name.endsWith(".jar")) continue; if (!name.equals(jarNames[i])) { // Missing JAR log.info(" Additional JARs have been added : '" + name + "'"); return true; } i++; } if (j < jars.length ) { for (; j < jars.length; j++) { // Additional non-JAR files are allowed if (jars[j].getName().endsWith(".jar")) { // There was more JARs log.info(" Additional JARs have been added"); return true; } } } else if (i < jarNames.length) { // There was less JARs log.info(" Additional JARs have been added"); return (true); } } // No classes have been modified return false; } /** * Render a String representation of this object. */ @Override public String toString() { StringBuilder sb = new StringBuilder("WebappClassLoader\r\n"); sb.append(" context: "); sb.append(getContextName()); sb.append("\r\n"); sb.append(" delegate: "); sb.append(delegate); sb.append("\r\n"); sb.append(" repository: "); sb.append(repository); sb.append("\r\n"); if (this.parent != null) { sb.append("----------> Parent Classloader:\r\n"); sb.append(this.parent.toString()); sb.append("\r\n"); } return (sb.toString()); } // ---------------------------------------------------- ClassLoader Methods /** * Expose this method for use by the unit tests. */ protected final Class<?> doDefineClass(String name, byte[] b, int off, int len, ProtectionDomain protectionDomain) { return super.defineClass(name, b, off, len, protectionDomain); } /** * Find the specified class in our local repositories, if possible. If * not found, throw <code>ClassNotFoundException</code>. * * @param name Name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> findClass(String name) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug(" findClass(" + name + ")"); // Cannot load anything from local repositories if class loader is stopped if (!started) { throw new ClassNotFoundException(name); } // (1) Permission to define this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { if (log.isTraceEnabled()) log.trace(" securityManager.checkPackageDefinition"); securityManager.checkPackageDefinition(name.substring(0,i)); } catch (Exception se) { if (log.isTraceEnabled()) log.trace(" -->Exception-->ClassNotFoundException", se); throw new ClassNotFoundException(name, se); } } } // Ask our superclass to locate this class, if possible // (throws ClassNotFoundException if it is not found) Class<?> clazz = null; try { if (log.isTraceEnabled()) log.trace(" findClassInternal(" + name + ")"); try { clazz = findClassInternal(name); } catch(ClassNotFoundException cnfe) { if (log.isDebugEnabled()) log.debug(" --> Returning ClassNotFoundException"); throw cnfe; } catch(AccessControlException ace) { log.warn("WebappClassLoader.findClassInternal(" + name + ") security exception: " + ace.getMessage(), ace); throw new ClassNotFoundException(name, ace); } catch (RuntimeException e) { if (log.isTraceEnabled()) log.trace(" -->RuntimeException Rethrown", e); throw e; } } catch (ClassNotFoundException e) { if (log.isTraceEnabled()) log.trace(" --> Passing on ClassNotFoundException"); throw e; } // Return the class we have located if (log.isTraceEnabled()) log.debug(" Returning class " + clazz); if (log.isTraceEnabled()) { ClassLoader cl; if (Globals.IS_SECURITY_ENABLED){ cl = AccessController.doPrivileged( new PrivilegedGetClassLoader(clazz)); } else { cl = clazz.getClassLoader(); } log.debug(" Loaded by " + cl.toString()); } return (clazz); } /** * Find the specified resource in our local repository, and return a * <code>URL</code> referring to it, or <code>null</code> if this resource * cannot be found. * * @param name Name of the resource to be found */ @Override public URL findResource(final String name) { if (log.isDebugEnabled()) log.debug(" findResource(" + name + ")"); URL url = null; ResourceEntry entry = resourceEntries.get(name); if (entry == null) { if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, name); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, name); } } if (entry != null) { url = entry.source; } if (log.isDebugEnabled()) { if (url != null) log.debug(" --> Returning '" + url.toString() + "'"); else log.debug(" --> Resource not found, returning null"); } return (url); } /** * Return an enumeration of <code>URLs</code> representing all of the * resources with the given name. If no resources with this name are * found, return an empty enumeration. * * @param name Name of the resources to be found * * @exception IOException if an input/output error occurs */ @Override public Enumeration<URL> findResources(String name) throws IOException { if (log.isDebugEnabled()) log.debug(" findResources(" + name + ")"); LinkedHashSet<URL> result = new LinkedHashSet<>(); int jarFilesLength = jarFiles.length; if (repository != null) { // Looking at the repository WebResource[] webResources = resources.getResources(repository + name); for (WebResource webResource : webResources) { if (webResource.exists()) { result.add(webResource.getURL()); } } } // Looking at the JAR files synchronized (jarFiles) { if (openJARs()) { for (int i = 0; i < jarFilesLength; i++) { JarEntry jarEntry = jarFiles[i].getJarEntry(name); if (jarEntry != null) { try { String jarFakeUrl = getURI(jarRealFiles[i]).toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + name; result.add(new URL(jarFakeUrl)); } catch (MalformedURLException e) { // Ignore } } } } } final Iterator<URL> iterator = result.iterator(); return new Enumeration<URL>() { @Override public boolean hasMoreElements() { return iterator.hasNext(); } @Override public URL nextElement() { return iterator.next(); } }; } /** * Find the resource with the given name. A resource is some data * (images, audio, text, etc.) that can be accessed by class code in a * way that is independent of the location of the code. The name of a * resource is a "/"-separated path name that identifies the resource. * If the resource cannot be found, return <code>null</code>. * <p> * This method searches according to the following algorithm, returning * as soon as it finds the appropriate URL. If the resource cannot be * found, returns <code>null</code>. * <ul> * <li>If the <code>delegate</code> property is set to <code>true</code>, * call the <code>getResource()</code> method of the parent class * loader, if any.</li> * <li>Call <code>findResource()</code> to find this resource in our * locally defined repositories.</li> * <li>Call the <code>getResource()</code> method of the parent class * loader, if any.</li> * </ul> * * @param name Name of the resource to return a URL for */ @Override public URL getResource(String name) { if (log.isDebugEnabled()) log.debug("getResource(" + name + ")"); URL url = null; // (1) Delegate to parent if requested if (delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); ClassLoader loader = parent; if (loader == null) loader = system; url = loader.getResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return (url); } } // (2) Search local repositories url = findResource(name); if (url != null) { // Locating the repository for special handling in the case // of a JAR if (antiJARLocking) { ResourceEntry entry = resourceEntries.get(name); try { String repository = entry.codeBase.toString(); if ((repository.endsWith(".jar")) && (!(name.endsWith(".class")))) { // Copy binary content to the work directory if not present File resourceFile = new File(loaderDir, name); url = getURI(resourceFile); } } catch (Exception e) { // Ignore } } if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return (url); } // (3) Delegate to parent unconditionally if not already attempted if( !delegate ) { ClassLoader loader = parent; if (loader == null) loader = system; url = loader.getResource(name); if (url != null) { if (log.isDebugEnabled()) log.debug(" --> Returning '" + url.toString() + "'"); return (url); } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return (null); } /** * Find the resource with the given name, and return an input stream * that can be used for reading it. The search order is as described * for <code>getResource()</code>, after checking to see if the resource * data has been previously cached. If the resource cannot be found, * return <code>null</code>. * * @param name Name of the resource to return an input stream for */ @Override public InputStream getResourceAsStream(String name) { if (log.isDebugEnabled()) log.debug("getResourceAsStream(" + name + ")"); InputStream stream = null; // (0) Check for a cached copy of this resource stream = findLoadedResource(name); if (stream != null) { if (log.isDebugEnabled()) log.debug(" --> Returning stream from cache"); return (stream); } // (1) Delegate to parent if requested if (delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader " + parent); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return (stream); } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); URL url = findResource(name); if (url != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from local"); stream = findLoadedResource(name); if (stream != null) return (stream); } // (3) Delegate to parent unconditionally if (!delegate) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader unconditionally " + parent); ClassLoader loader = parent; if (loader == null) loader = system; stream = loader.getResourceAsStream(name); if (stream != null) { // FIXME - cache??? if (log.isDebugEnabled()) log.debug(" --> Returning stream from parent"); return (stream); } } // (4) Resource was not found if (log.isDebugEnabled()) log.debug(" --> Resource not found, returning null"); return (null); } /** * Load the class with the specified name. This method searches for * classes in the same manner as <code>loadClass(String, boolean)</code> * with <code>false</code> as the second argument. * * @param name Name of the class to be loaded * * @exception ClassNotFoundException if the class was not found */ @Override public Class<?> loadClass(String name) throws ClassNotFoundException { return (loadClass(name, false)); } /** * Load the class with the specified name, searching using the following * algorithm until it finds and returns the class. If the class cannot * be found, returns <code>ClassNotFoundException</code>. * <ul> * <li>Call <code>findLoadedClass(String)</code> to check if the * class has already been loaded. If it has, the same * <code>Class</code> object is returned.</li> * <li>If the <code>delegate</code> property is set to <code>true</code>, * call the <code>loadClass()</code> method of the parent class * loader, if any.</li> * <li>Call <code>findClass()</code> to find this class in our locally * defined repositories.</li> * <li>Call the <code>loadClass()</code> method of our parent * class loader, if any.</li> * </ul> * If the class was found using the above steps, and the * <code>resolve</code> flag is <code>true</code>, this method will then * call <code>resolveClass(Class)</code> on the resulting Class object. * * @param name Name of the class to be loaded * @param resolve If <code>true</code> then resolve the class * * @exception ClassNotFoundException if the class was not found */ @Override public synchronized Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (log.isDebugEnabled()) log.debug("loadClass(" + name + ", " + resolve + ")"); Class<?> clazz = null; // Log access to stopped classloader if (!started) { try { throw new IllegalStateException(); } catch (IllegalStateException e) { log.info(sm.getString("webappClassLoader.stopped", name), e); } } // (0) Check our previously loaded local class cache clazz = findLoadedClass0(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.1) Check our previously loaded class cache clazz = findLoadedClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Returning class from cache"); if (resolve) resolveClass(clazz); return (clazz); } // (0.2) Try loading the class with the system class loader, to prevent // the webapp from overriding J2SE classes try { clazz = system.loadClass(name); if (clazz != null) { if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (0.5) Permission to access this class when using a SecurityManager if (securityManager != null) { int i = name.lastIndexOf('.'); if (i >= 0) { try { securityManager.checkPackageAccess(name.substring(0,i)); } catch (SecurityException se) { String error = "Security Violation, attempt to use " + "Restricted Class: " + name; log.info(error, se); throw new ClassNotFoundException(error, se); } } } boolean delegateLoad = delegate || filter(name); // (1) Delegate to our parent if requested if (delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader1 " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } // (2) Search local repositories if (log.isDebugEnabled()) log.debug(" Searching local repositories"); try { clazz = findClass(name); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from local repository"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } // (3) Delegate to parent unconditionally if (!delegateLoad) { if (log.isDebugEnabled()) log.debug(" Delegating to parent classloader at end: " + parent); ClassLoader loader = parent; if (loader == null) loader = system; try { clazz = Class.forName(name, false, loader); if (clazz != null) { if (log.isDebugEnabled()) log.debug(" Loading class from parent"); if (resolve) resolveClass(clazz); return (clazz); } } catch (ClassNotFoundException e) { // Ignore } } throw new ClassNotFoundException(name); } /** * Get the Permissions for a CodeSource. If this instance * of WebappClassLoader is for a web application context, * add read FilePermission or JndiPermissions for the base * directory (if unpacked), * the context URL, and jar file resources. * * @param codeSource where the code was loaded from * @return PermissionCollection for CodeSource */ @Override protected PermissionCollection getPermissions(CodeSource codeSource) { String codeUrl = codeSource.getLocation().toString(); PermissionCollection pc; if ((pc = loaderPC.get(codeUrl)) == null) { pc = super.getPermissions(codeSource); if (pc != null) { Iterator<Permission> perms = permissionList.iterator(); while (perms.hasNext()) { Permission p = perms.next(); pc.add(p); } loaderPC.put(codeUrl,pc); } } return (pc); } /** * Returns the search path of URLs for loading classes and resources. * This includes the original list of URLs specified to the constructor, * along with any URLs subsequently appended by the addURL() method. * @return the search path of URLs for loading classes and resources. */ @Override public URL[] getURLs() { if (repositoryURLs != null) { return repositoryURLs.clone(); } int resultLength; if (file == null) { resultLength = jarRealFiles.length; } else { resultLength = jarRealFiles.length + 1; } int off = 0; try { URL[] urls = new URL[resultLength]; if (file != null) { urls[off ++] = getURI(file); } for (File jarRealFile : jarRealFiles) { urls[off++] = getURI(jarRealFile); } repositoryURLs = urls; } catch (MalformedURLException e) { repositoryURLs = new URL[0]; } return repositoryURLs.clone(); } // ------------------------------------------------------ Lifecycle Methods /** * Add a lifecycle event listener to this component. * * @param listener The listener to add */ @Override public void addLifecycleListener(LifecycleListener listener) { // NOOP } /** * Get the lifecycle listeners associated with this lifecycle. If this * Lifecycle has no listeners registered, a zero-length array is returned. */ @Override public LifecycleListener[] findLifecycleListeners() { return new LifecycleListener[0]; } /** * Remove a lifecycle event listener from this component. * * @param listener The listener to remove */ @Override public void removeLifecycleListener(LifecycleListener listener) { // NOOP } /** * Obtain the current state of the source component. * * @return The current state of the source component. */ @Override public LifecycleState getState() { return LifecycleState.NEW; } /** * {@inheritDoc} */ @Override public String getStateName() { return getState().toString(); } @Override public void init() { // NOOP } /** * Start the class loader. * * @exception LifecycleException if a lifecycle error occurs */ @Override public void start() throws LifecycleException { started = true; String encoding = null; try { encoding = System.getProperty("file.encoding"); } catch (SecurityException e) { return; } if (encoding.indexOf("EBCDIC")!=-1) { needConvert = true; } } public boolean isStarted() { return started; } /** * Stop the class loader. * * @exception LifecycleException if a lifecycle error occurs */ @Override public void stop() throws LifecycleException { // Clearing references should be done before setting started to // false, due to possible side effects clearReferences(); started = false; file = null; int length = jarFiles.length; for (int i = 0; i < length; i++) { try { if (jarFiles[i] != null) { jarFiles[i].close(); } } catch (IOException e) { // Ignore } jarFiles[i] = null; } notFoundResources.clear(); resourceEntries.clear(); resources = null; repository = null; repositoryURLs = null; file = null; jarFiles = null; jarRealFiles = null; jarPath = null; jarNames = null; lastModifiedDates = null; paths = null; parent = null; permissionList.clear(); loaderPC.clear(); if (loaderDir != null) { deleteDir(loaderDir); } } @Override public void destroy() { // NOOP } /** * Used to periodically signal to the classloader to release * JAR resources. */ public void closeJARs(boolean force) { if (jarFiles.length > 0) { synchronized (jarFiles) { if (force || (System.currentTimeMillis() > (lastJarAccessed + 90000))) { for (int i = 0; i < jarFiles.length; i++) { try { if (jarFiles[i] != null) { jarFiles[i].close(); jarFiles[i] = null; } } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to close JAR", e); } } } } } } } // ------------------------------------------------------ Protected Methods /** * Clear references. */ protected void clearReferences() { // De-register any remaining JDBC drivers clearReferencesJdbc(); // Stop any threads the web application started clearReferencesThreads(); // Check for leaks triggered by ThreadLocals loaded by this class loader checkThreadLocalsForLeaks(); // Clear RMI Targets loaded by this class loader clearReferencesRmiTargets(); // Null out any static or final fields from loaded classes, // as a workaround for apparent garbage collection bugs if (clearReferencesStatic) { clearReferencesStaticFinal(); } // Clear the IntrospectionUtils cache. IntrospectionUtils.clear(); // Clear the classloader reference in common-logging if (clearReferencesLogFactoryRelease) { org.apache.juli.logging.LogFactory.release(this); } // Clear the resource bundle cache // This shouldn't be necessary, the cache uses weak references but // it has caused leaks. Oddly, using the leak detection code in // standard host allows the class loader to be GC'd. This has been seen // on Sun but not IBM JREs. Maybe a bug in Sun's GC impl? clearReferencesResourceBundles(); // Clear the classloader reference in the VM's bean introspector java.beans.Introspector.flushCaches(); } /** * Deregister any JDBC drivers registered by the webapp that the webapp * forgot. This is made unnecessary complex because a) DriverManager * checks the class loader of the calling class (it would be much easier * if it checked the context class loader) b) using reflection would * create a dependency on the DriverManager implementation which can, * and has, changed. * * We can't just create an instance of JdbcLeakPrevention as it will be * loaded by the common class loader (since it's .class file is in the * $CATALINA_HOME/lib directory). This would fail DriverManager's check * on the class loader of the calling class. So, we load the bytes via * our parent class loader but define the class with this class loader * so the JdbcLeakPrevention looks like a webapp class to the * DriverManager. * * If only apps cleaned up after themselves... */ private final void clearReferencesJdbc() { InputStream is = getResourceAsStream( "org/apache/catalina/loader/JdbcLeakPrevention.class"); // We know roughly how big the class will be (~ 1K) so allow 2k as a // starting point byte[] classBytes = new byte[2048]; int offset = 0; try { int read = is.read(classBytes, offset, classBytes.length-offset); while (read > -1) { offset += read; if (offset == classBytes.length) { // Buffer full - double size byte[] tmp = new byte[classBytes.length * 2]; System.arraycopy(classBytes, 0, tmp, 0, classBytes.length); classBytes = tmp; } read = is.read(classBytes, offset, classBytes.length-offset); } Class<?> lpClass = defineClass("org.apache.catalina.loader.JdbcLeakPrevention", classBytes, 0, offset, this.getClass().getProtectionDomain()); Object obj = lpClass.newInstance(); List<String> driverNames = (List<String>) obj.getClass().getMethod( "clearJdbcDriverRegistrations").invoke(obj); for (String name : driverNames) { log.error(sm.getString("webappClassLoader.clearJdbc", getContextName(), name)); } } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.jdbcRemoveFailed", getContextName()), t); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { log.warn(sm.getString( "webappClassLoader.jdbcRemoveStreamError", getContextName()), ioe); } } } } private final void clearReferencesStaticFinal() { Collection<ResourceEntry> values = ((HashMap<String,ResourceEntry>) resourceEntries.clone()).values(); Iterator<ResourceEntry> loadedClasses = values.iterator(); // // walk through all loaded class to trigger initialization for // any uninitialized classes, otherwise initialization of // one class may call a previously cleared class. while(loadedClasses.hasNext()) { ResourceEntry entry = loadedClasses.next(); if (entry.loadedClass != null) { Class<?> clazz = entry.loadedClass; try { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if(Modifier.isStatic(fields[i].getModifiers())) { fields[i].get(null); break; } } } catch(Throwable t) { // Ignore } } } loadedClasses = values.iterator(); while (loadedClasses.hasNext()) { ResourceEntry entry = loadedClasses.next(); if (entry.loadedClass != null) { Class<?> clazz = entry.loadedClass; try { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) { continue; } if (Modifier.isStatic(mods)) { try { field.setAccessible(true); if (Modifier.isFinal(mods)) { if (!((field.getType().getName().startsWith("java.")) || (field.getType().getName().startsWith("javax.")))) { nullInstance(field.get(null)); } } else { field.set(null, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + clazz.getName()); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in class " + clazz.getName(), t); } } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not clean fields for class " + clazz.getName(), t); } } } } } private void nullInstance(Object instance) { if (instance == null) { return; } Field[] fields = instance.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; int mods = field.getModifiers(); if (field.getType().isPrimitive() || (field.getName().indexOf("$") != -1)) { continue; } try { field.setAccessible(true); if (Modifier.isStatic(mods) && Modifier.isFinal(mods)) { // Doing something recursively is too risky continue; } Object value = field.get(instance); if (null != value) { Class<? extends Object> valueClass = value.getClass(); if (!loadedByThisOrChild(valueClass)) { if (log.isDebugEnabled()) { log.debug("Not setting field " + field.getName() + " to null in object of class " + instance.getClass().getName() + " because the referenced object was of type " + valueClass.getName() + " which was not loaded by this WebappClassLoader."); } } else { field.set(instance, null); if (log.isDebugEnabled()) { log.debug("Set field " + field.getName() + " to null in class " + instance.getClass().getName()); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { log.debug("Could not set field " + field.getName() + " to null in object instance of class " + instance.getClass().getName(), t); } } } } @SuppressWarnings("deprecation") // thread.stop() private void clearReferencesThreads() { Thread[] threads = getThreads(); // Iterate over the set of threads for (Thread thread : threads) { if (thread != null) { ClassLoader ccl = thread.getContextClassLoader(); if (ccl == this) { // Don't warn about this thread if (thread == Thread.currentThread()) { continue; } // JVM controlled threads ThreadGroup tg = thread.getThreadGroup(); if (tg != null && JVM_THREAD_GROUP_NAMES.contains(tg.getName())) { // HttpClient keep-alive threads if (clearReferencesHttpClientKeepAliveThread && thread.getName().equals("Keep-Alive-Timer")) { thread.setContextClassLoader(parent); log.debug(sm.getString( "webappClassLoader.checkThreadsHttpClient")); } // Don't warn about remaining JVM controlled threads continue; } // Skip threads that have already died if (!thread.isAlive()) { continue; } // TimerThread can be stopped safely so treat separately // "java.util.TimerThread" in Sun/Oracle JDK // "java.util.Timer$TimerImpl" in Apache Harmony and in IBM JDK if (thread.getClass().getName().startsWith("java.util.Timer") && clearReferencesStopTimerThreads) { clearReferencesStopTimerThread(thread); continue; } if (isRequestThread(thread)) { log.error(sm.getString("webappClassLoader.warnRequestThread", getContextName(), thread.getName())); } else { log.error(sm.getString("webappClassLoader.warnThread", getContextName(), thread.getName())); } // Don't try an stop the threads unless explicitly // configured to do so if (!clearReferencesStopThreads) { continue; } // If the thread has been started via an executor, try // shutting down the executor try { // Runnable wrapped by Thread // "target" in Sun/Oracle JDK // "runnable" in IBM JDK // "action" in Apache Harmony Object target = null; for (String fieldName : new String[] { "target", "runnable", "action" }) { try { Field targetField = thread.getClass() .getDeclaredField(fieldName); targetField.setAccessible(true); target = targetField.get(thread); break; } catch (NoSuchFieldException nfe) { continue; } } // "java.util.concurrent" code is in public domain, // so all implementations are similar if (target != null && target.getClass().getCanonicalName() != null && target.getClass().getCanonicalName().equals( "java.util.concurrent.ThreadPoolExecutor.Worker")) { Field executorField = target.getClass().getDeclaredField("this$0"); executorField.setAccessible(true); Object executor = executorField.get(target); if (executor instanceof ThreadPoolExecutor) { ((ThreadPoolExecutor) executor).shutdownNow(); } } } catch (SecurityException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), getContextName()), e); } catch (NoSuchFieldException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), getContextName()), e); } catch (IllegalArgumentException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), getContextName()), e); } catch (IllegalAccessException e) { log.warn(sm.getString( "webappClassLoader.stopThreadFail", thread.getName(), getContextName()), e); } // This method is deprecated and for good reason. This is // very risky code but is the only option at this point. // A *very* good reason for apps to do this clean-up // themselves. thread.stop(); } } } } /* * Look at a threads stack trace to see if it is a request thread or not. It * isn't perfect, but it should be good-enough for most cases. */ private boolean isRequestThread(Thread thread) { StackTraceElement[] elements = thread.getStackTrace(); if (elements == null || elements.length == 0) { // Must have stopped already. Too late to ignore it. Assume not a // request processing thread. return false; } // Step through the methods in reverse order looking for calls to any // CoyoteAdapter method. All request threads will have this unless // Tomcat has been heavily modified - in which case there isn't much we // can do. for (int i = 0; i < elements.length; i++) { StackTraceElement element = elements[elements.length - (i+1)]; if ("org.apache.catalina.connector.CoyoteAdapter".equals( element.getClassName())) { return true; } } return false; } private void clearReferencesStopTimerThread(Thread thread) { // Need to get references to: // in Sun/Oracle JDK: // - newTasksMayBeScheduled field (in java.util.TimerThread) // - queue field // - queue.clear() // in IBM JDK, Apache Harmony: // - cancel() method (in java.util.Timer$TimerImpl) try { try { Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled"); newTasksMayBeScheduledField.setAccessible(true); Field queueField = thread.getClass().getDeclaredField("queue"); queueField.setAccessible(true); Object queue = queueField.get(thread); Method clearMethod = queue.getClass().getDeclaredMethod("clear"); clearMethod.setAccessible(true); synchronized(queue) { newTasksMayBeScheduledField.setBoolean(thread, false); clearMethod.invoke(queue); queue.notify(); // In case queue was already empty. } }catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } log.error(sm.getString("webappClassLoader.warnTimerThread", getContextName(), thread.getName())); } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), getContextName()), t); } } private void checkThreadLocalsForLeaks() { Thread[] threads = getThreads(); try { // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); expungeStaleEntriesMethod.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } // Clear the second map threadLocalMap =inheritableThreadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), t); } } /** * Analyzes the given thread local map object. Also pass in the field that * points to the internal table to save re-calculating it on every * call to this method. */ private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { Object obj = table[j]; if (obj != null) { boolean potentialLeak = false; // Check the key Object key = ((Reference<?>) obj).get(); if (this.equals(key) || loadedByThisOrChild(key)) { potentialLeak = true; } // Check the value Field valueField = obj.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(obj); if (this.equals(value) || loadedByThisOrChild(value)) { potentialLeak = true; } if (potentialLeak) { Object[] args = new Object[5]; args[0] = getContextName(); if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksDebug", args)); } } else { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } } } } } } } private String getPrettyClassName(Class<?> clazz) { String name = clazz.getCanonicalName(); if (name==null){ name = clazz.getName(); } return name; } /** * @param o object to test, may be null * @return <code>true</code> if o has been loaded by the current classloader * or one of its descendants. */ private boolean loadedByThisOrChild(Object o) { if (o == null) { return false; } Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>) o; } else { clazz = o.getClass(); } ClassLoader cl = clazz.getClassLoader(); while (cl != null) { if (cl == this) { return true; } cl = cl.getParent(); } if (o instanceof Collection<?>) { Iterator<?> iter = ((Collection<?>) o).iterator(); while (iter.hasNext()) { Object entry = iter.next(); if (loadedByThisOrChild(entry)) { return true; } } } return false; } /* * Get the set of current threads as an array. */ private Thread[] getThreads() { // Get the current thread group ThreadGroup tg = Thread.currentThread( ).getThreadGroup( ); // Find the root thread group while (tg.getParent() != null) { tg = tg.getParent(); } int threadCountGuess = tg.activeCount() + 50; Thread[] threads = new Thread[threadCountGuess]; int threadCountActual = tg.enumerate(threads); // Make sure we don't miss any threads while (threadCountActual == threadCountGuess) { threadCountGuess *=2; threads = new Thread[threadCountGuess]; // Note tg.enumerate(Thread[]) silently ignores any threads that // can't fit into the array threadCountActual = tg.enumerate(threads); } return threads; } /** * This depends on the internals of the Sun JVM so it does everything by * reflection. */ private void clearReferencesRmiTargets() { try { // Need access to the ccl field of sun.rmi.transport.Target Class<?> objectTargetClass = Class.forName("sun.rmi.transport.Target"); Field cclField = objectTargetClass.getDeclaredField("ccl"); cclField.setAccessible(true); // Clear the objTable map Class<?> objectTableClass = Class.forName("sun.rmi.transport.ObjectTable"); Field objTableField = objectTableClass.getDeclaredField("objTable"); objTableField.setAccessible(true); Object objTable = objTableField.get(null); if (objTable == null) { return; } // Iterate over the values in the table if (objTable instanceof Map<?,?>) { Iterator<?> iter = ((Map<?,?>) objTable).values().iterator(); while (iter.hasNext()) { Object obj = iter.next(); Object cclObject = cclField.get(obj); if (this == cclObject) { iter.remove(); } } } // Clear the implTable map Field implTableField = objectTableClass.getDeclaredField("implTable"); implTableField.setAccessible(true); Object implTable = implTableField.get(null); if (implTable == null) { return; } // Iterate over the values in the table if (implTable instanceof Map<?,?>) { Iterator<?> iter = ((Map<?,?>) implTable).values().iterator(); while (iter.hasNext()) { Object obj = iter.next(); Object cclObject = cclField.get(obj); if (this == cclObject) { iter.remove(); } } } } catch (ClassNotFoundException e) { log.info(sm.getString("webappClassLoader.clearRmiInfo", getContextName()), e); } catch (SecurityException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", getContextName()), e); } catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", getContextName()), e); } catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", getContextName()), e); } catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.clearRmiFail", getContextName()), e); } } /** * Clear the {@link ResourceBundle} cache of any bundles loaded by this * class loader or any class loader where this loader is a parent class * loader. Whilst {@link ResourceBundle#clearCache()} could be used there * are complications around the * {@link org.apache.jasper.servlet.JasperLoader} that mean a reflection * based approach is more likely to be complete. * * The ResourceBundle is using WeakReferences so it shouldn't be pinning the * class loader in memory. However, it is. Therefore clear ou the * references. */ private void clearReferencesResourceBundles() { // Get a reference to the cache try { Field cacheListField = ResourceBundle.class.getDeclaredField("cacheList"); cacheListField.setAccessible(true); // Java 6 uses ConcurrentMap // Java 5 uses SoftCache extends Abstract Map // So use Map and it *should* work with both Map<?,?> cacheList = (Map<?,?>) cacheListField.get(null); // Get the keys (loader references are in the key) Set<?> keys = cacheList.keySet(); Field loaderRefField = null; // Iterate over the keys looking at the loader instances Iterator<?> keysIter = keys.iterator(); int countRemoved = 0; while (keysIter.hasNext()) { Object key = keysIter.next(); if (loaderRefField == null) { loaderRefField = key.getClass().getDeclaredField("loaderRef"); loaderRefField.setAccessible(true); } WeakReference<?> loaderRef = (WeakReference<?>) loaderRefField.get(key); ClassLoader loader = (ClassLoader) loaderRef.get(); while (loader != null && loader != this) { loader = loader.getParent(); } if (loader != null) { keysIter.remove(); countRemoved++; } } if (countRemoved > 0 && log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesCount", Integer.valueOf(countRemoved), getContextName())); } } catch (SecurityException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } catch (NoSuchFieldException e) { if (System.getProperty("java.vendor").startsWith("Sun")) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } else { log.debug(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } } catch (IllegalArgumentException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } catch (IllegalAccessException e) { log.error(sm.getString( "webappClassLoader.clearReferencesResourceBundlesFail", getContextName()), e); } } /** * Used to periodically signal to the classloader to release JAR resources. */ protected boolean openJARs() { if (started && (jarFiles.length > 0)) { lastJarAccessed = System.currentTimeMillis(); if (jarFiles[0] == null) { for (int i = 0; i < jarFiles.length; i++) { try { jarFiles[i] = new JarFile(jarRealFiles[i]); } catch (IOException e) { if (log.isDebugEnabled()) { log.debug("Failed to open JAR", e); } return false; } } } } return true; } /** * Find specified class in local repositories. * * @return the loaded class, or null if the class isn't found */ protected Class<?> findClassInternal(String name) throws ClassNotFoundException { if (!validate(name)) throw new ClassNotFoundException(name); String tempPath = name.replace('.', '/'); String classPath = tempPath + ".class"; ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, classPath); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, classPath); } if (entry == null) throw new ClassNotFoundException(name); Class<?> clazz = entry.loadedClass; if (clazz != null) return clazz; synchronized (this) { clazz = entry.loadedClass; if (clazz != null) return clazz; if (entry.binaryContent == null) throw new ClassNotFoundException(name); // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); Package pkg = null; if (packageName != null) { pkg = getPackage(packageName); // Define the package (if null) if (pkg == null) { try { if (entry.manifest == null) { definePackage(packageName, null, null, null, null, null, null, null); } else { definePackage(packageName, entry.manifest, entry.codeBase); } } catch (IllegalArgumentException e) { // Ignore: normal error due to dual definition of package } pkg = getPackage(packageName); } } if (securityManager != null) { // Checking sealing if (pkg != null) { boolean sealCheck = true; if (pkg.isSealed()) { sealCheck = pkg.isSealed(entry.codeBase); } else { sealCheck = (entry.manifest == null) || !isPackageSealed(packageName, entry.manifest); } if (!sealCheck) throw new SecurityException ("Sealing violation loading " + name + " : Package " + packageName + " is sealed."); } } try { clazz = defineClass(name, entry.binaryContent, 0, entry.binaryContent.length, new CodeSource(entry.codeBase, entry.certificates)); } catch (UnsupportedClassVersionError ucve) { throw new UnsupportedClassVersionError( ucve.getLocalizedMessage() + " " + sm.getString("webappClassLoader.wrongVersion", name)); } entry.loadedClass = clazz; entry.binaryContent = null; entry.source = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; } return clazz; } /** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found */ protected ResourceEntry findResourceInternal(File file, String path){ ResourceEntry entry = new ResourceEntry(); try { entry.source = getURI(new File(file, path)); entry.codeBase = entry.source; } catch (MalformedURLException e) { return null; } return entry; } /** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found */ protected ResourceEntry findResourceInternal(String name, String path) { if (!started) { log.info(sm.getString("webappClassLoader.stopped", name)); return null; } if ((name == null) || (path == null)) return null; ResourceEntry entry = resourceEntries.get(name); if (entry != null) return entry; int contentLength = -1; InputStream binaryStream = null; boolean isClassResource = path.endsWith(".class"); int jarFilesLength = jarFiles.length; WebResource resource = null; boolean fileNeedConvert = false; if (repository != null) { String fullPath = repository + path; resource = resources.getResource(fullPath); if (resource.exists()) { contentLength = (int) resource.getContentLength(); String canonicalPath = resource.getCanonicalPath(); if (canonicalPath != null) { // we create the ResourceEntry based on the information returned // by the DirContext rather than just using the path to the // repository. This allows to have smart DirContext implementations // that "virtualize" the docbase (e.g. Eclipse WTP) entry = findResourceInternal(new File(canonicalPath), ""); } else { // probably a resource not in the filesystem (e.g. in a // packaged war) entry = findResourceInternal(file, path); } entry.lastModified = resource.getLastModified(); binaryStream = resource.getInputStream(); if (needConvert) { if (path.endsWith(".properties")) { fileNeedConvert = true; } } // Register the full path for modification checking // Note: Only syncing on a 'constant' object is needed synchronized (allPermission) { int j; long[] result2 = new long[lastModifiedDates.length + 1]; for (j = 0; j < lastModifiedDates.length; j++) { result2[j] = lastModifiedDates[j]; } result2[lastModifiedDates.length] = entry.lastModified; lastModifiedDates = result2; String[] result = new String[paths.length + 1]; for (j = 0; j < paths.length; j++) { result[j] = paths[j]; } result[paths.length] = fullPath; paths = result; } } } if ((entry == null) && (notFoundResources.containsKey(name))) return null; JarEntry jarEntry = null; synchronized (jarFiles) { try { if (!openJARs()) { return null; } for (int i = 0; (entry == null) && (i < jarFilesLength); i++) { jarEntry = jarFiles[i].getJarEntry(path); if (jarEntry != null) { entry = new ResourceEntry(); try { entry.codeBase = getURI(jarRealFiles[i]); String jarFakeUrl = entry.codeBase.toString(); jarFakeUrl = "jar:" + jarFakeUrl + "!/" + path; entry.source = new URL(jarFakeUrl); entry.lastModified = jarRealFiles[i].lastModified(); } catch (MalformedURLException e) { return null; } contentLength = (int) jarEntry.getSize(); try { entry.manifest = jarFiles[i].getManifest(); binaryStream = jarFiles[i].getInputStream(jarEntry); } catch (IOException e) { return null; } // Extract resources contained in JAR to the workdir if (antiJARLocking && !(path.endsWith(".class"))) { byte[] buf = new byte[1024]; File resourceFile = new File (loaderDir, jarEntry.getName()); if (!resourceFile.exists()) { Enumeration<JarEntry> entries = jarFiles[i].entries(); while (entries.hasMoreElements()) { JarEntry jarEntry2 = entries.nextElement(); if (!(jarEntry2.isDirectory()) && (!jarEntry2.getName().endsWith (".class"))) { resourceFile = new File (loaderDir, jarEntry2.getName()); try { if (!resourceFile.getCanonicalPath().startsWith( canonicalLoaderDir)) { throw new IllegalArgumentException( sm.getString("webappClassLoader.illegalJarPath", jarEntry2.getName())); } } catch (IOException ioe) { throw new IllegalArgumentException( sm.getString("webappClassLoader.validationErrorJarPath", jarEntry2.getName()), ioe); } File parentFile = resourceFile.getParentFile(); if (!parentFile.mkdirs() && !parentFile.exists()) { // Ignore the error (like the IOExceptions below) } FileOutputStream os = null; InputStream is = null; try { is = jarFiles[i].getInputStream (jarEntry2); os = new FileOutputStream (resourceFile); while (true) { int n = is.read(buf); if (n <= 0) { break; } os.write(buf, 0, n); } resourceFile.setLastModified( jarEntry2.getTime()); } catch (IOException e) { // Ignore } finally { try { if (is != null) { is.close(); } } catch (IOException e) { // Ignore } try { if (os != null) { os.close(); } } catch (IOException e) { // Ignore } } } } } } } } if (entry == null) { synchronized (notFoundResources) { notFoundResources.put(name, name); } return null; } /* Only cache the binary content if there is some content * available and either: * a) It is a class file since the binary content is only cached * until the class has been loaded * or * b) The file needs conversion to address encoding issues (see * below) * * In all other cases do not cache the content to prevent * excessive memory usage if large resources are present (see * https://issues.apache.org/bugzilla/show_bug.cgi?id=53081). */ if (binaryStream != null && (isClassResource || fileNeedConvert)) { byte[] binaryContent = new byte[contentLength]; int pos = 0; try { while (true) { int n = binaryStream.read(binaryContent, pos, binaryContent.length - pos); if (n <= 0) break; pos += n; } } catch (IOException e) { log.error(sm.getString("webappClassLoader.readError", name), e); return null; } if (fileNeedConvert) { // Workaround for certain files on platforms that use // EBCDIC encoding, when they are read through FileInputStream. // See commit message of rev.303915 for details // http://svn.apache.org/viewvc?view=revision&revision=303915 String str = new String(binaryContent,0,pos); try { binaryContent = str.getBytes(CHARSET_UTF8); } catch (Exception e) { return null; } } entry.binaryContent = binaryContent; // The certificates are only available after the JarEntry // associated input stream has been fully read if (jarEntry != null) { entry.certificates = jarEntry.getCertificates(); } } } finally { if (binaryStream != null) { try { binaryStream.close(); } catch (IOException e) { /* Ignore */} } } } // Add the entry in the local resource repository synchronized (resourceEntries) { // Ensures that all the threads which may be in a race to load // a particular class all end up with the same ResourceEntry // instance ResourceEntry entry2 = resourceEntries.get(name); if (entry2 == null) { resourceEntries.put(name, entry); } else { entry = entry2; } } return entry; } /** * Returns true if the specified package name is sealed according to the * given manifest. */ protected boolean isPackageSealed(String name, Manifest man) { String path = name.replace('.', '/') + '/'; Attributes attr = man.getAttributes(path); String sealed = null; if (attr != null) { sealed = attr.getValue(Name.SEALED); } if (sealed == null) { if ((attr = man.getMainAttributes()) != null) { sealed = attr.getValue(Name.SEALED); } } return "true".equalsIgnoreCase(sealed); } /** * Finds the resource with the given name if it has previously been * loaded and cached by this class loader, and return an input stream * to the resource data. If this resource has not been cached, return * <code>null</code>. * * @param name Name of the resource to return */ protected InputStream findLoadedResource(String name) { ResourceEntry entry = resourceEntries.get(name); if (entry != null) { if (entry.binaryContent != null) return new ByteArrayInputStream(entry.binaryContent); else { try { return entry.source.openStream(); } catch (IOException ioe) { // Ignore } } } return null; } /** * Finds the class with the given name if it has previously been * loaded and cached by this class loader, and return the Class object. * If this class has not been cached, return <code>null</code>. * * @param name Name of the resource to return */ protected Class<?> findLoadedClass0(String name) { ResourceEntry entry = resourceEntries.get(name); if (entry != null) { return entry.loadedClass; } return (null); // FIXME - findLoadedResource() } /** * Refresh the system policy file, to pick up eventual changes. */ protected void refreshPolicy() { try { // The policy file may have been modified to adjust // permissions, so we're reloading it when loading or // reloading a Context Policy policy = Policy.getPolicy(); policy.refresh(); } catch (AccessControlException e) { // Some policy files may restrict this, even for the core, // so this exception is ignored } } /** * Filter classes. * * @param name class name * @return true if the class should be filtered */ protected boolean filter(String name) { if (name == null) return false; // Looking up the package String packageName = null; int pos = name.lastIndexOf('.'); if (pos != -1) packageName = name.substring(0, pos); else return false; for (int i = 0; i < packageTriggers.length; i++) { if (packageName.startsWith(packageTriggers[i])) return true; } return false; } /** * Validate a classname. As per SRV.9.7.2, we must restrict loading of * classes from J2SE (java.*) and most classes of the servlet API * (javax.servlet.*). That should enhance robustness and prevent a number * of user error (where an older version of servlet.jar would be present * in /WEB-INF/lib). * * @param name class name * @return true if the name is valid */ protected boolean validate(String name) { // Need to be careful with order here if (name == null) { // Can't load a class without a name return false; } if (name.startsWith("java.")) { // Must never load java.* classes return false; } if (name.startsWith("javax.servlet.jsp.jstl")) { // OK for web apps to package JSTL return true; } if (name.startsWith("javax.servlet.")) { // Web apps should never package any other Servlet or JSP classes return false; } if (name.startsWith("javax.el")) { // Must never load javax.el.* classes return false; } // Assume everything else is OK return true; } /** * Check the specified JAR file, and return <code>true</code> if it does * not contain any of the trigger classes. * * @param file The JAR file to be checked * * @exception IOException if an input/output error occurs */ protected boolean validateJarFile(File file) throws IOException { if (triggers == null) return (true); JarFile jarFile = null; try { jarFile = new JarFile(file); for (int i = 0; i < triggers.length; i++) { Class<?> clazz = null; try { if (parent != null) { clazz = parent.loadClass(triggers[i]); } else { clazz = Class.forName(triggers[i]); } } catch (Exception e) { clazz = null; } if (clazz == null) continue; String name = triggers[i].replace('.', '/') + ".class"; if (log.isDebugEnabled()) log.debug(" Checking for " + name); JarEntry jarEntry = jarFile.getJarEntry(name); if (jarEntry != null) { log.info("validateJarFile(" + file + ") - jar not loaded. See Servlet Spec 2.3, " + "section 9.7.2. Offending class: " + name); return false; } } return true; } finally { if (jarFile != null) { try { jarFile.close(); } catch (IOException ioe) { // Ignore } } } } /** * Get the URI for the given file. */ protected URL getURI(File file) throws MalformedURLException { File realFile = file; try { realFile = realFile.getCanonicalFile(); } catch (IOException e) { // Ignore } return realFile.toURI().toURL(); } /** * Delete the specified directory, including all of its contents and * subdirectories recursively. * * @param dir File object representing the directory to be deleted */ protected static void deleteDir(File dir) { String files[] = dir.list(); if (files == null) { files = new String[0]; } for (int i = 0; i < files.length; i++) { File file = new File(dir, files[i]); if (file.isDirectory()) { deleteDir(file); } else { file.delete(); } } dir.delete(); } }
54,703
Bug 54703 Nullpointer exception in HttpParser.parseMediaType
input for parseMediaType() is ---------- multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="----=_Part_121_929034657.1363355797756" ---------- exception trace java.lang.NullPointerException at org.apache.tomcat.util.http.parser.HttpParser.parseMediaType(HttpParser.java:215) at org.apache.tomcat.util.http.parser.MediaTypeCache.parse(MediaTypeCache.java:54) at org.apache.catalina.connector.Response.setContentType(Response.java:806) at org.apache.catalina.connector.Response.checkSpecialHeader(Response.java:1119) at org.apache.catalina.connector.Response.setHeader(Response.java:1446) at org.apache.catalina.connector.ResponseFacade.setHeader(ResponseFacade.java:535)
resolved fixed
7aeab0e
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-07T15:51:22Z
2013-03-15T17:53:20Z
java/org/apache/tomcat/util/http/parser/HttpParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.http.parser; import java.io.IOException; import java.io.StringReader; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * HTTP header value parser implementation. Parsing HTTP headers as per RFC2616 * is not always as simple as it first appears. For headers that only use tokens * the simple approach will normally be sufficient. However, for the other * headers, while simple code meets 99.9% of cases, there are often some edge * cases that make things far more complicated. * * The purpose of this parser is to let the parser worry about the edge cases. * It provides tolerant (where safe to do so) parsing of HTTP header values * assuming that wrapped header lines have already been unwrapped. (The Tomcat * header processing code does the unwrapping.) * * Provides parsing of the following HTTP header values as per RFC 2616: * - Authorization for DIGEST authentication * - MediaType (used for Content-Type header) * * Support for additional headers will be provided as required. */ public class HttpParser { @SuppressWarnings("unused") // Unused due to buggy client implementations private static final Integer FIELD_TYPE_TOKEN = Integer.valueOf(0); private static final Integer FIELD_TYPE_QUOTED_STRING = Integer.valueOf(1); private static final Integer FIELD_TYPE_TOKEN_OR_QUOTED_STRING = Integer.valueOf(2); private static final Integer FIELD_TYPE_LHEX = Integer.valueOf(3); private static final Integer FIELD_TYPE_QUOTED_TOKEN = Integer.valueOf(4); private static final Map<String,Integer> fieldTypes = new HashMap<>(); // Arrays used by isToken(), isHex() private static final boolean isToken[] = new boolean[128]; private static final boolean isHex[] = new boolean[128]; static { // Digest field types. // Note: These are more relaxed than RFC2617. This adheres to the // recommendation of RFC2616 that servers are tolerant of buggy // clients when they can be so without ambiguity. fieldTypes.put("username", FIELD_TYPE_QUOTED_STRING); fieldTypes.put("realm", FIELD_TYPE_QUOTED_STRING); fieldTypes.put("nonce", FIELD_TYPE_QUOTED_STRING); fieldTypes.put("digest-uri", FIELD_TYPE_QUOTED_STRING); // RFC2617 says response is <">32LHEX<">. 32LHEX will also be accepted fieldTypes.put("response", FIELD_TYPE_LHEX); // RFC2617 says algorithm is token. <">token<"> will also be accepted fieldTypes.put("algorithm", FIELD_TYPE_QUOTED_TOKEN); fieldTypes.put("cnonce", FIELD_TYPE_QUOTED_STRING); fieldTypes.put("opaque", FIELD_TYPE_QUOTED_STRING); // RFC2617 says qop is token. <">token<"> will also be accepted fieldTypes.put("qop", FIELD_TYPE_QUOTED_TOKEN); // RFC2617 says nc is 8LHEX. <">8LHEX<"> will also be accepted fieldTypes.put("nc", FIELD_TYPE_LHEX); // Setup the flag arrays for (int i = 0; i < 128; i++) { if (i < 32) { isToken[i] = false; } else if (i == '(' || i == ')' || i == '<' || i == '>' || i == '@' || i == ',' || i == ';' || i == ':' || i == '\\' || i == '\"' || i == '/' || i == '[' || i == ']' || i == '?' || i == '=' || i == '{' || i == '}' || i == ' ' || i == '\t') { isToken[i] = false; } else { isToken[i] = true; } if (i >= '0' && i <= '9' || i >= 'A' && i <= 'F' || i >= 'a' && i <= 'f') { isHex[i] = true; } else { isHex[i] = false; } } } /** * Parses an HTTP Authorization header for DIGEST authentication as per RFC * 2617 section 3.2.2. * * @param input The header value to parse * * @return A map of directives and values as {@link String}s or * <code>null</code> if a parsing error occurs. Although the * values returned are {@link String}s they will have been * validated to ensure that they conform to RFC 2617. * * @throws IllegalArgumentException If the header does not conform to RFC * 2617 * @throws IOException If an error occurs while reading the input */ public static Map<String,String> parseAuthorizationDigest ( StringReader input) throws IllegalArgumentException, IOException { Map<String,String> result = new HashMap<>(); if (skipConstant(input, "Digest") != SkipConstantResult.FOUND) { return null; } // All field names are valid tokens String field = readToken(input); if (field == null) { return null; } while (!field.equals("")) { if (skipConstant(input, "=") != SkipConstantResult.FOUND) { return null; } String value = null; Integer type = fieldTypes.get(field.toLowerCase(Locale.ENGLISH)); if (type == null) { // auth-param = token "=" ( token | quoted-string ) type = FIELD_TYPE_TOKEN_OR_QUOTED_STRING; } switch (type.intValue()) { case 0: // FIELD_TYPE_TOKEN value = readToken(input); break; case 1: // FIELD_TYPE_QUOTED_STRING value = readQuotedString(input, false); break; case 2: // FIELD_TYPE_TOKEN_OR_QUOTED_STRING value = readTokenOrQuotedString(input, false); break; case 3: // FIELD_TYPE_LHEX value = readLhex(input); break; case 4: // FIELD_TYPE_QUOTED_TOKEN value = readQuotedToken(input); break; default: // Error throw new IllegalArgumentException( "TODO i18n: Unsupported type"); } if (value == null) { return null; } result.put(field, value); if (skipConstant(input, ",") == SkipConstantResult.NOT_FOUND) { return null; } field = readToken(input); if (field == null) { return null; } } return result; } public static MediaType parseMediaType(StringReader input) throws IOException { // Type (required) String type = readToken(input); if (type == null || type.length() == 0) { return null; } if (skipConstant(input, "/") == SkipConstantResult.NOT_FOUND) { return null; } // Subtype (required) String subtype = readToken(input); if (subtype == null || subtype.length() == 0) { return null; } LinkedHashMap<String,String> parameters = new LinkedHashMap<>(); SkipConstantResult lookForSemiColon = skipConstant(input, ";"); if (lookForSemiColon == SkipConstantResult.NOT_FOUND) { return null; } while (lookForSemiColon == SkipConstantResult.FOUND) { String attribute = readToken(input); if (skipConstant(input, "=") == SkipConstantResult.FOUND) { String value = readTokenOrQuotedString(input, true); parameters.put(attribute.toLowerCase(Locale.ENGLISH), value); } else { parameters.put(attribute.toLowerCase(Locale.ENGLISH), ""); } lookForSemiColon = skipConstant(input, ";"); if (lookForSemiColon == SkipConstantResult.NOT_FOUND) { return null; } } return new MediaType(type, subtype, parameters); } public static String unquote(String input) { if (input == null || input.length() < 2 || input.charAt(0) != '"') { return input; } StringBuilder result = new StringBuilder(); for (int i = 1 ; i < (input.length() - 1); i++) { char c = input.charAt(i); if (input.charAt(i) == '\\') { i++; result.append(input.charAt(i)); } else { result.append(c); } } return result.toString(); } private static boolean isToken(int c) { // Fast for correct values, slower for incorrect ones try { return isToken[c]; } catch (ArrayIndexOutOfBoundsException ex) { return false; } } private static boolean isHex(int c) { // Fast for correct values, slower for incorrect ones try { return isHex[c]; } catch (ArrayIndexOutOfBoundsException ex) { return false; } } private static SkipConstantResult skipConstant(StringReader input, String constant) throws IOException { int len = constant.length(); int c = input.read(); // Skip lws while (c == 32 || c == 9) { c = input.read(); } for (int i = 0; i < len; i++) { if (i == 0 && c == -1) { return SkipConstantResult.EOF; } if (c != constant.charAt(i)) { input.skip(-(i + 1)); return SkipConstantResult.NOT_FOUND; } if (i != (len - 1)) { c = input.read(); } } return SkipConstantResult.FOUND; } /** * @return the token if one was found, the empty string if no data was * available to read or <code>null</code> if data other than a * token was found */ private static String readToken(StringReader input) throws IOException { StringBuilder result = new StringBuilder(); int c = input.read(); // Skip lws while (c == 32 || c == 9) { c = input.read(); } while (c != -1 && isToken(c)) { result.append((char) c); c = input.read(); } // Skip back so non-token character is available for next read input.skip(-1); if (c != -1 && result.length() == 0) { return null; } else { return result.toString(); } } /** * @return the quoted string if one was found, null if data other than a * quoted string was found or null if the end of data was reached * before the quoted string was terminated */ private static String readQuotedString(StringReader input, boolean returnQuoted) throws IOException { int c = input.read(); // Skip lws while (c == 32 || c == 9) { c = input.read(); } if (c != '"') { return null; } StringBuilder result = new StringBuilder(); if (returnQuoted) { result.append('\"'); } c = input.read(); while (c != '"') { if (c == -1) { return null; } else if (c == '\\') { c = input.read(); if (returnQuoted) { result.append('\\'); } result.append(c); } else { result.append((char) c); } c = input.read(); } if (returnQuoted) { result.append('\"'); } return result.toString(); } private static String readTokenOrQuotedString(StringReader input, boolean returnQuoted) throws IOException { // Use mark/reset as skip(-1) fails when reading the last character of // the input input.mark(1); int c = input.read(); // Go back so first character is available to be read again input.reset(); if (c == '"') { return readQuotedString(input, returnQuoted); } else { return readToken(input); } } /** * Token can be read unambiguously with or without surrounding quotes so * this parsing method for token permits optional surrounding double quotes. * This is not defined in any RFC. It is a special case to handle data from * buggy clients (known buggy clients for DIGEST auth include Microsoft IE 8 * &amp; 9, Apple Safari for OSX and iOS) that add quotes to values that * should be tokens. * * @return the token if one was found, null if data other than a token or * quoted token was found or null if the end of data was reached * before a quoted token was terminated */ private static String readQuotedToken(StringReader input) throws IOException { StringBuilder result = new StringBuilder(); boolean quoted = false; int c = input.read(); // Skip lws while (c == 32 || c == 9) { c = input.read(); } if (c == '"') { quoted = true; } else if (c == -1 || !isToken(c)) { return null; } else { result.append((char) c); } c = input.read(); while (c != -1 && isToken(c)) { result.append((char) c); c = input.read(); } if (quoted) { if (c != '"') { return null; } } else { // Skip back so non-token character is available for next read input.skip(-1); } if (c != -1 && result.length() == 0) { return null; } else { return result.toString(); } } /** * LHEX can be read unambiguously with or without surrounding quotes so this * parsing method for LHEX permits optional surrounding double quotes. Some * buggy clients (libwww-perl for DIGEST auth) are known to send quoted LHEX * when the specification requires just LHEX. * * <p> * LHEX are, literally, lower-case hexadecimal digits. This implementation * allows for upper-case digits as well, converting the returned value to * lower-case. * * @return the sequence of LHEX (minus any surrounding quotes) if any was * found, or <code>null</code> if data other LHEX was found */ private static String readLhex(StringReader input) throws IOException { StringBuilder result = new StringBuilder(); boolean quoted = false; int c = input.read(); // Skip lws while (c == 32 || c == 9) { c = input.read(); } if (c == '"') { quoted = true; } else if (c == -1 || !isHex(c)) { return null; } else { if ('A' <= c && c <= 'F') { c -= ('A' - 'a'); } result.append((char) c); } c = input.read(); while (c != -1 && isHex(c)) { if ('A' <= c && c <= 'F') { c -= ('A' - 'a'); } result.append((char) c); c = input.read(); } if (quoted) { if (c != '"') { return null; } } else { // Skip back so non-hex character is available for next read input.skip(-1); } if (c != -1 && result.length() == 0) { return null; } else { return result.toString(); } } private static enum SkipConstantResult { FOUND, NOT_FOUND, EOF } }
54,703
Bug 54703 Nullpointer exception in HttpParser.parseMediaType
input for parseMediaType() is ---------- multipart/signed; protocol="application/pkcs7-signature"; micalg=sha-256; boundary="----=_Part_121_929034657.1363355797756" ---------- exception trace java.lang.NullPointerException at org.apache.tomcat.util.http.parser.HttpParser.parseMediaType(HttpParser.java:215) at org.apache.tomcat.util.http.parser.MediaTypeCache.parse(MediaTypeCache.java:54) at org.apache.catalina.connector.Response.setContentType(Response.java:806) at org.apache.catalina.connector.Response.checkSpecialHeader(Response.java:1119) at org.apache.catalina.connector.Response.setHeader(Response.java:1446) at org.apache.catalina.connector.ResponseFacade.setHeader(ResponseFacade.java:535)
resolved fixed
7aeab0e
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-07T15:51:22Z
2013-03-15T17:53:20Z
test/org/apache/tomcat/util/http/parser/TestMediaType.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.http.parser; import java.io.IOException; import java.io.StringReader; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Assert; import org.junit.Test; /** * Unit tests for {@link HttpParser} focusing on media-type as defined in * section 3.7 of RFC 2616. */ public class TestMediaType { // Include whitespace to ensure Parser handles it correctly (it should be // skipped). private static final String TYPE = " foo "; private static final String SUBTYPE = " bar "; private static final String TYPES = TYPE + "/" + SUBTYPE; private static final Parameter PARAM_TOKEN = new Parameter("a", "b"); private static final Parameter PARAM_QUOTED = new Parameter("x", "\"y\""); private static final Parameter PARAM_EMPTY_QUOTED = new Parameter("z", "\"\""); private static final Parameter PARAM_COMPLEX_QUOTED = new Parameter("w", "\"foo'bar,a=b;x=y\""); private static final String CHARSET = "UTF-8"; private static final String WS_CHARSET = " \tUTF-8"; private static final String CHARSET_WS = "UTF-8 \t"; // Since this is quoted, it should retain the space at the end private static final String CHARSET_QUOTED = "\"" + CHARSET_WS + "\""; private static final Parameter PARAM_CHARSET = new Parameter("charset", CHARSET); private static final Parameter PARAM_WS_CHARSET = new Parameter("charset", WS_CHARSET); private static final Parameter PARAM_CHARSET_WS = new Parameter("charset", CHARSET_WS); private static final Parameter PARAM_CHARSET_QUOTED = new Parameter("charset", CHARSET_QUOTED); @Test public void testSimple() throws IOException { doTest(); } @Test public void testSimpleWithToken() throws IOException { doTest(PARAM_TOKEN); } @Test public void testSimpleWithQuotedString() throws IOException { doTest(PARAM_QUOTED); } @Test public void testSimpleWithEmptyQuotedString() throws IOException { doTest(PARAM_EMPTY_QUOTED); } @Test public void testSimpleWithComplesQuotedString() throws IOException { doTest(PARAM_COMPLEX_QUOTED); } @Test public void testSimpleWithCharset() throws IOException { doTest(PARAM_CHARSET); } @Test public void testSimpleWithCharsetWhitespaceBefore() throws IOException { doTest(PARAM_WS_CHARSET); } @Test public void testSimpleWithCharsetWhitespaceAfter() throws IOException { doTest(PARAM_CHARSET_WS); } @Test public void testSimpleWithCharsetQuoted() throws IOException { doTest(PARAM_CHARSET_QUOTED); } @Test public void testSimpleWithAll() throws IOException { doTest(PARAM_COMPLEX_QUOTED, PARAM_EMPTY_QUOTED, PARAM_QUOTED, PARAM_TOKEN, PARAM_CHARSET); } @Test public void testCharset() throws IOException { StringBuilder sb = new StringBuilder(); sb.append(TYPES); sb.append(PARAM_CHARSET); sb.append(PARAM_TOKEN); StringReader sr = new StringReader(sb.toString()); MediaType m = HttpParser.parseMediaType(sr); assertEquals("foo/bar; charset=UTF-8; a=b", m.toString()); assertEquals(CHARSET, m.getCharset()); assertEquals("foo/bar; a=b", m.toStringNoCharset()); } @Test public void testCharsetQuoted() throws IOException { StringBuilder sb = new StringBuilder(); sb.append(TYPES); sb.append(PARAM_CHARSET_QUOTED); StringReader sr = new StringReader(sb.toString()); MediaType m = HttpParser.parseMediaType(sr); assertEquals(CHARSET_WS, m.getCharset()); assertEquals(TYPES.replaceAll(" ", ""), m.toStringNoCharset()); } @Test public void testBug52811() throws IOException { String input = "multipart/related;boundary=1_4F50BD36_CDF8C28;" + "Start=\"<31671603.smil>\";" + "Type=\"application/smil;charset=UTF-8\""; StringReader sr = new StringReader(input); MediaType m = HttpParser.parseMediaType(sr); // Check the types assertEquals("multipart", m.getType()); assertEquals("related", m.getSubtype()); // Check the parameters assertTrue(m.getParameterCount() == 3); assertEquals("1_4F50BD36_CDF8C28", m.getParameterValue("boundary")); assertEquals("\"<31671603.smil>\"", m.getParameterValue("Start")); assertEquals("\"application/smil;charset=UTF-8\"", m.getParameterValue("Type")); String expected = "multipart/related; boundary=1_4F50BD36_CDF8C28; " + "start=\"<31671603.smil>\"; " + "type=\"application/smil;charset=UTF-8\""; assertEquals(expected, m.toString()); assertEquals(expected, m.toStringNoCharset()); assertNull(m.getCharset()); } @Test public void testBug53353() throws IOException { String input = "text/html; UTF-8;charset=UTF-8"; StringReader sr = new StringReader(input); MediaType m = HttpParser.parseMediaType(sr); // Check the types assertEquals("text", m.getType()); assertEquals("html", m.getSubtype()); // Check the parameters assertTrue(m.getParameterCount() == 2); assertEquals("", m.getParameterValue("UTF-8")); assertEquals("UTF-8", m.getCharset()); // Note: Invalid input is filtered out assertEquals("text/html; charset=UTF-8", m.toString()); assertEquals("UTF-8", m.getCharset()); } private void doTest(Parameter... parameters) throws IOException { StringBuilder sb = new StringBuilder(); sb.append(TYPES); for (Parameter p : parameters) { sb.append(p.toString()); } StringReader sr = new StringReader(sb.toString()); MediaType m = HttpParser.parseMediaType(sr); // Check all expected parameters are present assertTrue(m.getParameterCount() == parameters.length); // Check the types assertEquals(TYPE.trim(), m.getType()); assertEquals(SUBTYPE.trim(), m.getSubtype()); // Check the parameters for (int i = 0; i < parameters.length; i++) { assertEquals(parameters[i].getValue().trim(), m.getParameterValue(parameters[i].getName().trim())); } } private static class Parameter { private final String name; private final String value; public Parameter(String name,String value) { this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(";"); sb.append(name); sb.append("="); sb.append(value); return sb.toString(); } } @Test public void testCase() throws Exception { StringReader sr = new StringReader("type/sub-type;a=1;B=2"); MediaType m = HttpParser.parseMediaType(sr); Assert.assertEquals("1", m.getParameterValue("A")); Assert.assertEquals("1", m.getParameterValue("a")); Assert.assertEquals("2", m.getParameterValue("B")); Assert.assertEquals("2", m.getParameterValue("b")); } }
54,974
Bug 54974 SessionCookieConfig.setXXX methods must throw IllegalStateException when invoked after initialization phase
According to Servlet 3.0 javadoc javax.servlet.SessionCookieConfig setter methods must throw IllegalStateException when invoked after initialization phase setComment(String) setDomain(String) setHttpOnly(boolean) setMaxAge(int) setName(String) setPath(String) setSecure(boolean) " Throws: java.lang.IllegalStateException - if the ServletContext from which this SessionCookieConfig was acquired has already been initialized "
resolved fixed
41462ca
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-15T08:31:32Z
2013-05-15T12:13:20Z
java/org/apache/catalina/core/ApplicationContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestListener; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.LifecycleState; import org.apache.catalina.Service; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Connector; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.mapper.MappingData; import org.apache.catalina.util.ServerInfo; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.RequestUtil; import org.apache.tomcat.util.res.StringManager; /** * Standard implementation of <code>ServletContext</code> that represents * a web application's execution environment. An instance of this class is * associated with each instance of <code>StandardContext</code>. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class ApplicationContext implements ServletContext { protected static final boolean STRICT_SERVLET_COMPLIANCE; protected static final boolean GET_RESOURCE_REQUIRE_SLASH; static { STRICT_SERVLET_COMPLIANCE = Globals.STRICT_SERVLET_COMPLIANCE; String requireSlash = System.getProperty( "org.apache.catalina.core.ApplicationContext.GET_RESOURCE_REQUIRE_SLASH"); if (requireSlash == null) { GET_RESOURCE_REQUIRE_SLASH = STRICT_SERVLET_COMPLIANCE; } else { GET_RESOURCE_REQUIRE_SLASH = Boolean.valueOf(requireSlash).booleanValue(); } } // ----------------------------------------------------------- Constructors /** * Construct a new instance of this class, associated with the specified * Context instance. * * @param context The associated Context instance */ public ApplicationContext(StandardContext context) { super(); this.context = context; this.service = ((Engine) context.getParent().getParent()).getService(); // Populate session tracking modes populateSessionTrackingModes(); } // ----------------------------------------------------- Instance Variables /** * The context attributes for this context. */ protected Map<String,Object> attributes = new ConcurrentHashMap<>(); /** * List of read only attributes for this context. */ private final Map<String,String> readOnlyAttributes = new ConcurrentHashMap<>(); /** * The Context instance with which we are associated. */ private final StandardContext context; /** * The Service instance with which we are associated. */ private final Service service; /** * Empty String collection to serve as the basis for empty enumerations. */ private static final List<String> emptyString = Collections.emptyList(); /** * Empty Servlet collection to serve as the basis for empty enumerations. */ private static final List<Servlet> emptyServlet = Collections.emptyList(); /** * The facade around this object. */ private final ServletContext facade = new ApplicationContextFacade(this); /** * The merged context initialization parameters for this Context. */ private final ConcurrentHashMap<String,String> parameters = new ConcurrentHashMap<>(); /** * The string manager for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); /** * Thread local data used during request dispatch. */ private final ThreadLocal<DispatchData> dispatchData = new ThreadLocal<>(); /** * Session Cookie config */ private final SessionCookieConfig sessionCookieConfig = new ApplicationSessionCookieConfig(); /** * Session tracking modes */ private Set<SessionTrackingMode> sessionTrackingModes = null; private Set<SessionTrackingMode> defaultSessionTrackingModes = null; private Set<SessionTrackingMode> supportedSessionTrackingModes = null; /** * Flag that indicates if a new {@link ServletContextListener} may be added * to the application. Once the first {@link ServletContextListener} is * called, no more may be added. */ private boolean newServletContextListenerAllowed = true; // ------------------------------------------------- ServletContext Methods /** * Return the value of the specified context attribute, if any; * otherwise return <code>null</code>. * * @param name Name of the context attribute to return */ @Override public Object getAttribute(String name) { return (attributes.get(name)); } /** * Return an enumeration of the names of the context attributes * associated with this context. */ @Override public Enumeration<String> getAttributeNames() { Set<String> names = new HashSet<>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); } /** * Return a <code>ServletContext</code> object that corresponds to a * specified URI on the server. This method allows servlets to gain * access to the context for various parts of the server, and as needed * obtain <code>RequestDispatcher</code> objects or resources from the * context. The given path must be absolute (beginning with a "/"), * and is interpreted based on our virtual host's document root. * * @param uri Absolute URI of a resource on the server */ @Override public ServletContext getContext(String uri) { // Validate the format of the specified argument if ((uri == null) || (!uri.startsWith("/"))) return (null); Context child = null; try { Host host = (Host) context.getParent(); String mapuri = uri; while (true) { child = (Context) host.findChild(mapuri); if (child != null) break; int slash = mapuri.lastIndexOf('/'); if (slash < 0) break; mapuri = mapuri.substring(0, slash); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); } if (child == null) return (null); if (context.getCrossContext()) { // If crossContext is enabled, can always return the context return child.getServletContext(); } else if (child == context) { // Can still return the current context return context.getServletContext(); } else { // Nothing to return return (null); } } /** * Return the main path associated with this context. */ @Override public String getContextPath() { return context.getPath(); } /** * Return the value of the specified initialization parameter, or * <code>null</code> if this parameter does not exist. * * @param name Name of the initialization parameter to retrieve */ @Override public String getInitParameter(final String name) { return parameters.get(name); } /** * Return the names of the context's initialization parameters, or an * empty enumeration if the context has no initialization parameters. */ @Override public Enumeration<String> getInitParameterNames() { return Collections.enumeration(parameters.keySet()); } /** * Return the major version of the Java Servlet API that we implement. */ @Override public int getMajorVersion() { return (Constants.MAJOR_VERSION); } /** * Return the minor version of the Java Servlet API that we implement. */ @Override public int getMinorVersion() { return (Constants.MINOR_VERSION); } /** * Return the MIME type of the specified file, or <code>null</code> if * the MIME type cannot be determined. * * @param file Filename for which to identify a MIME type */ @Override public String getMimeType(String file) { if (file == null) return (null); int period = file.lastIndexOf("."); if (period < 0) return (null); String extension = file.substring(period + 1); if (extension.length() < 1) return (null); return (context.findMimeMapping(extension)); } /** * Return a <code>RequestDispatcher</code> object that acts as a * wrapper for the named servlet. * * @param name Name of the servlet for which a dispatcher is requested */ @Override public RequestDispatcher getNamedDispatcher(String name) { // Validate the name argument if (name == null) return (null); // Create and return a corresponding request dispatcher Wrapper wrapper = (Wrapper) context.findChild(name); if (wrapper == null) return (null); return new ApplicationDispatcher(wrapper, null, null, null, null, name); } /** * Return the real path for a given virtual path, if possible; otherwise * return <code>null</code>. * * @param path The path to the desired resource */ @Override public String getRealPath(String path) { return context.getRealPath(path); } /** * Return a <code>RequestDispatcher</code> instance that acts as a * wrapper for the resource at the given path. The path must begin * with a "/" and is interpreted as relative to the current context root. * * @param path The path to the desired resource. */ @Override public RequestDispatcher getRequestDispatcher(String path) { // Validate the path argument if (path == null) return (null); if (!path.startsWith("/")) throw new IllegalArgumentException (sm.getString ("applicationContext.requestDispatcher.iae", path)); // Get query string String queryString = null; String normalizedPath = path; int pos = normalizedPath.indexOf('?'); if (pos >= 0) { queryString = normalizedPath.substring(pos + 1); normalizedPath = normalizedPath.substring(0, pos); } normalizedPath = RequestUtil.normalize(normalizedPath); if (normalizedPath == null) return (null); pos = normalizedPath.length(); // Use the thread local URI and mapping data DispatchData dd = dispatchData.get(); if (dd == null) { dd = new DispatchData(); dispatchData.set(dd); } MessageBytes uriMB = dd.uriMB; uriMB.recycle(); // Use the thread local mapping data MappingData mappingData = dd.mappingData; // Map the URI CharChunk uriCC = uriMB.getCharChunk(); try { uriCC.append(context.getPath(), 0, context.getPath().length()); /* * Ignore any trailing path params (separated by ';') for mapping * purposes */ int semicolon = normalizedPath.indexOf(';'); if (pos >= 0 && semicolon > pos) { semicolon = -1; } uriCC.append(normalizedPath, 0, semicolon > 0 ? semicolon : pos); service.getMapper().map(context, uriMB, mappingData); if (mappingData.wrapper == null) { return (null); } /* * Append any trailing path params (separated by ';') that were * ignored for mapping purposes, so that they're reflected in the * RequestDispatcher's requestURI */ if (semicolon > 0) { uriCC.append(normalizedPath, semicolon, pos - semicolon); } } catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); } Wrapper wrapper = mappingData.wrapper; String wrapperPath = mappingData.wrapperPath.toString(); String pathInfo = mappingData.pathInfo.toString(); mappingData.recycle(); // Construct a RequestDispatcher to process this request return new ApplicationDispatcher (wrapper, uriCC.toString(), wrapperPath, pathInfo, queryString, null); } /** * Return the URL to the resource that is mapped to a specified path. * The path must begin with a "/" and is interpreted as relative to the * current context root. * * @param path The path to the desired resource * * @exception MalformedURLException if the path is not given * in the correct form */ @Override public URL getResource(String path) throws MalformedURLException { if (path == null || !path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) throw new MalformedURLException(sm.getString( "applicationContext.requestDispatcher.iae", path)); String normPath = RequestUtil.normalize(path); if (normPath == null) return (null); WebResourceRoot resources = context.getResources(); if (resources != null) { return resources.getResource(normPath).getURL(); } return null; } /** * Return the requested resource as an <code>InputStream</code>. The * path must be specified according to the rules described under * <code>getResource</code>. If no such resource can be identified, * return <code>null</code>. * * @param path The path to the desired resource. */ @Override public InputStream getResourceAsStream(String path) { if (path == null) return (null); if (!path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) return null; String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); WebResourceRoot resources = context.getResources(); if (resources != null) { return resources.getResource(normalizedPath).getInputStream(); } return null; } /** * Return a Set containing the resource paths of resources member of the * specified collection. Each path will be a String starting with * a "/" character. Paths representing directories will end with a "/" * character. The returned set is immutable. * * @param path Collection path */ @Override public Set<String> getResourcePaths(String path) { // Validate the path argument if (path == null) { return null; } if (!path.startsWith("/")) { throw new IllegalArgumentException (sm.getString("applicationContext.resourcePaths.iae", path)); } String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); WebResourceRoot resources = context.getResources(); if (resources != null) { return resources.listWebAppPaths(normalizedPath); } return null; } /** * Return the name and version of the servlet container. */ @Override public String getServerInfo() { return (ServerInfo.getServerInfo()); } /** * @deprecated As of Java Servlet API 2.1, with no direct replacement. */ @Override @Deprecated public Servlet getServlet(String name) { return (null); } /** * Return the display name of this web application. */ @Override public String getServletContextName() { return (context.getDisplayName()); } /** * @deprecated As of Java Servlet API 2.1, with no direct replacement. */ @Override @Deprecated public Enumeration<String> getServletNames() { return Collections.enumeration(emptyString); } /** * @deprecated As of Java Servlet API 2.1, with no direct replacement. */ @Override @Deprecated public Enumeration<Servlet> getServlets() { return Collections.enumeration(emptyServlet); } /** * Writes the specified message to a servlet log file. * * @param message Message to be written */ @Override public void log(String message) { context.getLogger().info(message); } /** * Writes the specified exception and message to a servlet log file. * * @param exception Exception to be reported * @param message Message to be written * * @deprecated As of Java Servlet API 2.1, use * <code>log(String, Throwable)</code> instead */ @Override @Deprecated public void log(Exception exception, String message) { context.getLogger().error(message, exception); } /** * Writes the specified message and exception to a servlet log file. * * @param message Message to be written * @param throwable Exception to be reported */ @Override public void log(String message, Throwable throwable) { context.getLogger().error(message, throwable); } /** * Remove the context attribute with the specified name, if any. * * @param name Name of the context attribute to be removed */ @Override public void removeAttribute(String name) { Object value = null; // Remove the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)){ return; } value = attributes.remove(name); if (value == null) { return; } // Notify interested application event listeners Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) return; ServletContextAttributeEvent event = new ServletContextAttributeEvent(context.getServletContext(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletContextAttributeListener)) continue; ServletContextAttributeListener listener = (ServletContextAttributeListener) listeners[i]; try { context.fireContainerEvent("beforeContextAttributeRemoved", listener); listener.attributeRemoved(event); context.fireContainerEvent("afterContextAttributeRemoved", listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); } } } /** * Bind the specified value with the specified context attribute name, * replacing any existing value for that name. * * @param name Attribute name to be bound * @param value New attribute value to be bound */ @Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) throw new IllegalArgumentException (sm.getString("applicationContext.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } Object oldValue = null; boolean replaced = false; // Add or replace the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)) return; oldValue = attributes.get(name); if (oldValue != null) replaced = true; attributes.put(name, value); // Notify interested application event listeners Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) return; ServletContextAttributeEvent event = null; if (replaced) event = new ServletContextAttributeEvent(context.getServletContext(), name, oldValue); else event = new ServletContextAttributeEvent(context.getServletContext(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletContextAttributeListener)) continue; ServletContextAttributeListener listener = (ServletContextAttributeListener) listeners[i]; try { if (replaced) { context.fireContainerEvent ("beforeContextAttributeReplaced", listener); listener.attributeReplaced(event); context.fireContainerEvent("afterContextAttributeReplaced", listener); } else { context.fireContainerEvent("beforeContextAttributeAdded", listener); listener.attributeAdded(event); context.fireContainerEvent("afterContextAttributeAdded", listener); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); } } } /** * Add filter to context. * @param filterName Name of filter to add * @param filterClass Name of filter class * @return <code>null</code> if the filter has already been fully defined, * else a {@link javax.servlet.FilterRegistration.Dynamic} object * that can be used to further configure the filter * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public FilterRegistration.Dynamic addFilter(String filterName, String filterClass) throws IllegalStateException { return addFilter(filterName, filterClass, null); } /** * Add filter to context. * @param filterName Name of filter to add * @param filter Filter to add * @return <code>null</code> if the filter has already been fully defined, * else a {@link javax.servlet.FilterRegistration.Dynamic} object * that can be used to further configure the filter * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) throws IllegalStateException { return addFilter(filterName, null, filter); } /** * Add filter to context. * @param filterName Name of filter to add * @param filterClass Class of filter to add * @return <code>null</code> if the filter has already been fully defined, * else a {@link javax.servlet.FilterRegistration.Dynamic} object * that can be used to further configure the filter * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) throws IllegalStateException { return addFilter(filterName, filterClass.getName(), null); } private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { if (filterName == null || filterName.equals("")) { throw new IllegalArgumentException(sm.getString( "applicationContext.invalidFilterName", filterName)); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addFilter.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. FilterDef filterDef = context.findFilterDef(filterName); // Assume a 'complete' FilterRegistration is one that has a class and // a name if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); context.addFilterDef(filterDef); } else { if (filterDef.getFilterName() != null && filterDef.getFilterClass() != null) { return null; } } if (filter == null) { filterDef.setFilterClass(filterClass); } else { filterDef.setFilterClass(filter.getClass().getName()); filterDef.setFilter(filter); } return new ApplicationFilterRegistration(filterDef, context); } @Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { try { T filter = (T) context.getInstanceManager().newInstance(c.getName()); return filter; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } } @Override public FilterRegistration getFilterRegistration(String filterName) { FilterDef filterDef = context.findFilterDef(filterName); if (filterDef == null) { return null; } return new ApplicationFilterRegistration(filterDef, context); } /** * Add servlet to context. * @param servletName Name of servlet to add * @param servletClass Name of servlet class * @return <code>null</code> if the servlet has already been fully defined, * else a {@link javax.servlet.ServletRegistration.Dynamic} object * that can be used to further configure the servlet * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public ServletRegistration.Dynamic addServlet(String servletName, String servletClass) throws IllegalStateException { return addServlet(servletName, servletClass, null); } /** * Add servlet to context. * @param servletName Name of servlet to add * @param servlet Servlet instance to add * @return <code>null</code> if the servlet has already been fully defined, * else a {@link javax.servlet.ServletRegistration.Dynamic} object * that can be used to further configure the servlet * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) throws IllegalStateException { return addServlet(servletName, null, servlet); } /** * Add servlet to context. * @param servletName Name of servlet to add * @param servletClass Class of servlet to add * @return <code>null</code> if the servlet has already been fully defined, * else a {@link javax.servlet.ServletRegistration.Dynamic} object * that can be used to further configure the servlet * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) throws IllegalStateException { return addServlet(servletName, servletClass.getName(), null); } private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet) throws IllegalStateException { if (servletName == null || servletName.equals("")) { throw new IllegalArgumentException(sm.getString( "applicationContext.invalidServletName", servletName)); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addServlet.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. Wrapper wrapper = (Wrapper) context.findChild(servletName); // Assume a 'complete' ServletRegistration is one that has a class and // a name if (wrapper == null) { wrapper = context.createWrapper(); wrapper.setName(servletName); context.addChild(wrapper); } else { if (wrapper.getName() != null && wrapper.getServletClass() != null) { if (wrapper.isOverridable()) { wrapper.setOverridable(false); } else { return null; } } } if (servlet == null) { wrapper.setServletClass(servletClass); } else { wrapper.setServletClass(servlet.getClass().getName()); wrapper.setServlet(servlet); } return context.dynamicServletAdded(wrapper); } @Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { try { T servlet = (T) context.getInstanceManager().newInstance(c.getName()); context.dynamicServletCreated(servlet); return servlet; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } } @Override public ServletRegistration getServletRegistration(String servletName) { Wrapper wrapper = (Wrapper) context.findChild(servletName); if (wrapper == null) { return null; } return new ApplicationServletRegistration(wrapper, context); } /** * By default {@link SessionTrackingMode#URL} is always supported, {@link * SessionTrackingMode#COOKIE} is supported unless the <code>cookies</code> * attribute has been set to <code>false</code> for the context and {@link * SessionTrackingMode#SSL} is supported if at least one of the connectors * used by this context has the attribute <code>secure</code> set to * <code>true</code>. */ @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { return defaultSessionTrackingModes; } private void populateSessionTrackingModes() { // URL re-writing is always enabled by default defaultSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL); supportedSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL); if (context.getCookies()) { defaultSessionTrackingModes.add(SessionTrackingMode.COOKIE); supportedSessionTrackingModes.add(SessionTrackingMode.COOKIE); } // SSL not enabled by default as it can only used on its own // Context > Host > Engine > Service Service s = ((Engine) context.getParent().getParent()).getService(); Connector[] connectors = s.findConnectors(); // Need at least one SSL enabled connector to use the SSL session ID. for (Connector connector : connectors) { if (Boolean.TRUE.equals(connector.getAttribute("SSLEnabled"))) { supportedSessionTrackingModes.add(SessionTrackingMode.SSL); break; } } } /** * Return the supplied value if one was previously set, else return the * defaults. */ @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { if (sessionTrackingModes != null) { return sessionTrackingModes; } return defaultSessionTrackingModes; } @Override public SessionCookieConfig getSessionCookieConfig() { return sessionCookieConfig; } /** * @throws IllegalStateException if the context has already been initialised * @throws IllegalArgumentException If SSL is requested in combination with * anything else or if an unsupported * tracking mode is requested */ @Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; } @Override public boolean setInitParameter(String name, String value) { return parameters.putIfAbsent(name, value) == null; } @Override public void addListener(Class<? extends EventListener> listenerClass) { EventListener listener; try { listener = createListener(listenerClass); } catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); } addListener(listener); } @Override public void addListener(String className) { try { Object obj = context.getInstanceManager().newInstance(className); if (!(obj instanceof EventListener)) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", className)); } EventListener listener = (EventListener) obj; addListener(listener); } catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } } @Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionIdListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } } @Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { T listener = (T) context.getInstanceManager().newInstance(c); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionIdListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } } @Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException( sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException( sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } } @Override public ClassLoader getClassLoader() { ClassLoader result = context.getLoader().getClassLoader(); if (Globals.IS_SECURITY_ENABLED) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); ClassLoader parent = result; while (parent != null) { if (parent == tccl) { break; } parent = parent.getParent(); } if (parent == null) { System.getSecurityManager().checkPermission( new RuntimePermission("getClassLoader")); } } return result; } @Override public int getEffectiveMajorVersion() { return context.getEffectiveMajorVersion(); } @Override public int getEffectiveMinorVersion() { return context.getEffectiveMinorVersion(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { Map<String, ApplicationFilterRegistration> result = new HashMap<>(); FilterDef[] filterDefs = context.findFilterDefs(); for (FilterDef filterDef : filterDefs) { result.put(filterDef.getFilterName(), new ApplicationFilterRegistration(filterDef, context)); } return result; } @Override public JspConfigDescriptor getJspConfigDescriptor() { return context.getJspConfigDescriptor(); } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { Map<String, ApplicationServletRegistration> result = new HashMap<>(); Container[] wrappers = context.findChildren(); for (Container wrapper : wrappers) { result.put(((Wrapper) wrapper).getName(), new ApplicationServletRegistration( (Wrapper) wrapper, context)); } return result; } @Override public String getVirtualServerName() { // Constructor will fail if context or its parent is null return ((Host) context.getParent()).getName(); } // -------------------------------------------------------- Package Methods protected StandardContext getContext() { return this.context; } /** * Clear all application-created attributes. */ protected void clearAttributes() { // Create list of attributes to be removed ArrayList<String> list = new ArrayList<>(); Iterator<String> iter = attributes.keySet().iterator(); while (iter.hasNext()) { list.add(iter.next()); } // Remove application originated attributes // (read only attributes will be left in place) Iterator<String> keys = list.iterator(); while (keys.hasNext()) { String key = keys.next(); removeAttribute(key); } } /** * Return the facade associated with this ApplicationContext. */ protected ServletContext getFacade() { return (this.facade); } /** * Set an attribute as read only. */ void setAttributeReadOnly(String name) { if (attributes.containsKey(name)) readOnlyAttributes.put(name, name); } protected void setNewServletContextListenerAllowed(boolean allowed) { this.newServletContextListenerAllowed = allowed; } /** * Internal class used as thread-local storage when doing path * mapping during dispatch. */ private static final class DispatchData { public MessageBytes uriMB; public MappingData mappingData; public DispatchData() { uriMB = MessageBytes.newInstance(); CharChunk uriCC = uriMB.getCharChunk(); uriCC.setLimit(-1); mappingData = new MappingData(); } } }
54,974
Bug 54974 SessionCookieConfig.setXXX methods must throw IllegalStateException when invoked after initialization phase
According to Servlet 3.0 javadoc javax.servlet.SessionCookieConfig setter methods must throw IllegalStateException when invoked after initialization phase setComment(String) setDomain(String) setHttpOnly(boolean) setMaxAge(int) setName(String) setPath(String) setSecure(boolean) " Throws: java.lang.IllegalStateException - if the ServletContext from which this SessionCookieConfig was acquired has already been initialized "
resolved fixed
41462ca
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-15T08:31:32Z
2013-05-15T12:13:20Z
java/org/apache/catalina/core/ApplicationSessionCookieConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import javax.servlet.SessionCookieConfig; import javax.servlet.http.Cookie; import org.apache.catalina.Context; import org.apache.catalina.util.SessionConfig; public class ApplicationSessionCookieConfig implements SessionCookieConfig { private boolean httpOnly; private boolean secure; private int maxAge = -1; private String comment; private String domain; private String name; private String path; @Override public String getComment() { return comment; } @Override public String getDomain() { return domain; } @Override public int getMaxAge() { return maxAge; } @Override public String getName() { return name; } @Override public String getPath() { return path; } @Override public boolean isHttpOnly() { return httpOnly; } @Override public boolean isSecure() { return secure; } @Override public void setComment(String comment) { this.comment = comment; } @Override public void setDomain(String domain) { this.domain = domain; } @Override public void setHttpOnly(boolean httpOnly) { this.httpOnly = httpOnly; } @Override public void setMaxAge(int maxAge) { this.maxAge = maxAge; } @Override public void setName(String name) { this.name = name; } @Override public void setPath(String path) { this.path = path; } @Override public void setSecure(boolean secure) { this.secure = secure; } /** * Creates a new session cookie for the given session ID * * @param context The Context for the web application * @param sessionId The ID of the session for which the cookie will be * created * @param secure Should session cookie be configured as secure */ public static Cookie createSessionCookie(Context context, String sessionId, boolean secure) { SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig(); // NOTE: The priority order for session cookie configuration is: // 1. Context level configuration // 2. Values from SessionCookieConfig // 3. Defaults Cookie cookie = new Cookie( SessionConfig.getSessionCookieName(context), sessionId); // Just apply the defaults. cookie.setMaxAge(scc.getMaxAge()); cookie.setComment(scc.getComment()); if (context.getSessionCookieDomain() == null) { // Avoid possible NPE if (scc.getDomain() != null) { cookie.setDomain(scc.getDomain()); } } else { cookie.setDomain(context.getSessionCookieDomain()); } // Always set secure if the request is secure if (scc.isSecure() || secure) { cookie.setSecure(true); } // Always set httpOnly if the context is configured for that if (scc.isHttpOnly() || context.getUseHttpOnly()) { cookie.setHttpOnly(true); } String contextPath = context.getSessionCookiePath(); if (contextPath == null || contextPath.length() == 0) { contextPath = scc.getPath(); } if (contextPath == null || contextPath.length() == 0) { contextPath = context.getEncodedPath(); } if (context.getSessionCookiePathUsesTrailingSlash()) { // Handle special case of ROOT context where cookies require a path of // '/' but the servlet spec uses an empty string // Also ensure the cookies for a context with a path of /foo don't get // sent for requests with a path of /foobar if (!contextPath.endsWith("/")) { contextPath = contextPath + "/"; } } else { // Only handle special case of ROOT context where cookies require a // path of '/' but the servlet spec uses an empty string if (contextPath.length() == 0) { contextPath = "/"; } } cookie.setPath(contextPath); return cookie; } }
54,974
Bug 54974 SessionCookieConfig.setXXX methods must throw IllegalStateException when invoked after initialization phase
According to Servlet 3.0 javadoc javax.servlet.SessionCookieConfig setter methods must throw IllegalStateException when invoked after initialization phase setComment(String) setDomain(String) setHttpOnly(boolean) setMaxAge(int) setName(String) setPath(String) setSecure(boolean) " Throws: java.lang.IllegalStateException - if the ServletContext from which this SessionCookieConfig was acquired has already been initialized "
resolved fixed
41462ca
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-15T08:31:32Z
2013-05-15T12:13:20Z
test/org/apache/catalina/core/TestApplicationSessionCookieConfig.java
54,981
Bug 54981 ServletContext.getJspConfigDescriptor() should return null when there is no jsp configuration
According to Servlet 3.0 javadoc ServletContext.getJspConfigDescriptor() must return NULL when there is no jsp configuration: " Returns: the <jsp-config> related configuration that was aggregated from the web.xml and web-fragment.xml descriptor files of the web application represented by this ServletContext, or null if no such configuration exists "
resolved fixed
aabef09
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-16T08:07:24Z
2013-05-16T13:13:20Z
java/org/apache/catalina/core/ApplicationContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.EnumSet; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestListener; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.LifecycleState; import org.apache.catalina.Service; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Connector; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.mapper.MappingData; import org.apache.catalina.util.ServerInfo; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.RequestUtil; import org.apache.tomcat.util.res.StringManager; /** * Standard implementation of <code>ServletContext</code> that represents * a web application's execution environment. An instance of this class is * associated with each instance of <code>StandardContext</code>. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class ApplicationContext implements ServletContext { protected static final boolean STRICT_SERVLET_COMPLIANCE; protected static final boolean GET_RESOURCE_REQUIRE_SLASH; static { STRICT_SERVLET_COMPLIANCE = Globals.STRICT_SERVLET_COMPLIANCE; String requireSlash = System.getProperty( "org.apache.catalina.core.ApplicationContext.GET_RESOURCE_REQUIRE_SLASH"); if (requireSlash == null) { GET_RESOURCE_REQUIRE_SLASH = STRICT_SERVLET_COMPLIANCE; } else { GET_RESOURCE_REQUIRE_SLASH = Boolean.valueOf(requireSlash).booleanValue(); } } // ----------------------------------------------------------- Constructors /** * Construct a new instance of this class, associated with the specified * Context instance. * * @param context The associated Context instance */ public ApplicationContext(StandardContext context) { super(); this.context = context; this.service = ((Engine) context.getParent().getParent()).getService(); this.sessionCookieConfig = new ApplicationSessionCookieConfig(context); // Populate session tracking modes populateSessionTrackingModes(); } // ----------------------------------------------------- Instance Variables /** * The context attributes for this context. */ protected Map<String,Object> attributes = new ConcurrentHashMap<>(); /** * List of read only attributes for this context. */ private final Map<String,String> readOnlyAttributes = new ConcurrentHashMap<>(); /** * The Context instance with which we are associated. */ private final StandardContext context; /** * The Service instance with which we are associated. */ private final Service service; /** * Empty String collection to serve as the basis for empty enumerations. */ private static final List<String> emptyString = Collections.emptyList(); /** * Empty Servlet collection to serve as the basis for empty enumerations. */ private static final List<Servlet> emptyServlet = Collections.emptyList(); /** * The facade around this object. */ private final ServletContext facade = new ApplicationContextFacade(this); /** * The merged context initialization parameters for this Context. */ private final ConcurrentHashMap<String,String> parameters = new ConcurrentHashMap<>(); /** * The string manager for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); /** * Thread local data used during request dispatch. */ private final ThreadLocal<DispatchData> dispatchData = new ThreadLocal<>(); /** * Session Cookie config */ private SessionCookieConfig sessionCookieConfig; /** * Session tracking modes */ private Set<SessionTrackingMode> sessionTrackingModes = null; private Set<SessionTrackingMode> defaultSessionTrackingModes = null; private Set<SessionTrackingMode> supportedSessionTrackingModes = null; /** * Flag that indicates if a new {@link ServletContextListener} may be added * to the application. Once the first {@link ServletContextListener} is * called, no more may be added. */ private boolean newServletContextListenerAllowed = true; // ------------------------------------------------- ServletContext Methods /** * Return the value of the specified context attribute, if any; * otherwise return <code>null</code>. * * @param name Name of the context attribute to return */ @Override public Object getAttribute(String name) { return (attributes.get(name)); } /** * Return an enumeration of the names of the context attributes * associated with this context. */ @Override public Enumeration<String> getAttributeNames() { Set<String> names = new HashSet<>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); } /** * Return a <code>ServletContext</code> object that corresponds to a * specified URI on the server. This method allows servlets to gain * access to the context for various parts of the server, and as needed * obtain <code>RequestDispatcher</code> objects or resources from the * context. The given path must be absolute (beginning with a "/"), * and is interpreted based on our virtual host's document root. * * @param uri Absolute URI of a resource on the server */ @Override public ServletContext getContext(String uri) { // Validate the format of the specified argument if ((uri == null) || (!uri.startsWith("/"))) return (null); Context child = null; try { Host host = (Host) context.getParent(); String mapuri = uri; while (true) { child = (Context) host.findChild(mapuri); if (child != null) break; int slash = mapuri.lastIndexOf('/'); if (slash < 0) break; mapuri = mapuri.substring(0, slash); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); } if (child == null) return (null); if (context.getCrossContext()) { // If crossContext is enabled, can always return the context return child.getServletContext(); } else if (child == context) { // Can still return the current context return context.getServletContext(); } else { // Nothing to return return (null); } } /** * Return the main path associated with this context. */ @Override public String getContextPath() { return context.getPath(); } /** * Return the value of the specified initialization parameter, or * <code>null</code> if this parameter does not exist. * * @param name Name of the initialization parameter to retrieve */ @Override public String getInitParameter(final String name) { return parameters.get(name); } /** * Return the names of the context's initialization parameters, or an * empty enumeration if the context has no initialization parameters. */ @Override public Enumeration<String> getInitParameterNames() { return Collections.enumeration(parameters.keySet()); } /** * Return the major version of the Java Servlet API that we implement. */ @Override public int getMajorVersion() { return (Constants.MAJOR_VERSION); } /** * Return the minor version of the Java Servlet API that we implement. */ @Override public int getMinorVersion() { return (Constants.MINOR_VERSION); } /** * Return the MIME type of the specified file, or <code>null</code> if * the MIME type cannot be determined. * * @param file Filename for which to identify a MIME type */ @Override public String getMimeType(String file) { if (file == null) return (null); int period = file.lastIndexOf("."); if (period < 0) return (null); String extension = file.substring(period + 1); if (extension.length() < 1) return (null); return (context.findMimeMapping(extension)); } /** * Return a <code>RequestDispatcher</code> object that acts as a * wrapper for the named servlet. * * @param name Name of the servlet for which a dispatcher is requested */ @Override public RequestDispatcher getNamedDispatcher(String name) { // Validate the name argument if (name == null) return (null); // Create and return a corresponding request dispatcher Wrapper wrapper = (Wrapper) context.findChild(name); if (wrapper == null) return (null); return new ApplicationDispatcher(wrapper, null, null, null, null, name); } /** * Return the real path for a given virtual path, if possible; otherwise * return <code>null</code>. * * @param path The path to the desired resource */ @Override public String getRealPath(String path) { return context.getRealPath(path); } /** * Return a <code>RequestDispatcher</code> instance that acts as a * wrapper for the resource at the given path. The path must begin * with a "/" and is interpreted as relative to the current context root. * * @param path The path to the desired resource. */ @Override public RequestDispatcher getRequestDispatcher(String path) { // Validate the path argument if (path == null) return (null); if (!path.startsWith("/")) throw new IllegalArgumentException (sm.getString ("applicationContext.requestDispatcher.iae", path)); // Get query string String queryString = null; String normalizedPath = path; int pos = normalizedPath.indexOf('?'); if (pos >= 0) { queryString = normalizedPath.substring(pos + 1); normalizedPath = normalizedPath.substring(0, pos); } normalizedPath = RequestUtil.normalize(normalizedPath); if (normalizedPath == null) return (null); pos = normalizedPath.length(); // Use the thread local URI and mapping data DispatchData dd = dispatchData.get(); if (dd == null) { dd = new DispatchData(); dispatchData.set(dd); } MessageBytes uriMB = dd.uriMB; uriMB.recycle(); // Use the thread local mapping data MappingData mappingData = dd.mappingData; // Map the URI CharChunk uriCC = uriMB.getCharChunk(); try { uriCC.append(context.getPath(), 0, context.getPath().length()); /* * Ignore any trailing path params (separated by ';') for mapping * purposes */ int semicolon = normalizedPath.indexOf(';'); if (pos >= 0 && semicolon > pos) { semicolon = -1; } uriCC.append(normalizedPath, 0, semicolon > 0 ? semicolon : pos); service.getMapper().map(context, uriMB, mappingData); if (mappingData.wrapper == null) { return (null); } /* * Append any trailing path params (separated by ';') that were * ignored for mapping purposes, so that they're reflected in the * RequestDispatcher's requestURI */ if (semicolon > 0) { uriCC.append(normalizedPath, semicolon, pos - semicolon); } } catch (Exception e) { // Should never happen log(sm.getString("applicationContext.mapping.error"), e); return (null); } Wrapper wrapper = mappingData.wrapper; String wrapperPath = mappingData.wrapperPath.toString(); String pathInfo = mappingData.pathInfo.toString(); mappingData.recycle(); // Construct a RequestDispatcher to process this request return new ApplicationDispatcher (wrapper, uriCC.toString(), wrapperPath, pathInfo, queryString, null); } /** * Return the URL to the resource that is mapped to a specified path. * The path must begin with a "/" and is interpreted as relative to the * current context root. * * @param path The path to the desired resource * * @exception MalformedURLException if the path is not given * in the correct form */ @Override public URL getResource(String path) throws MalformedURLException { if (path == null || !path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) throw new MalformedURLException(sm.getString( "applicationContext.requestDispatcher.iae", path)); String normPath = RequestUtil.normalize(path); if (normPath == null) return (null); WebResourceRoot resources = context.getResources(); if (resources != null) { return resources.getResource(normPath).getURL(); } return null; } /** * Return the requested resource as an <code>InputStream</code>. The * path must be specified according to the rules described under * <code>getResource</code>. If no such resource can be identified, * return <code>null</code>. * * @param path The path to the desired resource. */ @Override public InputStream getResourceAsStream(String path) { if (path == null) return (null); if (!path.startsWith("/") && GET_RESOURCE_REQUIRE_SLASH) return null; String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); WebResourceRoot resources = context.getResources(); if (resources != null) { return resources.getResource(normalizedPath).getInputStream(); } return null; } /** * Return a Set containing the resource paths of resources member of the * specified collection. Each path will be a String starting with * a "/" character. Paths representing directories will end with a "/" * character. The returned set is immutable. * * @param path Collection path */ @Override public Set<String> getResourcePaths(String path) { // Validate the path argument if (path == null) { return null; } if (!path.startsWith("/")) { throw new IllegalArgumentException (sm.getString("applicationContext.resourcePaths.iae", path)); } String normalizedPath = RequestUtil.normalize(path); if (normalizedPath == null) return (null); WebResourceRoot resources = context.getResources(); if (resources != null) { return resources.listWebAppPaths(normalizedPath); } return null; } /** * Return the name and version of the servlet container. */ @Override public String getServerInfo() { return (ServerInfo.getServerInfo()); } /** * @deprecated As of Java Servlet API 2.1, with no direct replacement. */ @Override @Deprecated public Servlet getServlet(String name) { return (null); } /** * Return the display name of this web application. */ @Override public String getServletContextName() { return (context.getDisplayName()); } /** * @deprecated As of Java Servlet API 2.1, with no direct replacement. */ @Override @Deprecated public Enumeration<String> getServletNames() { return Collections.enumeration(emptyString); } /** * @deprecated As of Java Servlet API 2.1, with no direct replacement. */ @Override @Deprecated public Enumeration<Servlet> getServlets() { return Collections.enumeration(emptyServlet); } /** * Writes the specified message to a servlet log file. * * @param message Message to be written */ @Override public void log(String message) { context.getLogger().info(message); } /** * Writes the specified exception and message to a servlet log file. * * @param exception Exception to be reported * @param message Message to be written * * @deprecated As of Java Servlet API 2.1, use * <code>log(String, Throwable)</code> instead */ @Override @Deprecated public void log(Exception exception, String message) { context.getLogger().error(message, exception); } /** * Writes the specified message and exception to a servlet log file. * * @param message Message to be written * @param throwable Exception to be reported */ @Override public void log(String message, Throwable throwable) { context.getLogger().error(message, throwable); } /** * Remove the context attribute with the specified name, if any. * * @param name Name of the context attribute to be removed */ @Override public void removeAttribute(String name) { Object value = null; // Remove the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)){ return; } value = attributes.remove(name); if (value == null) { return; } // Notify interested application event listeners Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) return; ServletContextAttributeEvent event = new ServletContextAttributeEvent(context.getServletContext(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletContextAttributeListener)) continue; ServletContextAttributeListener listener = (ServletContextAttributeListener) listeners[i]; try { context.fireContainerEvent("beforeContextAttributeRemoved", listener); listener.attributeRemoved(event); context.fireContainerEvent("afterContextAttributeRemoved", listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.fireContainerEvent("afterContextAttributeRemoved", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); } } } /** * Bind the specified value with the specified context attribute name, * replacing any existing value for that name. * * @param name Attribute name to be bound * @param value New attribute value to be bound */ @Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) throw new IllegalArgumentException (sm.getString("applicationContext.setAttribute.namenull")); // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } Object oldValue = null; boolean replaced = false; // Add or replace the specified attribute // Check for read only attribute if (readOnlyAttributes.containsKey(name)) return; oldValue = attributes.get(name); if (oldValue != null) replaced = true; attributes.put(name, value); // Notify interested application event listeners Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) return; ServletContextAttributeEvent event = null; if (replaced) event = new ServletContextAttributeEvent(context.getServletContext(), name, oldValue); else event = new ServletContextAttributeEvent(context.getServletContext(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletContextAttributeListener)) continue; ServletContextAttributeListener listener = (ServletContextAttributeListener) listeners[i]; try { if (replaced) { context.fireContainerEvent ("beforeContextAttributeReplaced", listener); listener.attributeReplaced(event); context.fireContainerEvent("afterContextAttributeReplaced", listener); } else { context.fireContainerEvent("beforeContextAttributeAdded", listener); listener.attributeAdded(event); context.fireContainerEvent("afterContextAttributeAdded", listener); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (replaced) context.fireContainerEvent("afterContextAttributeReplaced", listener); else context.fireContainerEvent("afterContextAttributeAdded", listener); // FIXME - should we do anything besides log these? log(sm.getString("applicationContext.attributeEvent"), t); } } } /** * Add filter to context. * @param filterName Name of filter to add * @param filterClass Name of filter class * @return <code>null</code> if the filter has already been fully defined, * else a {@link javax.servlet.FilterRegistration.Dynamic} object * that can be used to further configure the filter * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public FilterRegistration.Dynamic addFilter(String filterName, String filterClass) throws IllegalStateException { return addFilter(filterName, filterClass, null); } /** * Add filter to context. * @param filterName Name of filter to add * @param filter Filter to add * @return <code>null</code> if the filter has already been fully defined, * else a {@link javax.servlet.FilterRegistration.Dynamic} object * that can be used to further configure the filter * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public FilterRegistration.Dynamic addFilter(String filterName, Filter filter) throws IllegalStateException { return addFilter(filterName, null, filter); } /** * Add filter to context. * @param filterName Name of filter to add * @param filterClass Class of filter to add * @return <code>null</code> if the filter has already been fully defined, * else a {@link javax.servlet.FilterRegistration.Dynamic} object * that can be used to further configure the filter * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) throws IllegalStateException { return addFilter(filterName, filterClass.getName(), null); } private FilterRegistration.Dynamic addFilter(String filterName, String filterClass, Filter filter) throws IllegalStateException { if (filterName == null || filterName.equals("")) { throw new IllegalArgumentException(sm.getString( "applicationContext.invalidFilterName", filterName)); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addFilter.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. FilterDef filterDef = context.findFilterDef(filterName); // Assume a 'complete' FilterRegistration is one that has a class and // a name if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); context.addFilterDef(filterDef); } else { if (filterDef.getFilterName() != null && filterDef.getFilterClass() != null) { return null; } } if (filter == null) { filterDef.setFilterClass(filterClass); } else { filterDef.setFilterClass(filter.getClass().getName()); filterDef.setFilter(filter); } return new ApplicationFilterRegistration(filterDef, context); } @Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { try { T filter = (T) context.getInstanceManager().newInstance(c.getName()); return filter; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } } @Override public FilterRegistration getFilterRegistration(String filterName) { FilterDef filterDef = context.findFilterDef(filterName); if (filterDef == null) { return null; } return new ApplicationFilterRegistration(filterDef, context); } /** * Add servlet to context. * @param servletName Name of servlet to add * @param servletClass Name of servlet class * @return <code>null</code> if the servlet has already been fully defined, * else a {@link javax.servlet.ServletRegistration.Dynamic} object * that can be used to further configure the servlet * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public ServletRegistration.Dynamic addServlet(String servletName, String servletClass) throws IllegalStateException { return addServlet(servletName, servletClass, null); } /** * Add servlet to context. * @param servletName Name of servlet to add * @param servlet Servlet instance to add * @return <code>null</code> if the servlet has already been fully defined, * else a {@link javax.servlet.ServletRegistration.Dynamic} object * that can be used to further configure the servlet * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) throws IllegalStateException { return addServlet(servletName, null, servlet); } /** * Add servlet to context. * @param servletName Name of servlet to add * @param servletClass Class of servlet to add * @return <code>null</code> if the servlet has already been fully defined, * else a {@link javax.servlet.ServletRegistration.Dynamic} object * that can be used to further configure the servlet * @throws IllegalStateException if the context has already been initialised * @throws UnsupportedOperationException - if this context was passed to the * {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} * method of a {@link ServletContextListener} that was not declared * in web.xml, a web-fragment or annotated with * {@link javax.servlet.annotation.WebListener}. */ @Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) throws IllegalStateException { return addServlet(servletName, servletClass.getName(), null); } private ServletRegistration.Dynamic addServlet(String servletName, String servletClass, Servlet servlet) throws IllegalStateException { if (servletName == null || servletName.equals("")) { throw new IllegalArgumentException(sm.getString( "applicationContext.invalidServletName", servletName)); } if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addServlet.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. Wrapper wrapper = (Wrapper) context.findChild(servletName); // Assume a 'complete' ServletRegistration is one that has a class and // a name if (wrapper == null) { wrapper = context.createWrapper(); wrapper.setName(servletName); context.addChild(wrapper); } else { if (wrapper.getName() != null && wrapper.getServletClass() != null) { if (wrapper.isOverridable()) { wrapper.setOverridable(false); } else { return null; } } } if (servlet == null) { wrapper.setServletClass(servletClass); } else { wrapper.setServletClass(servlet.getClass().getName()); wrapper.setServlet(servlet); } return context.dynamicServletAdded(wrapper); } @Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { try { T servlet = (T) context.getInstanceManager().newInstance(c.getName()); context.dynamicServletCreated(servlet); return servlet; } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } catch (ClassNotFoundException e) { throw new ServletException(e); } } @Override public ServletRegistration getServletRegistration(String servletName) { Wrapper wrapper = (Wrapper) context.findChild(servletName); if (wrapper == null) { return null; } return new ApplicationServletRegistration(wrapper, context); } /** * By default {@link SessionTrackingMode#URL} is always supported, {@link * SessionTrackingMode#COOKIE} is supported unless the <code>cookies</code> * attribute has been set to <code>false</code> for the context and {@link * SessionTrackingMode#SSL} is supported if at least one of the connectors * used by this context has the attribute <code>secure</code> set to * <code>true</code>. */ @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { return defaultSessionTrackingModes; } private void populateSessionTrackingModes() { // URL re-writing is always enabled by default defaultSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL); supportedSessionTrackingModes = EnumSet.of(SessionTrackingMode.URL); if (context.getCookies()) { defaultSessionTrackingModes.add(SessionTrackingMode.COOKIE); supportedSessionTrackingModes.add(SessionTrackingMode.COOKIE); } // SSL not enabled by default as it can only used on its own // Context > Host > Engine > Service Service s = ((Engine) context.getParent().getParent()).getService(); Connector[] connectors = s.findConnectors(); // Need at least one SSL enabled connector to use the SSL session ID. for (Connector connector : connectors) { if (Boolean.TRUE.equals(connector.getAttribute("SSLEnabled"))) { supportedSessionTrackingModes.add(SessionTrackingMode.SSL); break; } } } /** * Return the supplied value if one was previously set, else return the * defaults. */ @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { if (sessionTrackingModes != null) { return sessionTrackingModes; } return defaultSessionTrackingModes; } @Override public SessionCookieConfig getSessionCookieConfig() { return sessionCookieConfig; } /** * @throws IllegalStateException if the context has already been initialised * @throws IllegalArgumentException If SSL is requested in combination with * anything else or if an unsupported * tracking mode is requested */ @Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.setSessionTracking.ise", getContextPath())); } // Check that only supported tracking modes have been requested for (SessionTrackingMode sessionTrackingMode : sessionTrackingModes) { if (!supportedSessionTrackingModes.contains(sessionTrackingMode)) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.invalid", sessionTrackingMode.toString(), getContextPath())); } } // Check SSL has not be configured with anything else if (sessionTrackingModes.contains(SessionTrackingMode.SSL)) { if (sessionTrackingModes.size() > 1) { throw new IllegalArgumentException(sm.getString( "applicationContext.setSessionTracking.iae.ssl", getContextPath())); } } this.sessionTrackingModes = sessionTrackingModes; } @Override public boolean setInitParameter(String name, String value) { return parameters.putIfAbsent(name, value) == null; } @Override public void addListener(Class<? extends EventListener> listenerClass) { EventListener listener; try { listener = createListener(listenerClass); } catch (ServletException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.init", listenerClass.getName()), e); } addListener(listener); } @Override public void addListener(String className) { try { Object obj = context.getInstanceManager().newInstance(className); if (!(obj instanceof EventListener)) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", className)); } EventListener listener = (EventListener) obj; addListener(listener); } catch (IllegalAccessException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (NamingException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (InstantiationException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } catch (ClassNotFoundException e) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.cnfe", className), e); } } @Override public <T extends EventListener> void addListener(T t) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { throw new IllegalStateException( sm.getString("applicationContext.addListener.ise", getContextPath())); } // TODO SERVLET3 // throw UnsupportedOperationException - if this context was passed to the // {@link ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)} // method of a {@link ServletContextListener} that was not declared // in web.xml, a web-fragment or annotated with // {@link javax.servlet.annotation.WebListener}. boolean match = false; if (t instanceof ServletContextAttributeListener || t instanceof ServletRequestListener || t instanceof ServletRequestAttributeListener || t instanceof HttpSessionIdListener || t instanceof HttpSessionAttributeListener) { context.addApplicationEventListener(t); match = true; } if (t instanceof HttpSessionListener || (t instanceof ServletContextListener && newServletContextListenerAllowed)) { context.addApplicationLifecycleListener(t); match = true; } if (match) return; if (t instanceof ServletContextListener) { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.sclNotAllowed", t.getClass().getName())); } else { throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", t.getClass().getName())); } } @Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { try { T listener = (T) context.getInstanceManager().newInstance(c); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || listener instanceof HttpSessionIdListener || listener instanceof HttpSessionAttributeListener) { return listener; } throw new IllegalArgumentException(sm.getString( "applicationContext.addListener.iae.wrongType", listener.getClass().getName())); } catch (IllegalAccessException e) { throw new ServletException(e); } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); throw new ServletException(e); } catch (NamingException e) { throw new ServletException(e); } catch (InstantiationException e) { throw new ServletException(e); } } @Override public void declareRoles(String... roleNames) { if (!context.getState().equals(LifecycleState.STARTING_PREP)) { //TODO Spec breaking enhancement to ignore this restriction throw new IllegalStateException( sm.getString("applicationContext.addRole.ise", getContextPath())); } if (roleNames == null) { throw new IllegalArgumentException( sm.getString("applicationContext.roles.iae", getContextPath())); } for (String role : roleNames) { if (role == null || "".equals(role)) { throw new IllegalArgumentException( sm.getString("applicationContext.role.iae", getContextPath())); } context.addSecurityRole(role); } } @Override public ClassLoader getClassLoader() { ClassLoader result = context.getLoader().getClassLoader(); if (Globals.IS_SECURITY_ENABLED) { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); ClassLoader parent = result; while (parent != null) { if (parent == tccl) { break; } parent = parent.getParent(); } if (parent == null) { System.getSecurityManager().checkPermission( new RuntimePermission("getClassLoader")); } } return result; } @Override public int getEffectiveMajorVersion() { return context.getEffectiveMajorVersion(); } @Override public int getEffectiveMinorVersion() { return context.getEffectiveMinorVersion(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { Map<String, ApplicationFilterRegistration> result = new HashMap<>(); FilterDef[] filterDefs = context.findFilterDefs(); for (FilterDef filterDef : filterDefs) { result.put(filterDef.getFilterName(), new ApplicationFilterRegistration(filterDef, context)); } return result; } @Override public JspConfigDescriptor getJspConfigDescriptor() { return context.getJspConfigDescriptor(); } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { Map<String, ApplicationServletRegistration> result = new HashMap<>(); Container[] wrappers = context.findChildren(); for (Container wrapper : wrappers) { result.put(((Wrapper) wrapper).getName(), new ApplicationServletRegistration( (Wrapper) wrapper, context)); } return result; } @Override public String getVirtualServerName() { // Constructor will fail if context or its parent is null return ((Host) context.getParent()).getName(); } // -------------------------------------------------------- Package Methods protected StandardContext getContext() { return this.context; } /** * Clear all application-created attributes. */ protected void clearAttributes() { // Create list of attributes to be removed ArrayList<String> list = new ArrayList<>(); Iterator<String> iter = attributes.keySet().iterator(); while (iter.hasNext()) { list.add(iter.next()); } // Remove application originated attributes // (read only attributes will be left in place) Iterator<String> keys = list.iterator(); while (keys.hasNext()) { String key = keys.next(); removeAttribute(key); } } /** * Return the facade associated with this ApplicationContext. */ protected ServletContext getFacade() { return (this.facade); } /** * Set an attribute as read only. */ void setAttributeReadOnly(String name) { if (attributes.containsKey(name)) readOnlyAttributes.put(name, name); } protected void setNewServletContextListenerAllowed(boolean allowed) { this.newServletContextListenerAllowed = allowed; } /** * Internal class used as thread-local storage when doing path * mapping during dispatch. */ private static final class DispatchData { public MessageBytes uriMB; public MappingData mappingData; public DispatchData() { uriMB = MessageBytes.newInstance(); CharChunk uriCC = uriMB.getCharChunk(); uriCC.setLimit(-1); mappingData = new MappingData(); } } }
54,981
Bug 54981 ServletContext.getJspConfigDescriptor() should return null when there is no jsp configuration
According to Servlet 3.0 javadoc ServletContext.getJspConfigDescriptor() must return NULL when there is no jsp configuration: " Returns: the <jsp-config> related configuration that was aggregated from the web.xml and web-fragment.xml descriptor files of the web application represented by this ServletContext, or null if no such configuration exists "
resolved fixed
aabef09
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-16T08:07:24Z
2013-05-16T13:13:20Z
test/org/apache/catalina/core/TestApplicationContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.File; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletResponse; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; public class TestApplicationContext extends TomcatBaseTest { @Test public void testBug53257() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); // app dir is relative to server home tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + "/test/bug53257/index.jsp"); String result = res.toString(); String[] lines = result.split("\n"); for (String line : lines) { if (line.startsWith("FAIL")) { Assert.fail(line); } } } @Test public void testBug53467() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); // app dir is relative to server home tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug53467].jsp", res, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); Assert.assertTrue(res.toString().contains("<p>OK</p>")); } @Test(expected = IllegalArgumentException.class) public void testAddFilterWithFilterNameNull() { getServletContext().addFilter(null, (Filter) null); } @Test(expected = IllegalArgumentException.class) public void testAddFilterWithFilterNameEmptyString() { getServletContext().addFilter("", (Filter) null); } @Test(expected = IllegalArgumentException.class) public void testAddServletWithServletNameNull() { getServletContext().addServlet(null, (Servlet) null); } @Test(expected = IllegalArgumentException.class) public void testAddServletWithServletNameEmptyString() { getServletContext().addServlet("", (Servlet) null); } private ServletContext getServletContext() { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); // app dir is relative to server home StandardContext standardContext = (StandardContext) tomcat.addWebapp( null, "/test", appDir.getAbsolutePath()); return standardContext.getServletContext(); } }
54,955
Bug 54955 Mapping to application context root returns 404 after reload
null
resolved fixed
cdbf6b0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-20T20:51:02Z
2013-05-13T07:26:40Z
java/org/apache/catalina/mapper/Mapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.mapper; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.tomcat.util.buf.Ascii; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.res.StringManager; /** * Mapper, which implements the servlet API mapping rules (which are derived * from the HTTP rules). * * @author Remy Maucherat */ public final class Mapper { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(Mapper.class); protected static final StringManager sm = StringManager.getManager(Mapper.class.getPackage().getName()); // ----------------------------------------------------- Instance Variables /** * Array containing the virtual hosts definitions. */ protected MappedHost[] hosts = new MappedHost[0]; /** * Default host name. */ protected String defaultHostName = null; /** * Mapping from Context object to Context version to support * RequestDispatcher mappings. */ protected Map<Context, ContextVersion> contextObjectToContextVersionMap = new ConcurrentHashMap<>(); // --------------------------------------------------------- Public Methods /** * Set default host. * * @param defaultHostName Default host name */ public void setDefaultHostName(String defaultHostName) { this.defaultHostName = defaultHostName; } /** * Add a new host to the mapper. * * @param name Virtual host name * @param host Host object */ public synchronized void addHost(String name, String[] aliases, Host host) { MappedHost[] newHosts = new MappedHost[hosts.length + 1]; MappedHost newHost = new MappedHost(); ContextList contextList = new ContextList(); newHost.name = name; newHost.contextList = contextList; newHost.object = host; if (insertMap(hosts, newHosts, newHost)) { hosts = newHosts; } for (int i = 0; i < aliases.length; i++) { newHosts = new MappedHost[hosts.length + 1]; newHost = new MappedHost(); newHost.name = aliases[i]; newHost.contextList = contextList; newHost.object = host; if (insertMap(hosts, newHosts, newHost)) { hosts = newHosts; } } } /** * Remove a host from the mapper. * * @param name Virtual host name */ public synchronized void removeHost(String name) { // Find and remove the old host int pos = find(hosts, name); if (pos < 0) { return; } Host host = hosts[pos].object; MappedHost[] newHosts = new MappedHost[hosts.length - 1]; if (removeMap(hosts, newHosts, name)) { hosts = newHosts; } // Remove all aliases (they will map to the same host object) for (int i = 0; i < newHosts.length; i++) { if (newHosts[i].object == host) { MappedHost[] newHosts2 = new MappedHost[hosts.length - 1]; if (removeMap(hosts, newHosts2, newHosts[i].name)) { hosts = newHosts2; } } } } /** * Add an alias to an existing host. * @param name The name of the host * @param alias The alias to add */ public synchronized void addHostAlias(String name, String alias) { int pos = find(hosts, name); if (pos < 0) { // Should not be adding an alias for a host that doesn't exist but // just in case... return; } MappedHost realHost = hosts[pos]; MappedHost[] newHosts = new MappedHost[hosts.length + 1]; MappedHost newHost = new MappedHost(); newHost.name = alias; newHost.contextList = realHost.contextList; newHost.object = realHost.object; if (insertMap(hosts, newHosts, newHost)) { hosts = newHosts; } } /** * Remove a host alias * @param alias The alias to remove */ public synchronized void removeHostAlias(String alias) { // Find and remove the alias int pos = find(hosts, alias); if (pos < 0) { return; } MappedHost[] newHosts = new MappedHost[hosts.length - 1]; if (removeMap(hosts, newHosts, alias)) { hosts = newHosts; } } /** * Add a new Context to an existing Host. * * @param hostName Virtual host name this context belongs to * @param host Host object * @param path Context path * @param version Context version * @param context Context object * @param welcomeResources Welcome files defined for this context * @param resources Static resources of the context */ public void addContextVersion(String hostName, Host host, String path, String version, Context context, String[] welcomeResources, WebResourceRoot resources) { MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if( pos <0 ) { addHost(hostName, new String[0], host); hosts = this.hosts; pos = find(hosts, hostName); } if (pos < 0) { log.error("No host found: " + hostName); } MappedHost mappedHost = hosts[pos]; if (mappedHost.name.equals(hostName)) { int slashCount = slashCount(path); synchronized (mappedHost) { MappedContext[] contexts = mappedHost.contextList.contexts; // Update nesting if (slashCount > mappedHost.contextList.nesting) { mappedHost.contextList.nesting = slashCount; } int pos2 = find(contexts, path); if (pos2 < 0 || !path.equals(contexts[pos2].name)) { MappedContext newContext = new MappedContext(); newContext.name = path; MappedContext[] newContexts = new MappedContext[contexts.length + 1]; if (insertMap(contexts, newContexts, newContext)) { mappedHost.contextList.contexts = newContexts; } pos2 = find(newContexts, path); } MappedContext mappedContext = mappedHost.contextList.contexts[pos2]; ContextVersion[] contextVersions = mappedContext.versions; ContextVersion[] newContextVersions = new ContextVersion[contextVersions.length + 1]; ContextVersion newContextVersion = new ContextVersion(); newContextVersion.path = path; newContextVersion.name = version; newContextVersion.object = context; newContextVersion.welcomeResources = welcomeResources; newContextVersion.resources = resources; if (insertMap(contextVersions, newContextVersions, newContextVersion)) { mappedContext.versions = newContextVersions; contextObjectToContextVersionMap.put( context, newContextVersion); } } } } /** * Remove a context from an existing host. * * @param ctxt The actual context * @param hostName Virtual host name this context belongs to * @param path Context path * @param version Context version */ public void removeContextVersion(Context ctxt, String hostName, String path, String version) { contextObjectToContextVersionMap.remove(ctxt); MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if (pos < 0) { return; } MappedHost host = hosts[pos]; if (host.name.equals(hostName)) { synchronized (host) { MappedContext[] contexts = host.contextList.contexts; if (contexts.length == 0 ){ return; } int pos2 = find(contexts, path); if (pos2 < 0 || !path.equals(contexts[pos2].name)) { return; } MappedContext context = contexts[pos2]; ContextVersion[] contextVersions = context.versions; ContextVersion[] newContextVersions = new ContextVersion[contextVersions.length - 1]; if (removeMap(contextVersions, newContextVersions, version)) { context.versions = newContextVersions; if (context.versions.length == 0) { // Remove the context MappedContext[] newContexts = new MappedContext[contexts.length -1]; if (removeMap(contexts, newContexts, path)) { host.contextList.contexts = newContexts; // Recalculate nesting host.contextList.nesting = 0; for (int i = 0; i < newContexts.length; i++) { int slashCount = slashCount(newContexts[i].name); if (slashCount > host.contextList.nesting) { host.contextList.nesting = slashCount; } } } } } } } } public void addWrapper(String hostName, String contextPath, String version, String path, Wrapper wrapper, boolean jspWildCard, boolean resourceOnly) { MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if (pos < 0) { return; } MappedHost host = hosts[pos]; if (host.name.equals(hostName)) { MappedContext[] contexts = host.contextList.contexts; int pos2 = find(contexts, contextPath); if (pos2 < 0) { log.error("No context found: " + contextPath ); return; } MappedContext context = contexts[pos2]; if (context.name.equals(contextPath)) { ContextVersion[] contextVersions = context.versions; int pos3 = find(contextVersions, version); if( pos3<0 ) { log.error("No context version found: " + contextPath + " " + version); return; } ContextVersion contextVersion = contextVersions[pos3]; if (contextVersion.name.equals(version)) { addWrapper(contextVersion, path, wrapper, jspWildCard, resourceOnly); } } } } /** * Adds a wrapper to the given context. * * @param context The context to which to add the wrapper * @param path Wrapper mapping * @param wrapper The Wrapper object * @param jspWildCard true if the wrapper corresponds to the JspServlet * @param resourceOnly true if this wrapper always expects a physical * resource to be present (such as a JSP) * and the mapping path contains a wildcard; false otherwise */ protected void addWrapper(ContextVersion context, String path, Wrapper wrapper, boolean jspWildCard, boolean resourceOnly) { synchronized (context) { MappedWrapper newWrapper = new MappedWrapper(); newWrapper.object = wrapper; newWrapper.jspWildCard = jspWildCard; newWrapper.resourceOnly = resourceOnly; if (path.endsWith("/*")) { // Wildcard wrapper newWrapper.name = path.substring(0, path.length() - 2); MappedWrapper[] oldWrappers = context.wildcardWrappers; MappedWrapper[] newWrappers = new MappedWrapper[oldWrappers.length + 1]; if (insertMap(oldWrappers, newWrappers, newWrapper)) { context.wildcardWrappers = newWrappers; int slashCount = slashCount(newWrapper.name); if (slashCount > context.nesting) { context.nesting = slashCount; } } } else if (path.startsWith("*.")) { // Extension wrapper newWrapper.name = path.substring(2); MappedWrapper[] oldWrappers = context.extensionWrappers; MappedWrapper[] newWrappers = new MappedWrapper[oldWrappers.length + 1]; if (insertMap(oldWrappers, newWrappers, newWrapper)) { context.extensionWrappers = newWrappers; } } else if (path.equals("/")) { // Default wrapper newWrapper.name = ""; context.defaultWrapper = newWrapper; } else { // Exact wrapper if (path.length() == 0) { // Special case for the Context Root mapping which is // treated as an exact match newWrapper.name = "/"; } else { newWrapper.name = path; } MappedWrapper[] oldWrappers = context.exactWrappers; MappedWrapper[] newWrappers = new MappedWrapper[oldWrappers.length + 1]; if (insertMap(oldWrappers, newWrappers, newWrapper)) { context.exactWrappers = newWrappers; } } } } /** * Remove a wrapper from an existing context. * * @param hostName Virtual host name this wrapper belongs to * @param contextPath Context path this wrapper belongs to * @param path Wrapper mapping */ public void removeWrapper (String hostName, String contextPath, String version, String path) { MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if (pos < 0) { return; } MappedHost host = hosts[pos]; if (host.name.equals(hostName)) { MappedContext[] contexts = host.contextList.contexts; int pos2 = find(contexts, contextPath); if (pos2 < 0) { return; } MappedContext context = contexts[pos2]; if (context.name.equals(contextPath)) { ContextVersion[] contextVersions = context.versions; int pos3 = find(contextVersions, version); if( pos3<0 ) { return; } ContextVersion contextVersion = contextVersions[pos3]; if (contextVersion.name.equals(version)) { removeWrapper(contextVersion, path); } } } } protected void removeWrapper(ContextVersion context, String path) { if (log.isDebugEnabled()) { log.debug(sm.getString("mapper.removeWrapper", context.name, path)); } synchronized (context) { if (path.endsWith("/*")) { // Wildcard wrapper String name = path.substring(0, path.length() - 2); MappedWrapper[] oldWrappers = context.wildcardWrappers; if (oldWrappers.length == 0) { return; } MappedWrapper[] newWrappers = new MappedWrapper[oldWrappers.length - 1]; if (removeMap(oldWrappers, newWrappers, name)) { // Recalculate nesting context.nesting = 0; for (int i = 0; i < newWrappers.length; i++) { int slashCount = slashCount(newWrappers[i].name); if (slashCount > context.nesting) { context.nesting = slashCount; } } context.wildcardWrappers = newWrappers; } } else if (path.startsWith("*.")) { // Extension wrapper String name = path.substring(2); MappedWrapper[] oldWrappers = context.extensionWrappers; if (oldWrappers.length == 0) { return; } MappedWrapper[] newWrappers = new MappedWrapper[oldWrappers.length - 1]; if (removeMap(oldWrappers, newWrappers, name)) { context.extensionWrappers = newWrappers; } } else if (path.equals("/")) { // Default wrapper context.defaultWrapper = null; } else { // Exact wrapper String name = path; MappedWrapper[] oldWrappers = context.exactWrappers; if (oldWrappers.length == 0) { return; } MappedWrapper[] newWrappers = new MappedWrapper[oldWrappers.length - 1]; if (removeMap(oldWrappers, newWrappers, name)) { context.exactWrappers = newWrappers; } } } } /** * Add a welcome file to the given context. * * @param hostName * @param contextPath * @param welcomeFile */ public void addWelcomeFile(String hostName, String contextPath, String version, String welcomeFile) { MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if (pos < 0) { return; } MappedHost host = hosts[pos]; if (host.name.equals(hostName)) { MappedContext[] contexts = host.contextList.contexts; int pos2 = find(contexts, contextPath); if (pos2 < 0) { log.error("No context found: " + contextPath ); return; } MappedContext context = contexts[pos2]; if (context.name.equals(contextPath)) { ContextVersion[] contextVersions = context.versions; int pos3 = find(contextVersions, version); if( pos3<0 ) { log.error("No context version found: " + contextPath + " " + version); return; } ContextVersion contextVersion = contextVersions[pos3]; if (contextVersion.name.equals(version)) { int len = contextVersion.welcomeResources.length + 1; String[] newWelcomeResources = new String[len]; System.arraycopy(contextVersion.welcomeResources, 0, newWelcomeResources, 0, len - 1); newWelcomeResources[len - 1] = welcomeFile; contextVersion.welcomeResources = newWelcomeResources; } } } } /** * Remove a welcome file from the given context. * * @param hostName * @param contextPath * @param welcomeFile */ public void removeWelcomeFile(String hostName, String contextPath, String version, String welcomeFile) { MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if (pos < 0) { return; } MappedHost host = hosts[pos]; if (host.name.equals(hostName)) { MappedContext[] contexts = host.contextList.contexts; int pos2 = find(contexts, contextPath); if (pos2 < 0) { log.error("No context found: " + contextPath ); return; } MappedContext context = contexts[pos2]; if (context.name.equals(contextPath)) { ContextVersion[] contextVersions = context.versions; int pos3 = find(contextVersions, version); if( pos3<0 ) { log.error("No context version found: " + contextPath + " " + version); return; } ContextVersion contextVersion = contextVersions[pos3]; if (contextVersion.name.equals(version)) { int match = -1; for (int i = 0; i < contextVersion.welcomeResources.length; i++) { if (welcomeFile.equals(contextVersion.welcomeResources[i])) { match = i; break; } } if (match > -1) { int len = contextVersion.welcomeResources.length - 1; String[] newWelcomeResources = new String[len]; System.arraycopy(contextVersion.welcomeResources, 0, newWelcomeResources, 0, match); if (match < len) { System.arraycopy(contextVersion.welcomeResources, match + 1, newWelcomeResources, match, len - match); } contextVersion.welcomeResources = newWelcomeResources; } } } } } /** * Clear the welcome files for the given context. * * @param hostName * @param contextPath */ public void clearWelcomeFiles(String hostName, String contextPath, String version) { MappedHost[] hosts = this.hosts; int pos = find(hosts, hostName); if (pos < 0) { return; } MappedHost host = hosts[pos]; if (host.name.equals(hostName)) { MappedContext[] contexts = host.contextList.contexts; int pos2 = find(contexts, contextPath); if (pos2 < 0) { log.error("No context found: " + contextPath ); return; } MappedContext context = contexts[pos2]; if (context.name.equals(contextPath)) { ContextVersion[] contextVersions = context.versions; int pos3 = find(contextVersions, version); if( pos3<0 ) { log.error("No context version found: " + contextPath + " " + version); return; } ContextVersion contextVersion = contextVersions[pos3]; if (contextVersion.name.equals(version)) { contextVersion.welcomeResources = new String[0]; } } } } /** * Map the specified host name and URI, mutating the given mapping data. * * @param host Virtual host name * @param uri URI * @param mappingData This structure will contain the result of the mapping * operation */ public void map(MessageBytes host, MessageBytes uri, String version, MappingData mappingData) throws Exception { if (host.isNull()) { host.getCharChunk().append(defaultHostName); } host.toChars(); uri.toChars(); internalMap(host.getCharChunk(), uri.getCharChunk(), version, mappingData); } /** * Map the specified URI relative to the context, * mutating the given mapping data. * * @param context The actual context * @param uri URI * @param mappingData This structure will contain the result of the mapping * operation */ public void map(Context context, MessageBytes uri, MappingData mappingData) throws Exception { ContextVersion contextVersion = contextObjectToContextVersionMap.get(context); uri.toChars(); CharChunk uricc = uri.getCharChunk(); uricc.setLimit(-1); internalMapWrapper(contextVersion, uricc, mappingData); } // -------------------------------------------------------- Private Methods /** * Map the specified URI. */ private final void internalMap(CharChunk host, CharChunk uri, String version, MappingData mappingData) throws Exception { uri.setLimit(-1); MappedContext[] contexts = null; MappedContext context = null; ContextVersion contextVersion = null; int nesting = 0; // Virtual host mapping if (mappingData.host == null) { MappedHost[] hosts = this.hosts; int pos = findIgnoreCase(hosts, host); if ((pos != -1) && (host.equalsIgnoreCase(hosts[pos].name))) { mappingData.host = hosts[pos].object; contexts = hosts[pos].contextList.contexts; nesting = hosts[pos].contextList.nesting; } else { if (defaultHostName == null) { return; } pos = find(hosts, defaultHostName); if ((pos != -1) && (defaultHostName.equals(hosts[pos].name))) { mappingData.host = hosts[pos].object; contexts = hosts[pos].contextList.contexts; nesting = hosts[pos].contextList.nesting; } else { return; } } } // Context mapping if (mappingData.context == null && contexts != null) { int pos = find(contexts, uri); if (pos == -1) { return; } int lastSlash = -1; int uriEnd = uri.getEnd(); int length = -1; boolean found = false; while (pos >= 0) { if (uri.startsWith(contexts[pos].name)) { length = contexts[pos].name.length(); if (uri.getLength() == length) { found = true; break; } else if (uri.startsWithIgnoreCase("/", length)) { found = true; break; } } if (lastSlash == -1) { lastSlash = nthSlash(uri, nesting + 1); } else { lastSlash = lastSlash(uri); } uri.setEnd(lastSlash); pos = find(contexts, uri); } uri.setEnd(uriEnd); if (!found) { if (contexts[0].name.equals("")) { context = contexts[0]; } } else { context = contexts[pos]; } if (context != null) { mappingData.contextPath.setString(context.name); } } if (context != null) { ContextVersion[] contextVersions = context.versions; int versionCount = contextVersions.length; if (versionCount > 1) { Context[] contextObjects = new Context[contextVersions.length]; for (int i = 0; i < contextObjects.length; i++) { contextObjects[i] = contextVersions[i].object; } mappingData.contexts = contextObjects; } if (version == null) { // Return the latest version contextVersion = contextVersions[versionCount - 1]; } else { int pos = find(contextVersions, version); if (pos < 0 || !contextVersions[pos].name.equals(version)) { // Return the latest version contextVersion = contextVersions[versionCount - 1]; } else { contextVersion = contextVersions[pos]; } } mappingData.context = contextVersion.object; } // Wrapper mapping if ((contextVersion != null) && (mappingData.wrapper == null)) { internalMapWrapper(contextVersion, uri, mappingData); } } /** * Wrapper mapping. */ private final void internalMapWrapper(ContextVersion contextVersion, CharChunk path, MappingData mappingData) throws Exception { int pathOffset = path.getOffset(); int pathEnd = path.getEnd(); int servletPath = pathOffset; boolean noServletPath = false; int length = contextVersion.path.length(); if (length != (pathEnd - pathOffset)) { servletPath = pathOffset + length; } else { noServletPath = true; path.append('/'); pathOffset = path.getOffset(); pathEnd = path.getEnd(); servletPath = pathOffset+length; } path.setOffset(servletPath); // Rule 1 -- Exact Match MappedWrapper[] exactWrappers = contextVersion.exactWrappers; internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 2 -- Prefix Match boolean checkJspWelcomeFiles = false; MappedWrapper[] wildcardWrappers = contextVersion.wildcardWrappers; if (mappingData.wrapper == null) { internalMapWildcardWrapper(wildcardWrappers, contextVersion.nesting, path, mappingData); if (mappingData.wrapper != null && mappingData.jspWildCard) { char[] buf = path.getBuffer(); if (buf[pathEnd - 1] == '/') { /* * Path ending in '/' was mapped to JSP servlet based on * wildcard match (e.g., as specified in url-pattern of a * jsp-property-group. * Force the context's welcome files, which are interpreted * as JSP files (since they match the url-pattern), to be * considered. See Bugzilla 27664. */ mappingData.wrapper = null; checkJspWelcomeFiles = true; } else { // See Bugzilla 27704 mappingData.wrapperPath.setChars(buf, path.getStart(), path.getLength()); mappingData.pathInfo.recycle(); } } } if(mappingData.wrapper == null && noServletPath) { // The path is empty, redirect to "/" mappingData.redirectPath.setChars (path.getBuffer(), pathOffset, pathEnd-pathOffset); path.setEnd(pathEnd - 1); return; } // Rule 3 -- Extension Match MappedWrapper[] extensionWrappers = contextVersion.extensionWrappers; if (mappingData.wrapper == null && !checkJspWelcomeFiles) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); } // Rule 4 -- Welcome resources processing for servlets if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); // Rule 4a -- Welcome resources processing for exact macth internalMapExactWrapper(exactWrappers, path, mappingData); // Rule 4b -- Welcome resources processing for prefix match if (mappingData.wrapper == null) { internalMapWildcardWrapper (wildcardWrappers, contextVersion.nesting, path, mappingData); } // Rule 4c -- Welcome resources processing // for physical folder if (mappingData.wrapper == null && contextVersion.resources != null) { String pathStr = path.toString(); WebResource file = contextVersion.resources.getResource(pathStr); if (file != null && file.isFile()) { internalMapExtensionWrapper(extensionWrappers, path, mappingData, true); if (mappingData.wrapper == null && contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } } path.setOffset(servletPath); path.setEnd(pathEnd); } } /* welcome file processing - take 2 * Now that we have looked for welcome files with a physical * backing, now look for an extension mapping listed * but may not have a physical backing to it. This is for * the case of index.jsf, index.do, etc. * A watered down version of rule 4 */ if (mappingData.wrapper == null) { boolean checkWelcomeFiles = checkJspWelcomeFiles; if (!checkWelcomeFiles) { char[] buf = path.getBuffer(); checkWelcomeFiles = (buf[pathEnd - 1] == '/'); } if (checkWelcomeFiles) { for (int i = 0; (i < contextVersion.welcomeResources.length) && (mappingData.wrapper == null); i++) { path.setOffset(pathOffset); path.setEnd(pathEnd); path.append(contextVersion.welcomeResources[i], 0, contextVersion.welcomeResources[i].length()); path.setOffset(servletPath); internalMapExtensionWrapper(extensionWrappers, path, mappingData, false); } path.setOffset(servletPath); path.setEnd(pathEnd); } } // Rule 7 -- Default servlet if (mappingData.wrapper == null && !checkJspWelcomeFiles) { if (contextVersion.defaultWrapper != null) { mappingData.wrapper = contextVersion.defaultWrapper.object; mappingData.requestPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); mappingData.wrapperPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); } // Redirection to a folder char[] buf = path.getBuffer(); if (contextVersion.resources != null && buf[pathEnd -1 ] != '/') { String pathStr = path.toString(); WebResource file = contextVersion.resources.getResource(pathStr); if (file != null && file.isDirectory()) { // Note: this mutates the path: do not do any processing // after this (since we set the redirectPath, there // shouldn't be any) path.setOffset(pathOffset); path.append('/'); mappingData.redirectPath.setChars (path.getBuffer(), path.getStart(), path.getLength()); } else { mappingData.requestPath.setString(pathStr); mappingData.wrapperPath.setString(pathStr); } } } path.setOffset(pathOffset); path.setEnd(pathEnd); } /** * Exact mapping. */ private final void internalMapExactWrapper (MappedWrapper[] wrappers, CharChunk path, MappingData mappingData) { int pos = find(wrappers, path); if ((pos != -1) && (path.equals(wrappers[pos].name))) { mappingData.requestPath.setString(wrappers[pos].name); mappingData.wrapper = wrappers[pos].object; if (path.equals("/")) { // Special handling for Context Root mapped servlet mappingData.pathInfo.setString("/"); mappingData.wrapperPath.setString(""); // This seems wrong but it is what the spec says... mappingData.contextPath.setString(""); } else { mappingData.wrapperPath.setString(wrappers[pos].name); } } } /** * Wildcard mapping. */ private final void internalMapWildcardWrapper (MappedWrapper[] wrappers, int nesting, CharChunk path, MappingData mappingData) { int pathEnd = path.getEnd(); int lastSlash = -1; int length = -1; int pos = find(wrappers, path); if (pos != -1) { boolean found = false; while (pos >= 0) { if (path.startsWith(wrappers[pos].name)) { length = wrappers[pos].name.length(); if (path.getLength() == length) { found = true; break; } else if (path.startsWithIgnoreCase("/", length)) { found = true; break; } } if (lastSlash == -1) { lastSlash = nthSlash(path, nesting + 1); } else { lastSlash = lastSlash(path); } path.setEnd(lastSlash); pos = find(wrappers, path); } path.setEnd(pathEnd); if (found) { mappingData.wrapperPath.setString(wrappers[pos].name); if (path.getLength() > length) { mappingData.pathInfo.setChars (path.getBuffer(), path.getOffset() + length, path.getLength() - length); } mappingData.requestPath.setChars (path.getBuffer(), path.getOffset(), path.getLength()); mappingData.wrapper = wrappers[pos].object; mappingData.jspWildCard = wrappers[pos].jspWildCard; } } } /** * Extension mappings. * * @param wrappers Set of wrappers to check for matches * @param path Path to map * @param mappingData Mapping data for result * @param resourceExpected Is this mapping expecting to find a resource */ private final void internalMapExtensionWrapper(MappedWrapper[] wrappers, CharChunk path, MappingData mappingData, boolean resourceExpected) { char[] buf = path.getBuffer(); int pathEnd = path.getEnd(); int servletPath = path.getOffset(); int slash = -1; for (int i = pathEnd - 1; i >= servletPath; i--) { if (buf[i] == '/') { slash = i; break; } } if (slash >= 0) { int period = -1; for (int i = pathEnd - 1; i > slash; i--) { if (buf[i] == '.') { period = i; break; } } if (period >= 0) { path.setOffset(period + 1); path.setEnd(pathEnd); int pos = find(wrappers, path); if ((pos != -1) && (path.equals(wrappers[pos].name)) && (resourceExpected || !wrappers[pos].resourceOnly)) { mappingData.wrapperPath.setChars (buf, servletPath, pathEnd - servletPath); mappingData.requestPath.setChars (buf, servletPath, pathEnd - servletPath); mappingData.wrapper = wrappers[pos].object; } path.setOffset(servletPath); path.setEnd(pathEnd); } } } /** * Find a map element given its name in a sorted array of map elements. * This will return the index for the closest inferior or equal item in the * given array. */ private static final <T> int find(MapElement<T>[] map, CharChunk name) { return find(map, name, name.getStart(), name.getEnd()); } /** * Find a map element given its name in a sorted array of map elements. * This will return the index for the closest inferior or equal item in the * given array. */ private static final <T> int find(MapElement<T>[] map, CharChunk name, int start, int end) { int a = 0; int b = map.length - 1; // Special cases: -1 and 0 if (b == -1) { return -1; } if (compare(name, start, end, map[0].name) < 0 ) { return -1; } if (b == 0) { return 0; } int i = 0; while (true) { i = (b + a) / 2; int result = compare(name, start, end, map[i].name); if (result == 1) { a = i; } else if (result == 0) { return i; } else { b = i; } if ((b - a) == 1) { int result2 = compare(name, start, end, map[b].name); if (result2 < 0) { return a; } else { return b; } } } } /** * Find a map element given its name in a sorted array of map elements. * This will return the index for the closest inferior or equal item in the * given array. */ private static final <T> int findIgnoreCase(MapElement<T>[] map, CharChunk name) { return findIgnoreCase(map, name, name.getStart(), name.getEnd()); } /** * Find a map element given its name in a sorted array of map elements. * This will return the index for the closest inferior or equal item in the * given array. */ private static final <T> int findIgnoreCase(MapElement<T>[] map, CharChunk name, int start, int end) { int a = 0; int b = map.length - 1; // Special cases: -1 and 0 if (b == -1) { return -1; } if (compareIgnoreCase(name, start, end, map[0].name) < 0 ) { return -1; } if (b == 0) { return 0; } int i = 0; while (true) { i = (b + a) / 2; int result = compareIgnoreCase(name, start, end, map[i].name); if (result == 1) { a = i; } else if (result == 0) { return i; } else { b = i; } if ((b - a) == 1) { int result2 = compareIgnoreCase(name, start, end, map[b].name); if (result2 < 0) { return a; } else { return b; } } } } /** * Find a map element given its name in a sorted array of map elements. * This will return the index for the closest inferior or equal item in the * given array. */ private static final <T> int find(MapElement<T>[] map, String name) { int a = 0; int b = map.length - 1; // Special cases: -1 and 0 if (b == -1) { return -1; } if (name.compareTo(map[0].name) < 0) { return -1; } if (b == 0) { return 0; } int i = 0; while (true) { i = (b + a) / 2; int result = name.compareTo(map[i].name); if (result > 0) { a = i; } else if (result == 0) { return i; } else { b = i; } if ((b - a) == 1) { int result2 = name.compareTo(map[b].name); if (result2 < 0) { return a; } else { return b; } } } } /** * Compare given char chunk with String. * Return -1, 0 or +1 if inferior, equal, or superior to the String. */ private static final int compare(CharChunk name, int start, int end, String compareTo) { int result = 0; char[] c = name.getBuffer(); int len = compareTo.length(); if ((end - start) < len) { len = end - start; } for (int i = 0; (i < len) && (result == 0); i++) { if (c[i + start] > compareTo.charAt(i)) { result = 1; } else if (c[i + start] < compareTo.charAt(i)) { result = -1; } } if (result == 0) { if (compareTo.length() > (end - start)) { result = -1; } else if (compareTo.length() < (end - start)) { result = 1; } } return result; } /** * Compare given char chunk with String ignoring case. * Return -1, 0 or +1 if inferior, equal, or superior to the String. */ private static final int compareIgnoreCase(CharChunk name, int start, int end, String compareTo) { int result = 0; char[] c = name.getBuffer(); int len = compareTo.length(); if ((end - start) < len) { len = end - start; } for (int i = 0; (i < len) && (result == 0); i++) { if (Ascii.toLower(c[i + start]) > Ascii.toLower(compareTo.charAt(i))) { result = 1; } else if (Ascii.toLower(c[i + start]) < Ascii.toLower(compareTo.charAt(i))) { result = -1; } } if (result == 0) { if (compareTo.length() > (end - start)) { result = -1; } else if (compareTo.length() < (end - start)) { result = 1; } } return result; } /** * Find the position of the last slash in the given char chunk. */ private static final int lastSlash(CharChunk name) { char[] c = name.getBuffer(); int end = name.getEnd(); int start = name.getStart(); int pos = end; while (pos > start) { if (c[--pos] == '/') { break; } } return (pos); } /** * Find the position of the nth slash, in the given char chunk. */ private static final int nthSlash(CharChunk name, int n) { char[] c = name.getBuffer(); int end = name.getEnd(); int start = name.getStart(); int pos = start; int count = 0; while (pos < end) { if ((c[pos++] == '/') && ((++count) == n)) { pos--; break; } } return (pos); } /** * Return the slash count in a given string. */ private static final int slashCount(String name) { int pos = -1; int count = 0; while ((pos = name.indexOf('/', pos + 1)) != -1) { count++; } return count; } /** * Insert into the right place in a sorted MapElement array, and prevent * duplicates. */ private static final <T> boolean insertMap (MapElement<T>[] oldMap, MapElement<T>[] newMap, MapElement<T> newElement) { int pos = find(oldMap, newElement.name); if ((pos != -1) && (newElement.name.equals(oldMap[pos].name))) { return false; } System.arraycopy(oldMap, 0, newMap, 0, pos + 1); newMap[pos + 1] = newElement; System.arraycopy (oldMap, pos + 1, newMap, pos + 2, oldMap.length - pos - 1); return true; } /** * Insert into the right place in a sorted MapElement array. */ private static final <T> boolean removeMap (MapElement<T>[] oldMap, MapElement<T>[] newMap, String name) { int pos = find(oldMap, name); if ((pos != -1) && (name.equals(oldMap[pos].name))) { System.arraycopy(oldMap, 0, newMap, 0, pos); System.arraycopy(oldMap, pos + 1, newMap, pos, oldMap.length - pos - 1); return true; } return false; } // ------------------------------------------------- MapElement Inner Class protected abstract static class MapElement<T> { public String name = null; public T object = null; } // ------------------------------------------------------- Host Inner Class protected static final class MappedHost extends MapElement<Host> { public ContextList contextList = null; } // ------------------------------------------------ ContextList Inner Class protected static final class ContextList { public MappedContext[] contexts = new MappedContext[0]; public int nesting = 0; } // ---------------------------------------------------- Context Inner Class protected static final class MappedContext extends MapElement<Context> { public ContextVersion[] versions = new ContextVersion[0]; } protected static final class ContextVersion extends MapElement<Context> { public String path = null; public String[] welcomeResources = new String[0]; public WebResourceRoot resources = null; public MappedWrapper defaultWrapper = null; public MappedWrapper[] exactWrappers = new MappedWrapper[0]; public MappedWrapper[] wildcardWrappers = new MappedWrapper[0]; public MappedWrapper[] extensionWrappers = new MappedWrapper[0]; public int nesting = 0; } // ---------------------------------------------------- Wrapper Inner Class protected static class MappedWrapper extends MapElement<Wrapper> { public boolean jspWildCard = false; public boolean resourceOnly = false; } }
54,928
Bug 54928 IllegalStateException: Calling [asyncError()] is not valid for a request with Async state [COMPLETING]
In an async scenario (request.startAsync), when the client goes away, trying to write to the response raises an IOException. If I then call asyncContext.complete() in order to finalize and clean up the request, soon after the following exception occurs: java.lang.IllegalStateException: Calling [asyncError()] is not valid for a request with Async state [COMPLETING] at org.apache.coyote.AsyncStateMachine.asyncError(AsyncStateMachine.java:304) at org.apache.coyote.http11.AbstractHttp11Processor.action(AbstractHttp11Processor.java:793) at org.apache.coyote.Request.action(Request.java:373) at org.apache.catalina.core.AsyncContextImpl.setErrorState(AsyncContextImpl.java:441) at org.apache.catalina.connector.CoyoteAdapter.asyncDispatch(CoyoteAdapter.java:312) at org.apache.coyote.http11.AbstractHttp11Processor.asyncDispatch(AbstractHttp11Processor.java:1509) at org.apache.coyote.http11.Http11NioProcessor.asyncDispatch(Http11NioProcessor.java:221) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:619) at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:223) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1581) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1540) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603) at java.lang.Thread.run(Thread.java:722) It looks like an attempt to maybe to send an error event to AsyncListener's but asyncContext.complete has already been called. Is calling asyncContext.complete() a reasonable way to handle an IOException from the response in order to finalize the request and release any resorces associated with it?
resolved fixed
3960b22
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-24T14:09:55Z
2013-05-04T17:53:20Z
test/org/apache/catalina/connector/TestCoyoteAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.connector; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; public class TestCoyoteAdapter extends TomcatBaseTest { @Test public void testPathParmsRootNone() throws Exception { pathParamTest("/", "none"); } @Test public void testPathParmsFooNone() throws Exception { pathParamTest("/foo", "none"); } @Test public void testPathParmsRootSessionOnly() throws Exception { pathParamTest("/;jsessionid=1234", "1234"); } @Test public void testPathParmsFooSessionOnly() throws Exception { pathParamTest("/foo;jsessionid=1234", "1234"); } @Test public void testPathParmsFooSessionDummy() throws Exception { pathParamTest("/foo;jsessionid=1234;dummy", "1234"); } @Test public void testPathParmsFooSessionDummyValue() throws Exception { pathParamTest("/foo;jsessionid=1234;dummy=5678", "1234"); } @Test public void testPathParmsFooSessionValue() throws Exception { pathParamTest("/foo;jsessionid=1234;=5678", "1234"); } @Test public void testPathParmsFooSessionBar() throws Exception { pathParamTest("/foo;jsessionid=1234/bar", "1234"); } @Test public void testPathParamsRedirect() throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp File docBase = new File(System.getProperty("java.io.tmpdir")); // Create the folder that will trigger the redirect File foo = new File(docBase, "foo"); addDeleteOnTearDown(foo); if (!foo.mkdirs() && !foo.isDirectory()) { Assert.fail("Unable to create foo directory in docBase"); } Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); Tomcat.addServlet(ctx, "servlet", new PathParamServlet()); ctx.addServletMapping("/", "servlet"); tomcat.start(); testPath("/", "none"); testPath("/;jsessionid=1234", "1234"); testPath("/foo;jsessionid=1234", "1234"); testPath("/foo;jsessionid=1234;dummy", "1234"); testPath("/foo;jsessionid=1234;dummy=5678", "1234"); testPath("/foo;jsessionid=1234;=5678", "1234"); testPath("/foo;jsessionid=1234/bar", "1234"); } private void pathParamTest(String path, String expected) throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "servlet", new PathParamServlet()); ctx.addServletMapping("/", "servlet"); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + path); Assert.assertEquals(expected, res.toString()); } private void testPath(String path, String expected) throws Exception { ByteChunk res = getUrl("http://localhost:" + getPort() + path); Assert.assertEquals(expected, res.toString()); } private static class PathParamServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); PrintWriter pw = resp.getWriter(); String sessionId = req.getRequestedSessionId(); if (sessionId == null) { sessionId = "none"; } pw.write(sessionId); } } @Test public void testPathParamExtRootNoParam() throws Exception { pathParamExtenionTest("/testapp/blah.txt", "none"); } @Test public void testPathParamExtLevel1NoParam() throws Exception { pathParamExtenionTest("/testapp/blah/blah.txt", "none"); } @Test public void testPathParamExtLevel1WithParam() throws Exception { pathParamExtenionTest("/testapp/blah;x=y/blah.txt", "none"); } private void pathParamExtenionTest(String path, String expected) throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("/testapp", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "servlet", new PathParamServlet()); ctx.addServletMapping("*.txt", "servlet"); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + path); Assert.assertEquals(expected, res.toString()); } @Test public void testBug54602a() throws Exception { // No UTF-8 doTestUriDecoding("/foo", "UTF-8", "/foo"); } @Test public void testBug54602b() throws Exception { // Valid UTF-8 doTestUriDecoding("/foo%c4%87", "UTF-8", "/foo\u0107"); } @Test public void testBug54602c() throws Exception { // Partial UTF-8 doTestUriDecoding("/foo%c4", "UTF-8", "/foo\uFFFD"); } @Test public void testBug54602d() throws Exception { // Invalid UTF-8 doTestUriDecoding("/foo%ff", "UTF-8", "/foo\uFFFD"); } @Test public void testBug54602e() throws Exception { // Invalid UTF-8 doTestUriDecoding("/foo%ed%a0%80", "UTF-8", "/foo\uFFFD\uFFFD\uFFFD"); } private void doTestUriDecoding(String path, String encoding, String expectedPathInfo) throws Exception{ // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); tomcat.getConnector().setURIEncoding(encoding); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("/", System.getProperty("java.io.tmpdir")); PathInfoServlet servlet = new PathInfoServlet(); Tomcat.addServlet(ctx, "servlet", servlet); ctx.addServletMapping("/*", "servlet"); tomcat.start(); int rc = getUrl("http://localhost:" + getPort() + path, new ByteChunk(), null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); Assert.assertEquals(expectedPathInfo, servlet.getPathInfo()); } private static class PathInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; private String pathInfo = null; public String getPathInfo() { return pathInfo; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Not thread safe pathInfo = req.getPathInfo(); } } }
54,984
Bug 54984 multipart/form-data is not always read with correct encoding
The bug occurs when form data is posted as multipart/form-data and using Servlet 3 API to get posted files. In a servlet, if we set the encoding: request.setCharacterEncoding("UTF-8"); Then invoke: request.getParts() And then invoke: String text = request.getParameter("sometextfield"); UTF-8 characters in the text have been garbled. Order of method calls are significant, if a getParameter is called before getParts, the correct encoding will be used. However, the order which you invoke the methods should not matter.
resolved fixed
7558546
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-24T17:46:27Z
2013-05-16T16:00:00Z
java/org/apache/catalina/connector/Request.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.connector; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.security.Principal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.NamingException; import javax.security.auth.Subject; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.MultipartConfigElement; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestAttributeEvent; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletResponse; import javax.servlet.SessionTrackingMode; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.Part; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Manager; import org.apache.catalina.Realm; import org.apache.catalina.Session; import org.apache.catalina.TomcatPrincipal; import org.apache.catalina.Wrapper; import org.apache.catalina.core.ApplicationPart; import org.apache.catalina.core.ApplicationSessionCookieConfig; import org.apache.catalina.core.AsyncContextImpl; import org.apache.catalina.mapper.MappingData; import org.apache.catalina.util.ParameterMap; import org.apache.catalina.util.StringParser; import org.apache.coyote.ActionCode; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.Cookies; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.Parameters; import org.apache.tomcat.util.http.ServerCookie; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileUploadBase; import org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; import org.apache.tomcat.util.res.StringManager; /** * Wrapper object for the Coyote request. * * @author Remy Maucherat * @author Craig R. McClanahan * @version $Id$ */ public class Request implements HttpServletRequest { private static final Log log = LogFactory.getLog(Request.class); // ----------------------------------------------------------- Constructors public Request() { formats[0].setTimeZone(GMT_ZONE); formats[1].setTimeZone(GMT_ZONE); formats[2].setTimeZone(GMT_ZONE); } // ------------------------------------------------------------- Properties /** * Coyote request. */ protected org.apache.coyote.Request coyoteRequest; /** * Set the Coyote request. * * @param coyoteRequest The Coyote request */ public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) { this.coyoteRequest = coyoteRequest; inputBuffer.setRequest(coyoteRequest); } /** * Get the Coyote request. */ public org.apache.coyote.Request getCoyoteRequest() { return (this.coyoteRequest); } // ----------------------------------------------------- Variables protected static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT"); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The set of cookies associated with this Request. */ protected Cookie[] cookies = null; /** * The set of SimpleDateFormat formats to use in getDateHeader(). * * Notice that because SimpleDateFormat is not thread-safe, we can't * declare formats[] as a static variable. */ protected final SimpleDateFormat formats[] = { new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE, Locale.US), new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; /** * The default Locale if none are specified. */ protected static final Locale defaultLocale = Locale.getDefault(); /** * The attributes associated with this Request, keyed by attribute name. */ protected final HashMap<String, Object> attributes = new HashMap<>(); /** * Flag that indicates if SSL attributes have been parsed to improve * performance for applications (usually frameworks) that make multiple * calls to {@link Request#getAttributeNames()}. */ protected boolean sslAttributesParsed = false; /** * List of read only attributes for this Request. */ private final HashMap<String,Object> readOnlyAttributes = new HashMap<>(); /** * The preferred Locales associated with this Request. */ protected final ArrayList<Locale> locales = new ArrayList<>(); /** * Internal notes associated with this request by Catalina components * and event listeners. */ private final transient HashMap<String, Object> notes = new HashMap<>(); /** * Authentication type. */ protected String authType = null; /** * Associated event. */ protected CometEventImpl event = null; /** * Comet state */ protected boolean comet = false; /** * The current dispatcher type. */ protected DispatcherType internalDispatcherType = null; /** * The associated input buffer. */ protected final InputBuffer inputBuffer = new InputBuffer(); /** * ServletInputStream. */ protected CoyoteInputStream inputStream = new CoyoteInputStream(inputBuffer); /** * Reader. */ protected CoyoteReader reader = new CoyoteReader(inputBuffer); /** * Using stream flag. */ protected boolean usingInputStream = false; /** * Using writer flag. */ protected boolean usingReader = false; /** * User principal. */ protected Principal userPrincipal = null; /** * Request parameters parsed flag. */ protected boolean parametersParsed = false; /** * Cookies parsed flag. */ protected boolean cookiesParsed = false; /** * Secure flag. */ protected boolean secure = false; /** * The Subject associated with the current AccessControllerContext */ protected transient Subject subject = null; /** * Post data buffer. */ protected static final int CACHED_POST_LEN = 8192; protected byte[] postData = null; /** * Hash map used in the getParametersMap method. */ protected ParameterMap<String, String[]> parameterMap = new ParameterMap<>(); /** * The parts, if any, uploaded with this request. */ protected Collection<Part> parts = null; /** * The exception thrown, if any when parsing the parts. */ protected Exception partsParseException = null; /** * The currently active session for this request. */ protected Session session = null; /** * The current request dispatcher path. */ protected Object requestDispatcherPath = null; /** * Was the requested session ID received in a cookie? */ protected boolean requestedSessionCookie = false; /** * The requested session ID (if any) for this request. */ protected String requestedSessionId = null; /** * Was the requested session ID received in a URL? */ protected boolean requestedSessionURL = false; /** * Was the requested session ID obtained from the SSL session? */ protected boolean requestedSessionSSL = false; /** * Parse locales. */ protected boolean localesParsed = false; /** * The string parser we will use for parsing request lines. */ private final StringParser parser = new StringParser(); /** * Local port */ protected int localPort = -1; /** * Remote address. */ protected String remoteAddr = null; /** * Remote host. */ protected String remoteHost = null; /** * Remote port */ protected int remotePort = -1; /** * Local address */ protected String localAddr = null; /** * Local address */ protected String localName = null; /** * AsyncContext */ protected volatile AsyncContextImpl asyncContext = null; protected Boolean asyncSupported = null; /** * Path parameters */ protected final Map<String,String> pathParameters = new HashMap<>(); // --------------------------------------------------------- Public Methods protected void addPathParameter(String name, String value) { pathParameters.put(name, value); } protected String getPathParameter(String name) { return pathParameters.get(name); } public void setAsyncSupported(boolean asyncSupported) { this.asyncSupported = Boolean.valueOf(asyncSupported); } /** * Release all object references, and initialize instance variables, in * preparation for reuse of this object. */ public void recycle() { context = null; wrapper = null; internalDispatcherType = null; requestDispatcherPath = null; comet = false; if (event != null) { event.clear(); event = null; } authType = null; inputBuffer.recycle(); usingInputStream = false; usingReader = false; userPrincipal = null; subject = null; parametersParsed = false; if (parts != null) { for (Part part: parts) { try { part.delete(); } catch (IOException ignored) { // ApplicationPart.delete() never throws an IOEx } } parts = null; } partsParseException = null; cookiesParsed = false; locales.clear(); localesParsed = false; secure = false; remoteAddr = null; remoteHost = null; remotePort = -1; localPort = -1; localAddr = null; localName = null; attributes.clear(); sslAttributesParsed = false; notes.clear(); cookies = null; if (session != null) { try { session.endAccess(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); } } session = null; requestedSessionCookie = false; requestedSessionId = null; requestedSessionURL = false; if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) { parameterMap = new ParameterMap<>(); } else { parameterMap.setLocked(false); parameterMap.clear(); } mappingData.recycle(); if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) { if (facade != null) { facade.clear(); facade = null; } if (inputStream != null) { inputStream.clear(); inputStream = null; } if (reader != null) { reader.clear(); reader = null; } } asyncSupported = null; if (asyncContext!=null) { asyncContext.recycle(); } asyncContext = null; pathParameters.clear(); } /** * Clear cached encoders (to save memory for Comet requests). */ public void clearEncoders() { inputBuffer.clearEncoders(); } /** * Clear cached encoders (to save memory for Comet requests). */ public boolean read() throws IOException { return (inputBuffer.realReadBytes(null, 0, 0) > 0); } // -------------------------------------------------------- Request Methods /** * Associated Catalina connector. */ protected Connector connector; /** * Return the Connector through which this Request was received. */ public Connector getConnector() { return this.connector; } /** * Set the Connector through which this Request was received. * * @param connector The new connector */ public void setConnector(Connector connector) { this.connector = connector; } /** * Associated context. */ protected Context context = null; /** * Return the Context within which this Request is being processed. */ public Context getContext() { return this.context; } /** * Set the Context within which this Request is being processed. This * must be called as soon as the appropriate Context is identified, because * it identifies the value to be returned by <code>getContextPath()</code>, * and thus enables parsing of the request URI. * * @param context The newly associated Context */ public void setContext(Context context) { this.context = context; } /** * Filter chain associated with the request. */ protected FilterChain filterChain = null; /** * Get filter chain associated with the request. */ public FilterChain getFilterChain() { return this.filterChain; } /** * Set filter chain associated with the request. * * @param filterChain new filter chain */ public void setFilterChain(FilterChain filterChain) { this.filterChain = filterChain; } /** * Return the Host within which this Request is being processed. */ public Host getHost() { return mappingData.host; } /** * Mapping data. */ protected final MappingData mappingData = new MappingData(); /** * Return mapping data. */ public MappingData getMappingData() { return mappingData; } /** * The facade associated with this request. */ protected RequestFacade facade = null; /** * Return the <code>ServletRequest</code> for which this object * is the facade. This method must be implemented by a subclass. */ public HttpServletRequest getRequest() { if (facade == null) { facade = new RequestFacade(this); } return facade; } /** * The response with which this request is associated. */ protected org.apache.catalina.connector.Response response = null; /** * Return the Response with which this Request is associated. */ public org.apache.catalina.connector.Response getResponse() { return this.response; } /** * Set the Response with which this Request is associated. * * @param response The new associated response */ public void setResponse(org.apache.catalina.connector.Response response) { this.response = response; } /** * Return the input stream associated with this Request. */ public InputStream getStream() { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * URI byte to char converter. */ protected B2CConverter URIConverter = null; /** * Return the URI converter. */ protected B2CConverter getURIConverter() { return URIConverter; } /** * Set the URI converter. * * @param URIConverter the new URI converter */ protected void setURIConverter(B2CConverter URIConverter) { this.URIConverter = URIConverter; } /** * Associated wrapper. */ protected Wrapper wrapper = null; /** * Return the Wrapper within which this Request is being processed. */ public Wrapper getWrapper() { return this.wrapper; } /** * Set the Wrapper within which this Request is being processed. This * must be called as soon as the appropriate Wrapper is identified, and * before the Request is ultimately passed to an application servlet. * @param wrapper The newly associated Wrapper */ public void setWrapper(Wrapper wrapper) { this.wrapper = wrapper; } // ------------------------------------------------- Request Public Methods /** * Create and return a ServletInputStream to read the content * associated with this Request. * * @exception IOException if an input/output error occurs */ public ServletInputStream createInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * Perform whatever actions are required to flush and close the input * stream or reader, in a single operation. * * @exception IOException if an input/output error occurs */ public void finishRequest() throws IOException { // Optionally disable swallowing of additional request data. Context context = getContext(); if (context != null && response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } } /** * Return the object bound with the specified name to the internal notes * for this request, or <code>null</code> if no such binding exists. * * @param name Name of the note to be returned */ public Object getNote(String name) { return notes.get(name); } /** * Remove any object bound to the specified name in the internal notes * for this request. * * @param name Name of the note to be removed */ public void removeNote(String name) { notes.remove(name); } /** * Set the port number of the server to process this request. * * @param port The server port */ public void setLocalPort(int port) { localPort = port; } /** * Bind an object to a specified name in the internal notes associated * with this request, replacing any existing binding for this name. * * @param name Name to which the object should be bound * @param value Object to be bound to the specified name */ public void setNote(String name, Object value) { notes.put(name, value); } /** * Set the IP address of the remote client associated with this Request. * * @param remoteAddr The remote IP address */ public void setRemoteAddr(String remoteAddr) { this.remoteAddr = remoteAddr; } /** * Set the fully qualified name of the remote client associated with this * Request. * * @param remoteHost The remote host name */ public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } /** * Set the value to be returned by <code>isSecure()</code> * for this Request. * * @param secure The new isSecure value */ public void setSecure(boolean secure) { this.secure = secure; } /** * Set the port number of the server to process this request. * * @param port The server port */ public void setServerPort(int port) { coyoteRequest.setServerPort(port); } // ------------------------------------------------- ServletRequest Methods /** * Return the specified request attribute if it exists; otherwise, return * <code>null</code>. * * @param name Name of the request attribute to return */ @Override public Object getAttribute(String name) { // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { return adapter.get(this, name); } Object attr=attributes.get(name); if(attr!=null) { return(attr); } attr = coyoteRequest.getAttribute(name); if(attr != null) { return attr; } if( isSSLAttribute(name) ) { coyoteRequest.action(ActionCode.REQ_SSL_ATTRIBUTE, coyoteRequest); attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR); if( attr != null) { attributes.put(Globals.CERTIFICATES_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR); if(attr != null) { attributes.put(Globals.CIPHER_SUITE_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR); if(attr != null) { attributes.put(Globals.KEY_SIZE_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR); if(attr != null) { attributes.put(Globals.SSL_SESSION_ID_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_MGR_ATTR); if(attr != null) { attributes.put(Globals.SSL_SESSION_MGR_ATTR, attr); } attr = attributes.get(name); sslAttributesParsed = true; } return attr; } @Override public long getContentLengthLong() { return coyoteRequest.getContentLengthLong(); } /** * Test if a given name is one of the special Servlet-spec SSL attributes. */ static boolean isSSLAttribute(String name) { return Globals.CERTIFICATES_ATTR.equals(name) || Globals.CIPHER_SUITE_ATTR.equals(name) || Globals.KEY_SIZE_ATTR.equals(name) || Globals.SSL_SESSION_ID_ATTR.equals(name) || Globals.SSL_SESSION_MGR_ATTR.equals(name); } /** * Return the names of all request attributes for this Request, or an * empty <code>Enumeration</code> if there are none. Note that the attribute * names returned will only be those for the attributes set via * {@link #setAttribute(String, Object)}. Tomcat internal attributes will * not be included although they are accessible via * {@link #getAttribute(String)}. The Tomcat internal attributes include: * <ul> * <li>{@link Globals#DISPATCHER_TYPE_ATTR}</li> * <li>{@link Globals#DISPATCHER_REQUEST_PATH_ATTR}</li> * <li>{@link Globals#ASYNC_SUPPORTED_ATTR}</li> * <li>{@link Globals#CERTIFICATES_ATTR} (SSL connections only)</li> * <li>{@link Globals#CIPHER_SUITE_ATTR} (SSL connections only)</li> * <li>{@link Globals#KEY_SIZE_ATTR} (SSL connections only)</li> * <li>{@link Globals#SSL_SESSION_ID_ATTR} (SSL connections only)</li> * <li>{@link Globals#SSL_SESSION_MGR_ATTR} (SSL connections only)</li> * <li>{@link Globals#PARAMETER_PARSE_FAILED_ATTR}</li> * </ul> * The underlying connector may also expose request attributes. These all * have names starting with "org.apache.tomcat" and include: * <ul> * <li>{@link Globals#SENDFILE_SUPPORTED_ATTR}</li> * <li>{@link Globals#COMET_SUPPORTED_ATTR}</li> * <li>{@link Globals#COMET_TIMEOUT_SUPPORTED_ATTR}</li> * </ul> * Connector implementations may return some, all or none of these * attributes and may also support additional attributes. */ @Override public Enumeration<String> getAttributeNames() { if (isSecure() && !sslAttributesParsed) { getAttribute(Globals.CERTIFICATES_ATTR); } // Take a copy to prevent ConncurrentModificationExceptions if used to // remove attributes Set<String> names = new HashSet<>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); } /** * Return the character encoding for this Request. */ @Override public String getCharacterEncoding() { return coyoteRequest.getCharacterEncoding(); } /** * Return the content length for this Request. */ @Override public int getContentLength() { return coyoteRequest.getContentLength(); } /** * Return the content type for this Request. */ @Override public String getContentType() { return coyoteRequest.getContentType(); } /** * Set the content type for this Request. */ public void setContentType(String contentType) { coyoteRequest.setContentType(contentType); } /** * Return the servlet input stream for this Request. The default * implementation returns a servlet input stream created by * <code>createInputStream()</code>. * * @exception IllegalStateException if <code>getReader()</code> has * already been called for this request * @exception IOException if an input/output error occurs */ @Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * Return the preferred Locale that the client will accept content in, * based on the value for the first <code>Accept-Language</code> header * that was encountered. If the request did not specify a preferred * language, the server's default Locale is returned. */ @Override public Locale getLocale() { if (!localesParsed) { parseLocales(); } if (locales.size() > 0) { return locales.get(0); } return defaultLocale; } /** * Return the set of preferred Locales that the client will accept * content in, based on the values for any <code>Accept-Language</code> * headers that were encountered. If the request did not specify a * preferred language, the server's default Locale is returned. */ @Override public Enumeration<Locale> getLocales() { if (!localesParsed) { parseLocales(); } if (locales.size() > 0) { return Collections.enumeration(locales); } ArrayList<Locale> results = new ArrayList<>(); results.add(defaultLocale); return Collections.enumeration(results); } /** * Return the value of the specified request parameter, if any; otherwise, * return <code>null</code>. If there is more than one value defined, * return only the first one. * * @param name Name of the desired request parameter */ @Override public String getParameter(String name) { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameter(name); } /** * Returns a <code>Map</code> of the parameters of this request. * Request parameters are extra information sent with the request. * For HTTP servlets, parameters are contained in the query string * or posted form data. * * @return A <code>Map</code> containing parameter names as keys * and parameter values as map values. */ @Override public Map<String, String[]> getParameterMap() { if (parameterMap.isLocked()) { return parameterMap; } Enumeration<String> enumeration = getParameterNames(); while (enumeration.hasMoreElements()) { String name = enumeration.nextElement(); String[] values = getParameterValues(name); parameterMap.put(name, values); } parameterMap.setLocked(true); return parameterMap; } /** * Return the names of all defined request parameters for this request. */ @Override public Enumeration<String> getParameterNames() { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameterNames(); } /** * Return the defined values for the specified request parameter, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired request parameter */ @Override public String[] getParameterValues(String name) { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameterValues(name); } /** * Return the protocol and version used to make this Request. */ @Override public String getProtocol() { return coyoteRequest.protocol().toString(); } /** * Read the Reader wrapping the input stream for this Request. The * default implementation wraps a <code>BufferedReader</code> around the * servlet input stream returned by <code>createInputStream()</code>. * * @exception IllegalStateException if <code>getInputStream()</code> * has already been called for this request * @exception IOException if an input/output error occurs */ @Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; } /** * Return the real path of the specified virtual path. * * @param path Path to be translated * * @deprecated As of version 2.1 of the Java Servlet API, use * <code>ServletContext.getRealPath()</code>. */ @Override @Deprecated public String getRealPath(String path) { if (context == null) { return null; } ServletContext servletContext = context.getServletContext(); if (servletContext == null) { return null; } try { return (servletContext.getRealPath(path)); } catch (IllegalArgumentException e) { return null; } } /** * Return the remote IP address making this Request. */ @Override public String getRemoteAddr() { if (remoteAddr == null) { coyoteRequest.action (ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest); remoteAddr = coyoteRequest.remoteAddr().toString(); } return remoteAddr; } /** * Return the remote host name making this Request. */ @Override public String getRemoteHost() { if (remoteHost == null) { if (!connector.getEnableLookups()) { remoteHost = getRemoteAddr(); } else { coyoteRequest.action (ActionCode.REQ_HOST_ATTRIBUTE, coyoteRequest); remoteHost = coyoteRequest.remoteHost().toString(); } } return remoteHost; } /** * Returns the Internet Protocol (IP) source port of the client * or last proxy that sent the request. */ @Override public int getRemotePort(){ if (remotePort == -1) { coyoteRequest.action (ActionCode.REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest); remotePort = coyoteRequest.getRemotePort(); } return remotePort; } /** * Returns the host name of the Internet Protocol (IP) interface on * which the request was received. */ @Override public String getLocalName(){ if (localName == null) { coyoteRequest.action (ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest); localName = coyoteRequest.localName().toString(); } return localName; } /** * Returns the Internet Protocol (IP) address of the interface on * which the request was received. */ @Override public String getLocalAddr(){ if (localAddr == null) { coyoteRequest.action (ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest); localAddr = coyoteRequest.localAddr().toString(); } return localAddr; } /** * Returns the Internet Protocol (IP) port number of the interface * on which the request was received. */ @Override public int getLocalPort(){ if (localPort == -1){ coyoteRequest.action (ActionCode.REQ_LOCALPORT_ATTRIBUTE, coyoteRequest); localPort = coyoteRequest.getLocalPort(); } return localPort; } /** * Return a RequestDispatcher that wraps the resource at the specified * path, which may be interpreted as relative to the current request path. * * @param path Path of the resource to be wrapped */ @Override public RequestDispatcher getRequestDispatcher(String path) { if (context == null) { return null; } // If the path is already context-relative, just pass it through if (path == null) { return null; } else if (path.startsWith("/")) { return (context.getServletContext().getRequestDispatcher(path)); } // Convert a request-relative path to a context-relative one String servletPath = (String) getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (servletPath == null) { servletPath = getServletPath(); } // Add the path info, if there is any String pathInfo = getPathInfo(); String requestPath = null; if (pathInfo == null) { requestPath = servletPath; } else { requestPath = servletPath + pathInfo; } int pos = requestPath.lastIndexOf('/'); String relative = null; if (pos >= 0) { relative = requestPath.substring(0, pos + 1) + path; } else { relative = requestPath + path; } return context.getServletContext().getRequestDispatcher(relative); } /** * Return the scheme used to make this Request. */ @Override public String getScheme() { return coyoteRequest.scheme().toString(); } /** * Return the server name responding to this Request. */ @Override public String getServerName() { return coyoteRequest.serverName().toString(); } /** * Return the server port responding to this Request. */ @Override public int getServerPort() { return coyoteRequest.getServerPort(); } /** * Was this request received on a secure connection? */ @Override public boolean isSecure() { return secure; } /** * Remove the specified request attribute if it exists. * * @param name Name of the request attribute to remove */ @Override public void removeAttribute(String name) { // Remove the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.getAttributes().remove(name); } boolean found = attributes.containsKey(name); if (found) { Object value = attributes.get(name); attributes.remove(name); // Notify interested application event listeners notifyAttributeRemoved(name, value); } else { return; } } /** * Set the specified request attribute to the specified value. * * @param name Name of the request attribute to set * @param value The associated value */ @Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); } /** * Notify interested listeners that attribute has been assigned a value. */ private void notifyAttributeAssigned(String name, Object value, Object oldValue) { Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) { return; } boolean replaced = (oldValue != null); ServletRequestAttributeEvent event = null; if (replaced) { event = new ServletRequestAttributeEvent( context.getServletContext(), getRequest(), name, oldValue); } else { event = new ServletRequestAttributeEvent( context.getServletContext(), getRequest(), name, value); } for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletRequestAttributeListener)) { continue; } ServletRequestAttributeListener listener = (ServletRequestAttributeListener) listeners[i]; try { if (replaced) { listener.attributeReplaced(event); } else { listener.attributeAdded(event); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); } } } /** * Notify interested listeners that attribute has been removed. */ private void notifyAttributeRemoved(String name, Object value) { Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) { return; } ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(context.getServletContext(), getRequest(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletRequestAttributeListener)) { continue; } ServletRequestAttributeListener listener = (ServletRequestAttributeListener) listeners[i]; try { listener.attributeRemoved(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); } } } /** * Overrides the name of the character encoding used in the body of * this request. This method must be called prior to reading request * parameters or reading input using <code>getReader()</code>. * * @param enc The character encoding to be used * * @exception UnsupportedEncodingException if the specified encoding * is not supported * * @since Servlet 2.3 */ @Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { if (usingReader) { return; } // Ensure that the specified encoding is valid byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; // Confirm that the encoding name is valid B2CConverter.getCharset(enc); // Save the validated encoding coyoteRequest.setCharacterEncoding(enc); } @Override public ServletContext getServletContext() { return context.getServletContext(); } @Override public AsyncContext startAsync() { return startAsync(getRequest(),response.getResponse()); } @Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) { if (!isAsyncSupported()) { throw new IllegalStateException("Not supported."); } if (asyncContext == null) { asyncContext = new AsyncContextImpl(this); } asyncContext.setStarted(getContext(), request, response, request==getRequest() && response==getResponse().getResponse()); asyncContext.setTimeout(getConnector().getAsyncTimeout()); return asyncContext; } @Override public boolean isAsyncStarted() { if (asyncContext == null) { return false; } return asyncContext.isStarted(); } public boolean isAsyncDispatching() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_DISPATCHING, result); return result.get(); } public boolean isAsync() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC, result); return result.get(); } @Override public boolean isAsyncSupported() { if (this.asyncSupported == null) { return true; } return asyncSupported.booleanValue(); } @Override public AsyncContext getAsyncContext() { return this.asyncContext; } @Override public DispatcherType getDispatcherType() { if (internalDispatcherType == null) { return DispatcherType.REQUEST; } return this.internalDispatcherType; } // ---------------------------------------------------- HttpRequest Methods /** * Add a Cookie to the set of Cookies associated with this Request. * * @param cookie The new cookie */ public void addCookie(Cookie cookie) { if (!cookiesParsed) { parseCookies(); } int size = 0; if (cookies != null) { size = cookies.length; } Cookie[] newCookies = new Cookie[size + 1]; for (int i = 0; i < size; i++) { newCookies[i] = cookies[i]; } newCookies[size] = cookie; cookies = newCookies; } /** * Add a Locale to the set of preferred Locales for this Request. The * first added Locale will be the first one returned by getLocales(). * * @param locale The new preferred Locale */ public void addLocale(Locale locale) { locales.add(locale); } /** * Clear the collection of Cookies associated with this Request. */ public void clearCookies() { cookiesParsed = true; cookies = null; } /** * Clear the collection of Locales associated with this Request. */ public void clearLocales() { locales.clear(); } /** * Set the authentication type used for this request, if any; otherwise * set the type to <code>null</code>. Typical values are "BASIC", * "DIGEST", or "SSL". * * @param type The authentication type used */ public void setAuthType(String type) { this.authType = type; } /** * Set the path information for this Request. This will normally be called * when the associated Context is mapping the Request to a particular * Wrapper. * * @param path The path information */ public void setPathInfo(String path) { mappingData.pathInfo.setString(path); } /** * Set a flag indicating whether or not the requested session ID for this * request came in through a cookie. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionCookie(boolean flag) { this.requestedSessionCookie = flag; } /** * Set the requested session ID for this request. This is normally called * by the HTTP Connector, when it parses the request headers. * * @param id The new session id */ public void setRequestedSessionId(String id) { this.requestedSessionId = id; } /** * Set a flag indicating whether or not the requested session ID for this * request came in through a URL. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionURL(boolean flag) { this.requestedSessionURL = flag; } /** * Set a flag indicating whether or not the requested session ID for this * request came in through SSL. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionSSL(boolean flag) { this.requestedSessionSSL = flag; } /** * Get the decoded request URI. * * @return the URL decoded request URI */ public String getDecodedRequestURI() { return coyoteRequest.decodedURI().toString(); } /** * Get the decoded request URI. * * @return the URL decoded request URI */ public MessageBytes getDecodedRequestURIMB() { return coyoteRequest.decodedURI(); } /** * Set the Principal who has been authenticated for this Request. This * value is also used to calculate the value to be returned by the * <code>getRemoteUser()</code> method. * * @param principal The user Principal */ public void setUserPrincipal(Principal principal) { if (Globals.IS_SECURITY_ENABLED){ HttpSession session = getSession(false); if ( (subject != null) && (!subject.getPrincipals().contains(principal)) ){ subject.getPrincipals().add(principal); } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) { subject = new Subject(); subject.getPrincipals().add(principal); } if (session != null){ session.setAttribute(Globals.SUBJECT_ATTR, subject); } } this.userPrincipal = principal; } // --------------------------------------------- HttpServletRequest Methods /** * {@inheritDoc} * * @since Servlet 3.1 */ @Override public <T extends HttpUpgradeHandler> T upgrade( Class<T> httpUpgradeHandlerClass) throws java.io.IOException { T handler; try { handler = (T) context.getInstanceManager().newInstance(httpUpgradeHandlerClass); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NamingException e) { throw new IOException(e); } coyoteRequest.action(ActionCode.UPGRADE, handler); // Output required by RFC2616. Protocol specific headers should have // already been set. response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); response.flushBuffer(); return handler; } /** * Return the authentication type used for this Request. */ @Override public String getAuthType() { return authType; } /** * Return the portion of the request URI used to select the Context * of the Request. */ @Override public String getContextPath() { return mappingData.contextPath.toString(); } /** * Return the set of Cookies received with this Request. */ @Override public Cookie[] getCookies() { if (!cookiesParsed) { parseCookies(); } return cookies; } /** * Return the value of the specified date header, if any; otherwise * return -1. * * @param name Name of the requested date header * * @exception IllegalArgumentException if the specified header value * cannot be converted to a date */ @Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return (-1L); } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat.parseDate(value, formats); if (result != (-1L)) { return result; } throw new IllegalArgumentException(value); } /** * Return the first value of the specified header, if any; otherwise, * return <code>null</code> * * @param name Name of the requested header */ @Override public String getHeader(String name) { return coyoteRequest.getHeader(name); } /** * Return all of the values of the specified header, if any; otherwise, * return an empty enumeration. * * @param name Name of the requested header */ @Override public Enumeration<String> getHeaders(String name) { return coyoteRequest.getMimeHeaders().values(name); } /** * Return the names of all headers received with this request. */ @Override public Enumeration<String> getHeaderNames() { return coyoteRequest.getMimeHeaders().names(); } /** * Return the value of the specified header as an integer, or -1 if there * is no such header for this request. * * @param name Name of the requested header * * @exception IllegalArgumentException if the specified header value * cannot be converted to an integer */ @Override public int getIntHeader(String name) { String value = getHeader(name); if (value == null) { return (-1); } return Integer.parseInt(value); } /** * Return the HTTP request method used in this Request. */ @Override public String getMethod() { return coyoteRequest.method().toString(); } /** * Return the path information associated with this Request. */ @Override public String getPathInfo() { return mappingData.pathInfo.toString(); } /** * Return the extra path information for this request, translated * to a real path. */ @Override public String getPathTranslated() { if (context == null) { return null; } if (getPathInfo() == null) { return null; } return context.getServletContext().getRealPath(getPathInfo()); } /** * Return the query string associated with this request. */ @Override public String getQueryString() { return coyoteRequest.queryString().toString(); } /** * Return the name of the remote user that has been authenticated * for this Request. */ @Override public String getRemoteUser() { if (userPrincipal == null) { return null; } return userPrincipal.getName(); } /** * Get the request path. * * @return the request path */ public MessageBytes getRequestPathMB() { return mappingData.requestPath; } /** * Return the session identifier included in this request, if any. */ @Override public String getRequestedSessionId() { return requestedSessionId; } /** * Return the request URI for this request. */ @Override public String getRequestURI() { return coyoteRequest.requestURI().toString(); } /** * Reconstructs the URL the client used to make the request. * The returned URL contains a protocol, server name, port * number, and server path, but it does not include query * string parameters. * <p> * Because this method returns a <code>StringBuffer</code>, * not a <code>String</code>, you can modify the URL easily, * for example, to append query parameters. * <p> * This method is useful for creating redirect messages and * for reporting errors. * * @return A <code>StringBuffer</code> object containing the * reconstructed URL */ @Override public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); String scheme = getScheme(); int port = getServerPort(); if (port < 0) { port = 80; // Work around java.net.URL bug } url.append(scheme); url.append("://"); url.append(getServerName()); if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) { url.append(':'); url.append(port); } url.append(getRequestURI()); return url; } /** * Return the portion of the request URI used to select the servlet * that will process this request. */ @Override public String getServletPath() { return (mappingData.wrapperPath.toString()); } /** * Return the session associated with this Request, creating one * if necessary. */ @Override public HttpSession getSession() { Session session = doGetSession(true); if (session == null) { return null; } return session.getSession(); } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ @Override public HttpSession getSession(boolean create) { Session session = doGetSession(create); if (session == null) { return null; } return session.getSession(); } /** * Return <code>true</code> if the session identifier included in this * request came from a cookie. */ @Override public boolean isRequestedSessionIdFromCookie() { if (requestedSessionId == null) { return false; } return requestedSessionCookie; } /** * Return <code>true</code> if the session identifier included in this * request came from the request URI. */ @Override public boolean isRequestedSessionIdFromURL() { if (requestedSessionId == null) { return false; } return requestedSessionURL; } /** * Return <code>true</code> if the session identifier included in this * request came from the request URI. * * @deprecated As of Version 2.1 of the Java Servlet API, use * <code>isRequestedSessionIdFromURL()</code> instead. */ @Override @Deprecated public boolean isRequestedSessionIdFromUrl() { return (isRequestedSessionIdFromURL()); } /** * Return <code>true</code> if the session identifier included in this * request identifies a valid session. */ @Override public boolean isRequestedSessionIdValid() { if (requestedSessionId == null) { return false; } if (context == null) { return false; } Manager manager = context.getManager(); if (manager == null) { return false; } Session session = null; try { session = manager.findSession(requestedSessionId); } catch (IOException e) { // Can't find the session } if ((session == null) || !session.isValid()) { // Check for parallel deployment contexts if (getMappingData().contexts == null) { return false; } else { for (int i = (getMappingData().contexts.length); i > 0; i--) { Context ctxt = getMappingData().contexts[i - 1]; try { if (ctxt.getManager().findSession(requestedSessionId) != null) { return true; } } catch (IOException e) { // Ignore } } return false; } } return true; } /** * Return <code>true</code> if the authenticated user principal * possesses the specified role name. * * @param role Role name to be validated */ @Override public boolean isUserInRole(String role) { // Have we got an authenticated principal at all? if (userPrincipal == null) { return false; } // Identify the Realm we will use for checking role assignments if (context == null) { return false; } Realm realm = context.getRealm(); if (realm == null) { return false; } // Check for a role defined directly as a <security-role> return (realm.hasRole(wrapper, userPrincipal, role)); } /** * Return the principal that has been authenticated for this Request. */ public Principal getPrincipal() { return userPrincipal; } /** * Return the principal that has been authenticated for this Request. */ @Override public Principal getUserPrincipal() { if (userPrincipal instanceof TomcatPrincipal) { return ((TomcatPrincipal) userPrincipal).getUserPrincipal(); } return userPrincipal; } /** * Return the session associated with this Request, creating one * if necessary. */ public Session getSessionInternal() { return doGetSession(true); } /** * Change the ID of the session that this request is associated with. There * are several things that may trigger an ID change. These include moving * between nodes in a cluster and session fixation prevention during the * authentication process. * * @param newSessionId The session to change the session ID for */ public void changeSessionId(String newSessionId) { // This should only ever be called if there was an old session ID but // double check to be sure if (requestedSessionId != null && requestedSessionId.length() > 0) { requestedSessionId = newSessionId; } if (context != null && !context.getServletContext() .getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { return; } if (response != null) { Cookie newCookie = ApplicationSessionCookieConfig.createSessionCookie(context, newSessionId, secure); response.addSessionCookieInternal(newCookie); } } /** * Changes the session ID of the session associated with this request. * * @return the old session ID before it was changed * @see javax.servlet.http.HttpSessionIdListener * @since Servlet 3.1 */ @Override public String changeSessionId() { Session session = this.getSessionInternal(false); if (session == null) { throw new IllegalStateException( sm.getString("coyoteRequest.changeSessionId")); } Manager manager = this.getContext().getManager(); manager.changeSessionId(session); String newSessionId = session.getId(); this.changeSessionId(newSessionId); return newSessionId; } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ public Session getSessionInternal(boolean create) { return doGetSession(create); } /** * Get the event associated with the request. * @return the event */ public CometEventImpl getEvent() { if (event == null) { event = new CometEventImpl(this, response); } return event; } /** * Return true if the current request is handling Comet traffic. */ public boolean isComet() { return comet; } /** * Set comet state. */ public void setComet(boolean comet) { this.comet = comet; } /** * return true if we have parsed parameters */ public boolean isParametersParsed() { return parametersParsed; } /** * Return true if bytes are available. */ public boolean getAvailable() { return (inputBuffer.available() > 0); } /** * Return true if an attempt has been made to read the request body and all * of the request body has been read */ public boolean isFinished() { AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.REQUEST_BODY_FULLY_READ, result); return result.get(); } /** * Disable swallowing of remaining input if configured */ protected void checkSwallowInput() { Context context = getContext(); if (context != null && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } } public void cometClose() { coyoteRequest.action(ActionCode.COMET_CLOSE,getEvent()); setComet(false); } public void setCometTimeout(long timeout) { coyoteRequest.action(ActionCode.COMET_SETTIMEOUT, Long.valueOf(timeout)); } /** * @throws IOException If an I/O error occurs * @throws IllegalStateException If the response has been committed * @throws ServletException If the caller is responsible for handling the * error and the container has NOT set the HTTP response code etc. */ @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); } /** * {@inheritDoc} */ @Override public void login(String username, String password) throws ServletException { if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { throw new ServletException( sm.getString("coyoteRequest.alreadyAuthenticated")); } if (context.getAuthenticator() == null) { throw new ServletException("no authenticator"); } context.getAuthenticator().login(username, password, this); } /** * {@inheritDoc} */ @Override public void logout() throws ServletException { context.getAuthenticator().logout(this); } /** * {@inheritDoc} */ @Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; } private void parseParts() { // Return immediately if the parts have already been parsed if (parts != null || partsParseException != null) { return; } MultipartConfigElement mce = getWrapper().getMultipartConfigElement(); if (mce == null) { if(getContext().getAllowCasualMultipartParsing()) { mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize()); } else { parts = Collections.emptyList(); return; } } Parameters parameters = coyoteRequest.getParameters(); parameters.setLimit(getConnector().getMaxParameterCount()); boolean success = false; try { File location; String locationStr = mce.getLocation(); if (locationStr == null || locationStr.length() == 0) { location = ((File) context.getServletContext().getAttribute( ServletContext.TEMPDIR)); } else { // If relative, it is relative to TEMPDIR location = new File(locationStr); if (!location.isAbsolute()) { location = new File( (File) context.getServletContext().getAttribute( ServletContext.TEMPDIR), locationStr).getAbsoluteFile(); } } if (!location.isDirectory()) { partsParseException = new IOException( sm.getString("coyoteRequest.uploadLocationInvalid", location)); return; } // Create a new file upload handler DiskFileItemFactory factory = new DiskFileItemFactory(); try { factory.setRepository(location.getCanonicalFile()); } catch (IOException ioe) { partsParseException = ioe; return; } factory.setSizeThreshold(mce.getFileSizeThreshold()); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); upload.setFileSizeMax(mce.getMaxFileSize()); upload.setSizeMax(mce.getMaxRequestSize()); parts = new ArrayList<>(); try { List<FileItem> items = upload.parseRequest(new ServletRequestContext(this)); int maxPostSize = getConnector().getMaxPostSize(); int postSize = 0; String enc = getCharacterEncoding(); Charset charset = null; if (enc != null) { try { charset = B2CConverter.getCharset(enc); } catch (UnsupportedEncodingException e) { // Ignore } } for (FileItem item : items) { ApplicationPart part = new ApplicationPart(item, mce); parts.add(part); if (part.getSubmittedFileName() == null) { String name = part.getName(); String value = null; try { String encoding = parameters.getEncoding(); if (encoding == null) { encoding = Parameters.DEFAULT_ENCODING; } value = part.getString(encoding); } catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } } if (maxPostSize > 0) { // Have to calculate equivalent size. Not completely // accurate but close enough. if (charset == null) { // Name length postSize += name.getBytes().length; } else { postSize += name.getBytes(charset).length; } if (value != null) { // Equals sign postSize++; // Value length postSize += part.getSize(); } // Value separator postSize++; if (postSize > maxPostSize) { throw new IllegalStateException(sm.getString( "coyoteRequest.maxPostSizeExceeded")); } } parameters.addParameter(name, value); } } success = true; } catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); } catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); } catch (FileUploadException e) { partsParseException = new IOException(e); } catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; } } finally { if (partsParseException != null || !success) { parameters.setParseFailed(true); } } } /** * {@inheritDoc} */ @Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; } // ------------------------------------------------------ Protected Methods protected Session doGetSession(boolean create) { // There cannot be a session if no context has been assigned yet if (context == null) { return (null); } // Return the current session if it exists and is valid if ((session != null) && !session.isValid()) { session = null; } if (session != null) { return (session); } // Return the requested session if it exists and is valid Manager manager = null; if (context != null) { manager = context.getManager(); } if (manager == null) { return (null); // Sessions are not supported } if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) { session = null; } if (session != null) { session.access(); return (session); } } // Create a new session if requested and the response is not committed if (!create) { return (null); } if ((context != null) && (response != null) && context.getServletContext().getEffectiveSessionTrackingModes(). contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) { throw new IllegalStateException (sm.getString("coyoteRequest.sessionCreateCommitted")); } // Attempt to reuse session id if one was submitted in a cookie // Do not reuse the session id if it is from a URL, to prevent possible // phishing attacks // Use the SSL session ID if one is present. if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie()) || requestedSessionSSL ) { session = manager.createSession(getRequestedSessionId()); } else { session = manager.createSession(null); } // Creating a new session cookie based on that session if ((session != null) && (getContext() != null) && getContext().getServletContext(). getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } if (session == null) { return null; } session.access(); return session; } protected String unescape(String s) { if (s==null) { return null; } if (s.indexOf('\\') == -1) { return s; } StringBuilder buf = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c!='\\') { buf.append(c); } else { if (++i >= s.length()) { throw new IllegalArgumentException();//invalid escape, hence invalid cookie } c = s.charAt(i); buf.append(c); } } return buf.toString(); } /** * Parse cookies. */ protected void parseCookies() { cookiesParsed = true; Cookies serverCookies = coyoteRequest.getCookies(); int count = serverCookies.getCookieCount(); if (count <= 0) { return; } cookies = new Cookie[count]; int idx=0; for (int i = 0; i < count; i++) { ServerCookie scookie = serverCookies.getCookie(i); try { /* we must unescape the '\\' escape character */ Cookie cookie = new Cookie(scookie.getName().toString(),null); int version = scookie.getVersion(); cookie.setVersion(version); cookie.setValue(unescape(scookie.getValue().toString())); cookie.setPath(unescape(scookie.getPath().toString())); String domain = scookie.getDomain().toString(); if (domain!=null) { cookie.setDomain(unescape(domain));//avoid NPE } String comment = scookie.getComment().toString(); cookie.setComment(version==1?unescape(comment):null); cookies[idx++] = cookie; } catch(IllegalArgumentException e) { // Ignore bad cookie } } if( idx < count ) { Cookie [] ncookies = new Cookie[idx]; System.arraycopy(cookies, 0, ncookies, 0, idx); cookies = ncookies; } } /** * Parse request parameters. */ protected void parseParameters() { parametersParsed = true; Parameters parameters = coyoteRequest.getParameters(); boolean success = false; try { // Set this every time in case limit has been changed via JMX parameters.setLimit(getConnector().getMaxParameterCount()); // getCharacterEncoding() may have been overridden to search for // hidden form field containing request encoding String enc = getCharacterEncoding(); boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI(); if (enc != null) { parameters.setEncoding(enc); if (useBodyEncodingForURI) { parameters.setQueryStringEncoding(enc); } } else { parameters.setEncoding (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); if (useBodyEncodingForURI) { parameters.setQueryStringEncoding (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); } } parameters.handleQueryParameters(); if (usingInputStream || usingReader) { success = true; return; } if( !getConnector().isParseBodyMethod(getMethod()) ) { success = true; return; } String contentType = getContentType(); if (contentType == null) { contentType = ""; } int semicolon = contentType.indexOf(';'); if (semicolon >= 0) { contentType = contentType.substring(0, semicolon).trim(); } else { contentType = contentType.trim(); } if ("multipart/form-data".equals(contentType)) { parseParts(); success = true; return; } if (!("application/x-www-form-urlencoded".equals(contentType))) { success = true; return; } int len = getContentLength(); if (len > 0) { int maxPostSize = connector.getMaxPostSize(); if ((maxPostSize > 0) && (len > maxPostSize)) { if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.postTooLarge")); } checkSwallowInput(); return; } byte[] formData = null; if (len < CACHED_POST_LEN) { if (postData == null) { postData = new byte[CACHED_POST_LEN]; } formData = postData; } else { formData = new byte[len]; } try { if (readPostBody(formData, len) != len) { return; } } catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; } parameters.processParameters(formData, 0, len); } else if ("chunked".equalsIgnoreCase( coyoteRequest.getHeader("transfer-encoding"))) { byte[] formData = null; try { formData = readChunkedPostBody(); } catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; } if (formData != null) { parameters.processParameters(formData, 0, formData.length); } } success = true; } finally { if (!success) { parameters.setParseFailed(true); } } } /** * Read post body in an array. */ protected int readPostBody(byte body[], int len) throws IOException { int offset = 0; do { int inputLen = getStream().read(body, offset, len - offset); if (inputLen <= 0) { return offset; } offset += inputLen; } while ((len - offset) > 0); return len; } /** * Read chunked post body. */ protected byte[] readChunkedPostBody() throws IOException { ByteChunk body = new ByteChunk(); byte[] buffer = new byte[CACHED_POST_LEN]; int len = 0; while (len > -1) { len = getStream().read(buffer, 0, CACHED_POST_LEN); if (connector.getMaxPostSize() > 0 && (body.getLength() + len) > connector.getMaxPostSize()) { // Too much data checkSwallowInput(); throw new IOException( sm.getString("coyoteRequest.chunkedPostTooLarge")); } if (len > 0) { body.append(buffer, 0, len); } } if (body.getLength() == 0) { return null; } if (body.getLength() < body.getBuffer().length) { int length = body.getLength(); byte[] result = new byte[length]; System.arraycopy(body.getBuffer(), 0, result, 0, length); return result; } return body.getBuffer(); } /** * Parse request locales. */ protected void parseLocales() { localesParsed = true; Enumeration<String> values = getHeaders("accept-language"); while (values.hasMoreElements()) { String value = values.nextElement(); parseLocalesHeader(value); } } /** * Parse accept-language header value. */ protected void parseLocalesHeader(String value) { // Store the accumulated languages that have been requested in // a local collection, sorted by the quality value (so we can // add Locales in descending order). The values will be ArrayLists // containing the corresponding Locales to be added TreeMap<Double, ArrayList<Locale>> locales = new TreeMap<>(); // Preprocess the value to remove all whitespace int white = value.indexOf(' '); if (white < 0) { white = value.indexOf('\t'); } if (white >= 0) { StringBuilder sb = new StringBuilder(); int len = value.length(); for (int i = 0; i < len; i++) { char ch = value.charAt(i); if ((ch != ' ') && (ch != '\t')) { sb.append(ch); } } parser.setString(sb.toString()); } else { parser.setString(value); } // Process each comma-delimited language specification int length = parser.getLength(); while (true) { // Extract the next comma-delimited entry int start = parser.getIndex(); if (start >= length) { break; } int end = parser.findChar(','); String entry = parser.extract(start, end).trim(); parser.advance(); // For the following entry // Extract the quality factor for this entry double quality = 1.0; int semi = entry.indexOf(";q="); if (semi >= 0) { try { String strQuality = entry.substring(semi + 3); if (strQuality.length() <= 5) { quality = Double.parseDouble(strQuality); } else { quality = 0.0; } } catch (NumberFormatException e) { quality = 0.0; } entry = entry.substring(0, semi); } // Skip entries we are not going to keep track of if (quality < 0.00005) { continue; // Zero (or effectively zero) quality factors } if ("*".equals(entry)) { continue; // FIXME - "*" entries are not handled } // Extract the language and country for this entry String language = null; String country = null; String variant = null; int dash = entry.indexOf('-'); if (dash < 0) { language = entry; country = ""; variant = ""; } else { language = entry.substring(0, dash); country = entry.substring(dash + 1); int vDash = country.indexOf('-'); if (vDash > 0) { String cTemp = country.substring(0, vDash); variant = country.substring(vDash + 1); country = cTemp; } else { variant = ""; } } if (!isAlpha(language) || !isAlpha(country) || !isAlpha(variant)) { continue; } // Add a new Locale to the list of Locales for this quality level Locale locale = new Locale(language, country, variant); Double key = new Double(-quality); // Reverse the order ArrayList<Locale> values = locales.get(key); if (values == null) { values = new ArrayList<>(); locales.put(key, values); } values.add(locale); } // Process the quality values in highest->lowest order (due to // negating the Double value when creating the key) for (ArrayList<Locale> list : locales.values()) { for (Locale locale : list) { addLocale(locale); } } } protected static final boolean isAlpha(String value) { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { return false; } } return true; } // ----------------------------------------------------- Special attributes handling private static interface SpecialAttributeAdapter { Object get(Request request, String name); void set(Request request, String name, Object value); // None of special attributes support removal // void remove(Request request, String name); } private static final Map<String, SpecialAttributeAdapter> specialAttributes = new HashMap<>(); static { specialAttributes.put(Globals.DISPATCHER_TYPE_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return (request.internalDispatcherType == null) ? DispatcherType.REQUEST : request.internalDispatcherType; } @Override public void set(Request request, String name, Object value) { request.internalDispatcherType = (DispatcherType) value; } }); specialAttributes.put(Globals.DISPATCHER_REQUEST_PATH_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return (request.requestDispatcherPath == null) ? request .getRequestPathMB().toString() : request.requestDispatcherPath.toString(); } @Override public void set(Request request, String name, Object value) { request.requestDispatcherPath = value; } }); specialAttributes.put(Globals.ASYNC_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return request.asyncSupported; } @Override public void set(Request request, String name, Object value) { Boolean oldValue = request.asyncSupported; request.asyncSupported = (Boolean)value; request.notifyAttributeAssigned(name, value, oldValue); } }); specialAttributes.put(Globals.GSS_CREDENTIAL_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { if (request.userPrincipal instanceof TomcatPrincipal) { return ((TomcatPrincipal) request.userPrincipal) .getGssCredential(); } return null; } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.PARAMETER_PARSE_FAILED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { if (request.getCoyoteRequest().getParameters() .isParseFailed()) { return Boolean.TRUE; } return null; } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.COMET_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return Boolean.valueOf( request.getConnector().getProtocolHandler( ).isCometSupported()); } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.COMET_TIMEOUT_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return Boolean.valueOf( request.getConnector().getProtocolHandler( ).isCometTimeoutSupported()); } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.SENDFILE_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return Boolean.valueOf( request.getConnector().getProtocolHandler( ).isSendfileSupported()); } @Override public void set(Request request, String name, Object value) { // NO-OP } }); } }
54,984
Bug 54984 multipart/form-data is not always read with correct encoding
The bug occurs when form data is posted as multipart/form-data and using Servlet 3 API to get posted files. In a servlet, if we set the encoding: request.setCharacterEncoding("UTF-8"); Then invoke: request.getParts() And then invoke: String text = request.getParameter("sometextfield"); UTF-8 characters in the text have been garbled. Order of method calls are significant, if a getParameter is called before getParts, the correct encoding will be used. However, the order which you invoke the methods should not matter.
resolved fixed
7558546
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-24T17:46:27Z
2013-05-16T16:00:00Z
test/org/apache/catalina/connector/TestRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.connector; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.util.Enumeration; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.authenticator.BasicAuthenticator; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.deploy.FilterMap; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.filters.FailedRequestFilter; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.TestTomcat.MapRealm; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; /** * Test case for {@link Request}. */ public class TestRequest extends TomcatBaseTest { /** * Test case for https://issues.apache.org/bugzilla/show_bug.cgi?id=37794 * POST parameters are not returned from a call to * any of the {@link HttpServletRequest} getParameterXXX() methods if the * request is chunked. */ @Test public void testBug37794() { Bug37794Client client = new Bug37794Client(true); // Edge cases around zero client.doRequest(-1, false); // Unlimited assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); client.reset(); client.doRequest(0, false); // Unlimited assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); client.reset(); client.doRequest(1, false); // 1 byte - too small should fail assertTrue(client.isResponse400()); client.reset(); // Edge cases around actual content length client.reset(); client.doRequest(6, false); // Too small should fail assertTrue(client.isResponse400()); client.reset(); client.doRequest(7, false); // Just enough should pass assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); client.reset(); client.doRequest(8, false); // 1 extra - should pass assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); // Much larger client.reset(); client.doRequest(8096, false); // Plenty of space - should pass assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); // Check for case insensitivity client.reset(); client.doRequest(8096, true); // Plenty of space - should pass assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); } /** * Additional test for failed requests handling when no FailedRequestFilter * is defined. */ @Test public void testBug37794withoutFilter() { Bug37794Client client = new Bug37794Client(false); // Edge cases around actual content length client.reset(); client.doRequest(6, false); // Too small should fail // Response code will be OK, but parameters list will be empty assertTrue(client.isResponse200()); assertEquals("", client.getResponseBody()); } private static class Bug37794Servlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Only interested in the parameters and values for POST requests. */ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the parameters and values back as plain text resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); // Assume one value per attribute Enumeration<String> names = req.getParameterNames(); while (names.hasMoreElements()) { String name = names.nextElement(); out.println(name + "=" + req.getParameter(name)); } } } /** * Bug 37794 test client. */ private class Bug37794Client extends SimpleHttpClient { private final boolean createFilter; private boolean init; public Bug37794Client(boolean createFilter) { this.createFilter = createFilter; } private synchronized void init() throws Exception { if (init) return; Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet()); root.addServletMapping("/test", "Bug37794"); if (createFilter) { FilterDef failedRequestFilter = new FilterDef(); failedRequestFilter.setFilterName("failedRequestFilter"); failedRequestFilter.setFilterClass( FailedRequestFilter.class.getName()); FilterMap failedRequestFilterMap = new FilterMap(); failedRequestFilterMap.setFilterName("failedRequestFilter"); failedRequestFilterMap.addURLPattern("/*"); root.addFilterDef(failedRequestFilter); root.addFilterMap(failedRequestFilterMap); } tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); init = true; } private Exception doRequest(int postLimit, boolean ucChunkedHead) { Tomcat tomcat = getTomcatInstance(); try { init(); tomcat.getConnector().setMaxPostSize(postLimit); // Open connection connect(); // Send request in two parts String[] request = new String[2]; if (ucChunkedHead) { request[0] = "POST http://localhost:8080/test HTTP/1.1" + CRLF + "content-type: application/x-www-form-urlencoded" + CRLF + "Transfer-Encoding: CHUNKED" + CRLF + "Connection: close" + CRLF + CRLF + "3" + CRLF + "a=1" + CRLF; } else { request[0] = "POST http://localhost:8080/test HTTP/1.1" + CRLF + "content-type: application/x-www-form-urlencoded" + CRLF + "Transfer-Encoding: chunked" + CRLF + "Connection: close" + CRLF + CRLF + "3" + CRLF + "a=1" + CRLF; } request[1] = "4" + CRLF + "&b=2" + CRLF + "0" + CRLF + CRLF; setRequest(request); processRequest(); // blocks until response has been read // Close the connection disconnect(); } catch (Exception e) { return e; } return null; } @Override public boolean isResponseBodyOK() { if (getResponseBody() == null) { return false; } if (!getResponseBody().contains("a=1")) { return false; } if (!getResponseBody().contains("b=2")) { return false; } return true; } } /** * Test case for * <a href="https://issues.apache.org/bugzilla/show_bug.cgi?id=38113">bug * 38118</a>. */ @Test public void testBug38113() throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); // Add the Servlet Tomcat.addServlet(ctx, "servlet", new EchoQueryStringServlet()); ctx.addServletMapping("/", "servlet"); tomcat.start(); // No query string ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); assertEquals("QueryString=null", res.toString()); // Query string res = getUrl("http://localhost:" + getPort() + "/?a=b"); assertEquals("QueryString=a=b", res.toString()); // Empty string res = getUrl("http://localhost:" + getPort() + "/?"); assertEquals("QueryString=", res.toString()); } private static final class EchoQueryStringServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); PrintWriter pw = resp.getWriter(); pw.print("QueryString=" + req.getQueryString()); } } /** * Test case for {@link Request#login(String, String)} and * {@link Request#logout()}. */ @Test public void testLoginLogout() throws Exception{ // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); LoginConfig config = new LoginConfig(); config.setAuthMethod("BASIC"); ctx.setLoginConfig(config); ctx.getPipeline().addValve(new BasicAuthenticator()); Tomcat.addServlet(ctx, "servlet", new LoginLogoutServlet()); ctx.addServletMapping("/", "servlet"); MapRealm realm = new MapRealm(); realm.addUser(LoginLogoutServlet.USER, LoginLogoutServlet.PWD); ctx.setRealm(realm); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); assertEquals(LoginLogoutServlet.OK, res.toString()); } private static final class LoginLogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String USER = "user"; private static final String PWD = "pwd"; private static final String OK = "OK"; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.login(USER, PWD); if (!req.getRemoteUser().equals(USER)) throw new ServletException(); if (!req.getUserPrincipal().getName().equals(USER)) throw new ServletException(); req.logout(); if (req.getRemoteUser() != null) throw new ServletException(); if (req.getUserPrincipal() != null) throw new ServletException(); resp.getWriter().write(OK); } } @Test public void testBug49424NoChunking() throws Exception { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet()); root.addServletMapping("/", "Bug37794"); tomcat.start(); HttpURLConnection conn = getConnection(); InputStream is = conn.getInputStream(); assertNotNull(is); } @Test public void testBug49424WithChunking() throws Exception { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet()); root.addServletMapping("/", "Bug37794"); tomcat.start(); HttpURLConnection conn = getConnection(); conn.setChunkedStreamingMode(8 * 1024); InputStream is = conn.getInputStream(); assertNotNull(is); } /** * Test case for https://issues.apache.org/bugzilla/show_bug.cgi?id=48692 * PUT requests should be able to fetch request parameters coming from * the request body (when properly configured using the new parseBodyMethod * setting). */ @Test public void testBug48692() { Bug48692Client client = new Bug48692Client(); // Make sure GET works properly client.doRequest("GET", "foo=bar", null, null, false); assertTrue("Non-200 response for GET request", client.isResponse200()); assertEquals("Incorrect response for GET request", "foo=bar", client.getResponseBody()); client.reset(); // // Make sure POST works properly // // POST with separate GET and POST parameters client.doRequest("POST", "foo=bar", "application/x-www-form-urlencoded", "bar=baz", true); assertTrue("Non-200 response for POST request", client.isResponse200()); assertEquals("Incorrect response for POST request", "bar=baz,foo=bar", client.getResponseBody()); client.reset(); // POST with overlapping GET and POST parameters client.doRequest("POST", "foo=bar&bar=foo", "application/x-www-form-urlencoded", "bar=baz&foo=baz", true); assertTrue("Non-200 response for POST request", client.isResponse200()); assertEquals("Incorrect response for POST request", "bar=baz,bar=foo,foo=bar,foo=baz", client.getResponseBody()); client.reset(); // PUT without POST-style parsing client.doRequest("PUT", "foo=bar&bar=foo", "application/x-www-form-urlencoded", "bar=baz&foo=baz", false); assertTrue("Non-200 response for PUT/noparse request", client.isResponse200()); assertEquals("Incorrect response for PUT request", "bar=foo,foo=bar", client.getResponseBody()); client.reset(); // PUT with POST-style parsing client.doRequest("PUT", "foo=bar&bar=foo", "application/x-www-form-urlencoded", "bar=baz&foo=baz", true); assertTrue("Non-200 response for PUT request", client.isResponse200()); assertEquals("Incorrect response for PUT/parse request", "bar=baz,bar=foo,foo=bar,foo=baz", client.getResponseBody()); client.reset(); /* private Exception doRequest(String method, String queryString, String contentType, String requestBody, boolean allowBody) { */ } /** * */ private static class EchoParametersServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Only interested in the parameters and values for requests. * Note: echos parameters in alphabetical order. */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the parameters and values back as plain text resp.setContentType("text/plain"); resp.setCharacterEncoding("UTF-8"); PrintWriter out = resp.getWriter(); TreeMap<String,String[]> parameters = new TreeMap<>(req.getParameterMap()); boolean first = true; for(String name: parameters.keySet()) { String[] values = req.getParameterValues(name); java.util.Arrays.sort(values); for(int i=0; i<values.length; ++i) { if(first) first = false; else out.print(","); out.print(name + "=" + values[i]); } } } } /** * Bug 48692 test client: test for allowing PUT request bodies. */ private class Bug48692Client extends SimpleHttpClient { private boolean init; private synchronized void init() throws Exception { if (init) return; Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(root, "EchoParameters", new EchoParametersServlet()); root.addServletMapping("/echo", "EchoParameters"); tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); init = true; } private Exception doRequest(String method, String queryString, String contentType, String requestBody, boolean allowBody) { Tomcat tomcat = getTomcatInstance(); try { init(); if(allowBody) tomcat.getConnector().setParseBodyMethods(method); else tomcat.getConnector().setParseBodyMethods(""); // never parse // Open connection connect(); // Re-encode the request body so that bytes = characters if(null != requestBody) requestBody = new String(requestBody.getBytes("UTF-8"), "ASCII"); // Send specified request body using method String[] request = { ( method + " http://localhost:" + getPort() + "/echo" + (null == queryString ? "" : ("?" + queryString)) + " HTTP/1.1" + CRLF + "Host: localhost" + CRLF + (null == contentType ? "" : ("Content-Type: " + contentType + CRLF)) + "Connection: close" + CRLF + (null == requestBody ? "" : "Content-Length: " + requestBody.length() + CRLF) + CRLF + (null == requestBody ? "" : requestBody) ) }; setRequest(request); processRequest(); // blocks until response has been read // Close the connection disconnect(); } catch (Exception e) { return e; } return null; } @Override public boolean isResponseBodyOK() { return false; // Don't care } } private HttpURLConnection getConnection() throws IOException { final String query = "http://localhost:" + getPort() + "/"; URL postURL; postURL = new URL(query); HttpURLConnection conn = (HttpURLConnection) postURL.openConnection(); conn.setRequestMethod("POST"); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setAllowUserInteraction(false); return conn; } }
55,019
Bug 55019 <jsp:include page="blabla" flush="true"/> failed to compile under security manager
null
resolved fixed
76a7098
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-27T15:15:32Z
2013-05-27T15:53:20Z
java/org/apache/coyote/http11/AbstractOutputBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.IOException; import java.nio.ByteBuffer; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Iterator; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.coyote.ActionCode; import org.apache.coyote.OutputBuffer; import org.apache.coyote.Response; import org.apache.coyote.http11.filters.GzipOutputFilter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.HttpMessages; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractOutputBuffer<S> implements OutputBuffer { // ----------------------------------------------------- Instance Variables /** * Associated Coyote response. */ protected Response response; /** * Committed flag. */ protected boolean committed; /** * Finished flag. */ protected boolean finished; /** * The buffer used for header composition. */ protected byte[] headerBuffer; /** * Position in the buffer. */ protected int pos; /** * Filter library. * Note: Filter[0] is always the "chunked" filter. */ protected OutputFilter[] filterLibrary; /** * Active filter (which is actually the top of the pipeline). */ protected OutputFilter[] activeFilters; /** * Index of the last active filter. */ protected int lastActiveFilter; /** * Underlying output buffer. */ protected OutputBuffer outputStreamOutputBuffer; /** * Bytes written to client for the current request */ protected long byteCount = 0; /** * Socket buffering. */ protected int socketBuffer = -1; /** * For "non-blocking" writes use an external set of buffers. Although the * API only allows one non-blocking write at a time, due to buffering and * the possible need to write HTTP headers, there may be more than one write * to the OutputBuffer. */ protected final LinkedBlockingDeque<ByteBufferHolder> bufferedWrites = new LinkedBlockingDeque<>(); /** * The max size of the buffered write buffer */ protected int bufferedWriteSize = 64*1024; //64k default write buffer // -------------------------------------------------------------- Variables /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Logger. */ private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(AbstractOutputBuffer.class); // ------------------------------------------------------------- Properties /** * Add an output filter to the filter library. */ public void addFilter(OutputFilter filter) { OutputFilter[] newFilterLibrary = new OutputFilter[filterLibrary.length + 1]; for (int i = 0; i < filterLibrary.length; i++) { newFilterLibrary[i] = filterLibrary[i]; } newFilterLibrary[filterLibrary.length] = filter; filterLibrary = newFilterLibrary; activeFilters = new OutputFilter[filterLibrary.length]; } /** * Get filters. */ public OutputFilter[] getFilters() { return filterLibrary; } /** * Add an output filter to the filter library. */ public void addActiveFilter(OutputFilter filter) { if (lastActiveFilter == -1) { filter.setBuffer(outputStreamOutputBuffer); } else { for (int i = 0; i <= lastActiveFilter; i++) { if (activeFilters[i] == filter) return; } filter.setBuffer(activeFilters[lastActiveFilter]); } activeFilters[++lastActiveFilter] = filter; filter.setResponse(response); } /** * Set the socket buffer flag. */ public void setSocketBuffer(int socketBuffer) { this.socketBuffer = socketBuffer; } /** * Get the socket buffer flag. */ public int getSocketBuffer() { return socketBuffer; } public void setBufferedWriteSize(int bufferedWriteSize) { this.bufferedWriteSize = bufferedWriteSize; } public int getBufferedWriteSize() { return bufferedWriteSize; } // --------------------------------------------------- OutputBuffer Methods /** * Write the contents of a byte chunk. * * @param chunk byte chunk * @return number of bytes written * @throws IOException an underlying I/O error occurred */ @Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeaders) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (lastActiveFilter == -1) return outputStreamOutputBuffer.doWrite(chunk, res); else return activeFilters[lastActiveFilter].doWrite(chunk, res); } @Override public long getBytesWritten() { if (lastActiveFilter == -1) { return outputStreamOutputBuffer.getBytesWritten(); } else { return activeFilters[lastActiveFilter].getBytesWritten(); } } // --------------------------------------------------------- Public Methods /** * Flush the response. * * @throws IOException an underlying I/O error occurred */ public void flush() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } // go through the filters and if there is gzip filter // invoke it to flush for (int i = 0; i <= lastActiveFilter; i++) { if (activeFilters[i] instanceof GzipOutputFilter) { if (log.isDebugEnabled()) { log.debug("Flushing the gzip filter at position " + i + " of the filter chain..."); } ((GzipOutputFilter) activeFilters[i]).flush(); break; } } // Flush the current buffer(s) flushBuffer(isBlocking()); } /** * Reset current response. * * @throws IllegalStateException if the response has already been committed */ public void reset() { if (committed) { throw new IllegalStateException(sm.getString("iob.illegalreset")); } // Recycle Request object response.recycle(); // These will need to be reset if the reset was triggered by the error // handling if the headers were too large pos = 0; byteCount = 0; } /** * Recycle the output buffer. This should be called when closing the * connection. */ public void recycle() { // Sub-classes may wish to do more than this. nextRequest(); bufferedWrites.clear(); } /** * 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 for (int i = 0; i <= lastActiveFilter; i++) { activeFilters[i].recycle(); } // Recycle response object response.recycle(); // Reset pointers pos = 0; lastActiveFilter = -1; committed = false; finished = false; byteCount = 0; } /** * End request. * * @throws IOException an underlying I/O error occurred */ public void endRequest() throws IOException { if (!committed) { // Send the connector a request for commit. The connector should // then validate the headers, send them (using sendHeader) and // set the filters accordingly. response.action(ActionCode.COMMIT, null); } if (finished) return; if (lastActiveFilter != -1) activeFilters[lastActiveFilter].end(); flushBuffer(true); finished = true; } public abstract void init(SocketWrapper<S> socketWrapper, AbstractEndpoint endpoint) throws IOException; public abstract void sendAck() throws IOException; protected abstract void commit() throws IOException; /** * Send the response status line. */ public void sendStatus() { // Write protocol name write(Constants.HTTP_11_BYTES); headerBuffer[pos++] = Constants.SP; // 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); } headerBuffer[pos++] = Constants.SP; // Write message String message = null; if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER && HttpMessages.isSafeInHttpHeader(response.getMessage())) { message = response.getMessage(); } if (message == null) { write(HttpMessages.getMessage(status)); } else { write(message); } // End the response status line if (org.apache.coyote.Constants.IS_SECURITY_ENABLED){ AccessController.doPrivileged( new PrivilegedAction<Void>(){ @Override public Void run(){ headerBuffer[pos++] = Constants.CR; headerBuffer[pos++] = Constants.LF; return null; } } ); } else { headerBuffer[pos++] = Constants.CR; headerBuffer[pos++] = Constants.LF; } } /** * Send a header. * * @param name Header name * @param value Header value */ public void sendHeader(MessageBytes name, MessageBytes value) { write(name); headerBuffer[pos++] = Constants.COLON; headerBuffer[pos++] = Constants.SP; write(value); headerBuffer[pos++] = Constants.CR; headerBuffer[pos++] = Constants.LF; } /** * End the header block. */ public void endHeaders() { headerBuffer[pos++] = Constants.CR; headerBuffer[pos++] = Constants.LF; } /** * 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 */ protected void write(MessageBytes mb) { if (mb.getType() == MessageBytes.T_BYTES) { ByteChunk bc = mb.getByteChunk(); write(bc); } else if (mb.getType() == MessageBytes.T_CHARS) { CharChunk cc = mb.getCharChunk(); write(cc); } else { write(mb.toString()); } } /** * 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 bc data to be written */ protected void write(ByteChunk bc) { // Writing the byte chunk to the output buffer int length = bc.getLength(); checkLengthBeforeWrite(length); System.arraycopy(bc.getBytes(), bc.getStart(), headerBuffer, pos, length); pos = pos + length; } /** * This method will write the contents of the specified char * buffer to the output stream, without filtering. This method is meant to * be used to write the response header. * * @param cc data to be written */ protected void write(CharChunk cc) { int start = cc.getStart(); int end = cc.getEnd(); checkLengthBeforeWrite(end-start); char[] cbuf = cc.getBuffer(); for (int i = start; i < end; i++) { char c = cbuf[i]; // Note: This is clearly incorrect for many strings, // but is the only consistent approach within the current // servlet framework. It must suffice until servlet output // streams properly encode their output. if (((c <= 31) && (c != 9)) || c == 127 || c > 255) { c = ' '; } headerBuffer[pos++] = (byte) c; } } /** * 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 */ public void write(byte[] b) { checkLengthBeforeWrite(b.length); // Writing the byte chunk to the output buffer System.arraycopy(b, 0, headerBuffer, pos, b.length); pos = pos + b.length; } /** * This method will write the contents of the specified String to the * output stream, without filtering. This method is meant to be used to * write the response header. * * @param s data to be written */ protected void write(String s) { if (s == null) return; // From the Tomcat 3.3 HTTP/1.0 connector int len = s.length(); checkLengthBeforeWrite(len); for (int i = 0; i < len; i++) { char c = s.charAt (i); // Note: This is clearly incorrect for many strings, // but is the only consistent approach within the current // servlet framework. It must suffice until servlet output // streams properly encode their output. if (((c <= 31) && (c != 9)) || c == 127 || c > 255) { c = ' '; } headerBuffer[pos++] = (byte) c; } } /** * This method will print the specified integer to the output stream, * without filtering. This method is meant to be used to write the * response header. * * @param i data to be written */ protected void write(int i) { write(String.valueOf(i)); } /** * Checks to see if there is enough space in the buffer to write the * requested number of bytes. */ private void checkLengthBeforeWrite(int length) { if (pos + length > headerBuffer.length) { throw new HeadersTooLargeException( sm.getString("iob.responseheadertoolarge.error")); } } //------------------------------------------------------ Non-blocking writes protected abstract boolean hasMoreDataToFlush(); /** * 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>. * @throws IOException */ protected abstract boolean flushBuffer(boolean block) throws IOException; /** * Is standard Servlet blocking IO being used for output? */ protected final boolean isBlocking() { return response.getWriteListener() == null; } protected final boolean isReady() { return !hasDataToWrite(); } public final boolean hasDataToWrite() { return hasMoreDataToFlush() || hasBufferedData(); } private boolean hasBufferedData() { boolean result = false; if (bufferedWrites!=null) { Iterator<ByteBufferHolder> iter = bufferedWrites.iterator(); while (!result && iter.hasNext()) { result = iter.next().hasData(); } } return result; } protected static class ByteBufferHolder { private final ByteBuffer buf; private final AtomicBoolean flipped; public ByteBufferHolder(ByteBuffer buf, boolean flipped) { this.buf = buf; this.flipped = new AtomicBoolean(flipped); } public ByteBuffer getBuf() { return buf; } public boolean isFlipped() { return flipped.get(); } public boolean flip() { if (flipped.compareAndSet(false, true)) { buf.flip(); return true; } else { return false; } } public boolean hasData() { if (flipped.get()) { return buf.remaining()>0; } else { return buf.position()>0; } } @Override public String toString() { StringBuilder builder = new StringBuilder(super.toString()); builder.append("[flipped="); builder.append(isFlipped()?"true, remaining=" : "false, position="); builder.append(isFlipped()? buf.remaining(): buf.position()); builder.append("]"); return builder.toString(); } } }
54,944
Bug 54944 Enhancements to TestFormAuthenticator
null
resolved fixed
0de078e
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T10:53:41Z
2013-05-09T17:20:00Z
test/org/apache/catalina/authenticator/TestFormAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.io.File; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.TestTomcat.MapRealm; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.websocket.server.WsListener; public class TestFormAuthenticator extends TomcatBaseTest { @Test public void testGet() throws Exception { doTest("GET", "GET", false); } @Test public void testPostNoContinue() throws Exception { doTest("POST", "GET", false); } @Test public void testPostWithContinue() throws Exception { doTest("POST", "GET", true); } // Bug 49779 @Test public void testPostNoContinuePostRedirect() throws Exception { doTest("POST", "POST", false); } // Bug 49779 @Test public void testPostWithContinuePostRedirect() throws Exception { doTest("POST", "POST", true); } private void doTest(String resourceMethod, String redirectMethod, boolean useContinue) throws Exception { FormAuthClient client = new FormAuthClient(); // First request for authenticated resource client.setUseContinue(useContinue); client.doResourceRequest(resourceMethod); assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); client.reset(); // Second request for the login page client.setUseContinue(useContinue); client.doLoginRequest(); assertTrue(client.isResponse302()); assertTrue(client.isResponseBodyOK()); client.reset(); // Third request - follow the redirect client.doResourceRequest(redirectMethod); if ("POST".equals(redirectMethod)) { client.setUseContinue(useContinue); } assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); client.reset(); // Subsequent requests - direct to the resource for (int i = 0; i < 5; i++) { client.setUseContinue(useContinue); client.doResourceRequest(resourceMethod); assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); client.reset(); } } private final class FormAuthClient extends SimpleHttpClient { private static final String LOGIN_PAGE = "j_security_check"; private String protectedPage = "index.jsp"; private String protectedLocation = "/examples/jsp/security/protected/"; private int requestCount = 0; private String sessionId = null; private FormAuthClient() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File(getBuildDirectory(), "webapps/examples"); Context ctx = tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath()); ctx.addApplicationListener(WsListener.class.getName()); MapRealm realm = new MapRealm(); realm.addUser("tomcat", "tomcat"); realm.addUserRole("tomcat", "tomcat"); ctx.setRealm(realm); tomcat.start(); // Port only known after Tomcat starts setPort(getPort()); } private void doResourceRequest(String method) throws Exception { StringBuilder requestHead = new StringBuilder(128); String requestTail; requestHead.append(method).append(" ").append(protectedLocation) .append(protectedPage); if ("GET".equals(method)) { requestHead.append("?role=bar"); } requestHead.append(" HTTP/1.1").append(CRLF); requestHead.append("Host: localhost").append(CRLF); requestHead.append("Connection: close").append(CRLF); if (getUseContinue()) { requestHead.append("Expect: 100-continue").append(CRLF); } if (sessionId != null) { requestHead.append("Cookie: JSESSIONID=").append(sessionId) .append(CRLF); } if ("POST".equals(method)) { requestHead.append( "Content-Type: application/x-www-form-urlencoded") .append(CRLF); requestHead.append("Content-length: 8").append(CRLF); requestHead.append(CRLF); requestTail = "role=bar"; } else { requestTail = CRLF; } String request[] = new String[2]; request[0] = requestHead.toString(); request[1] = requestTail; doRequest(request); } private void doLoginRequest() throws Exception { StringBuilder requestHead = new StringBuilder(128); requestHead.append("POST ").append(protectedLocation) .append(LOGIN_PAGE).append(" HTTP/1.1").append(CRLF); requestHead.append("Host: localhost").append(CRLF); requestHead.append("Connection: close").append(CRLF); if (getUseContinue()) { requestHead.append("Expect: 100-continue").append(CRLF); } if (sessionId != null) { requestHead.append("Cookie: JSESSIONID=").append(sessionId) .append(CRLF); } requestHead.append( "Content-Type: application/x-www-form-urlencoded").append( CRLF); requestHead.append("Content-length: 35").append(CRLF); requestHead.append(CRLF); String request[] = new String[2]; request[0] = requestHead.toString(); request[1] = "j_username=tomcat&j_password=tomcat"; doRequest(request); } private void doRequest(String request[]) throws Exception { setRequest(request); connect(); processRequest(); String newSessionId = getSessionId(); if (newSessionId != null) { sessionId = newSessionId; } disconnect(); requestCount++; } @Override public boolean isResponseBodyOK() { if (requestCount == 1) { // First request should result in the login page assertContains(getResponseBody(), "<title>Login Page for Examples</title>"); return true; } else if (requestCount == 2) { // Second request should result in a redirect return true; } else { // Subsequent requests should result in the protected page // The role parameter should have reached the page String body = getResponseBody(); assertContains(body, "<title>Protected Page for Examples</title>"); assertContains(body, "<input type=\"text\" name=\"role\" value=\"bar\""); return true; } } private void assertContains(String body, String expected) { if (!body.contains(expected)) { fail("Response body check failure.\n" + "Expected to contain substring: [" + expected + "]\nActual: [" + body + "]"); } } } }
54,947
Bug 54947 Http11NioProtocol generates HTTP 505 responses on valid requests if request is split across multiple packets
If an HTTP request is broken up across multiple packets *and* the first packet contains a GET request up to "\r" AND the "\n" terminating the first line of the request is included in the next packet Tomcat incorrectly throws an HTTP "505 Version Not Supported" response. This is with the Http11NioProtocol connector only - the default HTTP/1.1 connector does not exhibit this problem. An example request: Packet 1: GET / HTTP/1.1\r Packet 2: \nHost: localhost\r\n Packet 3: Connection: Close\r\n\r\n Response: HTTP/1.1 505 HTTP Version Not Supported Server: Apache-Coyote/1.1 Date: Thu, 09 May 2013 20:23:58 GMT Connection: close The following Python program reproduces the problem for me in both Tomcat 6.0.37 and Tomcat 7.0.39: """ #!/usr/bin/python import socket import time s = socket.socket() s.connect(("localhost",8080)) s.sendall("GET / HTTP/1.1\r") time.sleep(1.5) # make sure the above goes out in its own packet s.sendall("\nHost: localhost\r\n") s.sendall("Connection: close\r\n\r\n") print s.makefile().read() """ Moving the "\n" to from the second sendall to the end of the first sendall causes Tomcat to respond correctly.
resolved fixed
f763975
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T11:26:20Z
2013-05-10T01:40:00Z
java/org/apache/coyote/http11/InternalNioInputBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.EOFException; import java.io.IOException; import java.nio.channels.Selector; import java.nio.charset.Charset; import org.apache.coyote.InputBuffer; import org.apache.coyote.Request; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.NioChannel; import org.apache.tomcat.util.net.NioEndpoint; import org.apache.tomcat.util.net.NioSelectorPool; import org.apache.tomcat.util.net.SocketWrapper; /** * Implementation of InputBuffer which provides HTTP request header parsing as * well as transfer decoding. * * @author <a href="mailto:remm@apache.org">Remy Maucherat</a> * @author Filip Hanik */ public class InternalNioInputBuffer extends AbstractInputBuffer<NioChannel> { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(InternalNioInputBuffer.class); private static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1"); // -------------------------------------------------------------- Constants enum HeaderParseStatus { DONE, HAVE_MORE_HEADERS, NEED_MORE_DATA } enum HeaderParsePosition { /** * 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. */ 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. */ 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. */ 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). */ HEADER_MULTI_LINE, /** * Reading all bytes until the next CRLF. The line is being ignored. */ HEADER_SKIPLINE } // ----------------------------------------------------------- Constructors /** * Alternate constructor. */ public InternalNioInputBuffer(Request request, int headerBufferSize) { this.request = request; headers = request.getMimeHeaders(); this.headerBufferSize = headerBufferSize; inputStreamInputBuffer = new SocketInputBuffer(); filterLibrary = new InputFilter[0]; activeFilters = new InputFilter[0]; lastActiveFilter = -1; parsingHeader = true; parsingRequestLine = true; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; parsingRequestLineQPos = -1; headerParsePos = HeaderParsePosition.HEADER_START; headerData.recycle(); swallowInput = true; } /** * Parsing state - used for non blocking parsing so that * when more data arrives, we can pick up where we left off. */ private boolean parsingRequestLine; private int parsingRequestLinePhase = 0; private boolean parsingRequestLineEol = false; private int parsingRequestLineStart = 0; private int parsingRequestLineQPos = -1; private HeaderParsePosition headerParsePos; /** * Underlying socket. */ private NioChannel socket; /** * Selector pool, for blocking reads and blocking writes */ private NioSelectorPool pool; /** * Maximum allowed size of the HTTP request line plus headers plus any * leading blank lines. */ private final int headerBufferSize; /** * Known size of the NioChannel read buffer. */ private int socketReadBufferSize; // --------------------------------------------------------- Public Methods @Override public int available() { int available = super.available(); if (available>0) { return available; } available = Math.max(lastValid - pos, 0); if (available>0) { return available; } try { available = nbRead(); }catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug(sm.getString("iib.available.readFail"), ioe); } // Not ideal. This will indicate that data is available which should // trigger a read which in turn will trigger another IOException and // that one can be thrown. available = 1; } return available; } @Override public int nbRead() throws IOException { return readSocket(true,false); } /** * Recycle the input buffer. This should be called when closing the * connection. */ @Override public void recycle() { super.recycle(); socket = null; headerParsePos = HeaderParsePosition.HEADER_START; parsingRequestLine = true; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; parsingRequestLineQPos = -1; headerData.recycle(); } /** * 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. */ @Override public void nextRequest() { super.nextRequest(); headerParsePos = HeaderParsePosition.HEADER_START; parsingRequestLine = true; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; parsingRequestLineQPos = -1; headerData.recycle(); } /** * 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. * @return true if data is properly fed; false if no data is available * immediately and thread should be freed */ @Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Do a simple read with a short timeout if (!fill(true, false)) { return false; } } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; } if (parsingRequestLinePhase == 6) { // Mark the current buffer position end = 0; // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); } private void expand(int newsize) { if ( newsize > buf.length ) { if (parsingHeader) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } // Should not happen log.warn("Expanding buffer size. Old size: " + buf.length + ", new size: " + newsize, new Exception()); byte[] tmp = new byte[newsize]; System.arraycopy(buf,0,tmp,0,buf.length); buf = tmp; } } /** * Perform blocking read with a timeout if desired * @param timeout boolean - if we want to use the timeout data * @param block - true if the system should perform a blocking read, false otherwise * @return boolean - true if data was read, false is no data read, EOFException if EOF is reached * @throws IOException if a socket exception occurs * @throws EOFException if end of stream is reached */ private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } } /** * Parse the HTTP headers. */ @Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // 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 (pos > headerBufferSize || buf.length - pos < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; return true; } else { return false; } } /** * Parse an HTTP header. * * @return false after reading a blank line (which indicates that the * HTTP header parsing is done */ private HeaderParseStatus parseHeader() throws IOException { // // Check for blank line // byte chr = 0; while (headerParsePos == HeaderParsePosition.HEADER_START) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { pos++; return HeaderParseStatus.DONE; } else { break; } pos++; } if ( headerParsePos == HeaderParsePosition.HEADER_START ) { // Mark the current buffer position headerData.start = pos; headerParsePos = HeaderParsePosition.HEADER_NAME; } // // Reading the header name // Header name is always US-ASCII // while (headerParsePos == HeaderParsePosition.HEADER_NAME) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { //parse header return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.COLON) { headerParsePos = HeaderParsePosition.HEADER_VALUE_START; headerData.headerValue = headers.addValue(buf, headerData.start, pos - headerData.start); pos++; // Mark the current buffer position headerData.start = pos; headerData.realPos = pos; headerData.lastSignificantChar = pos; break; } else if (!HTTP_TOKEN_CHAR[chr]) { // If a non-token header is detected, skip the line and // ignore the header headerData.lastSignificantChar = pos; return skipLine(); } // chr is next byte of header name. Convert to lowercase. if ((chr >= Constants.A) && (chr <= Constants.Z)) { buf[pos] = (byte) (chr - Constants.LC_OFFSET); } pos++; } // Skip the line and ignore the header if (headerParsePos == HeaderParsePosition.HEADER_SKIPLINE) { return skipLine(); } // // Reading the header value (which can be spanned over multiple lines) // while (headerParsePos == HeaderParsePosition.HEADER_VALUE_START || headerParsePos == HeaderParsePosition.HEADER_VALUE || headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) { if ( headerParsePos == HeaderParsePosition.HEADER_VALUE_START ) { // Skipping spaces while (true) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE_START return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.SP || chr == Constants.HT) { pos++; } else { headerParsePos = HeaderParsePosition.HEADER_VALUE; break; } } } if ( headerParsePos == HeaderParsePosition.HEADER_VALUE ) { // Reading bytes until the end of the line boolean eol = false; while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP || chr == Constants.HT) { buf[headerData.realPos] = chr; headerData.realPos++; } else { buf[headerData.realPos] = chr; headerData.realPos++; headerData.lastSignificantChar = headerData.realPos; } pos++; } // Ignore whitespaces at the end of the line headerData.realPos = headerData.lastSignificantChar; // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header headerParsePos = HeaderParsePosition.HEADER_MULTI_LINE; } // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_MULTI_LINE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if ( headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE ) { if ( (chr != Constants.SP) && (chr != Constants.HT)) { headerParsePos = HeaderParsePosition.HEADER_START; break; } else { // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) buf[headerData.realPos] = chr; headerData.realPos++; headerParsePos = HeaderParsePosition.HEADER_VALUE_START; } } } // Set the header value headerData.headerValue.setBytes(buf, headerData.start, headerData.lastSignificantChar - headerData.start); headerData.recycle(); return HeaderParseStatus.HAVE_MORE_HEADERS; } public int getParsingRequestLinePhase() { return parsingRequestLinePhase; } private HeaderParseStatus skipLine() throws IOException { headerParsePos = HeaderParsePosition.HEADER_SKIPLINE; boolean eol = false; // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { return HeaderParseStatus.NEED_MORE_DATA; } } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { headerData.lastSignificantChar = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, headerData.start, headerData.lastSignificantChar - headerData.start + 1, DEFAULT_CHARSET))); } headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.HAVE_MORE_HEADERS; } private final HeaderParseData headerData = new HeaderParseData(); public static class HeaderParseData { /** * When parsing header name: first character of the header.<br /> * When skipping broken header line: first character of the header.<br /> * When parsing header value: first character after ':'. */ int start = 0; /** * 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 /> */ int realPos = 0; /** * When parsing header name: not used (stays as 0).<br /> * When skipping broken header line: last non-CR/non-LF character.<br /> * When parsing header value: position after the last not-LWS character.<br /> */ 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. */ MessageBytes headerValue = null; public void recycle() { start = 0; realPos = 0; lastSignificantChar = 0; headerValue = null; } } // ------------------------------------------------------ Protected Methods @Override protected void init(SocketWrapper<NioChannel> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket(); if (socket == null) { // Socket has been closed in another thread throw new IOException(sm.getString("iib.socketClosed")); } socketReadBufferSize = socket.getBufHandler().getReadBuffer().capacity(); int bufLength = headerBufferSize + socketReadBufferSize; if (buf == null || buf.length < bufLength) { buf = new byte[bufLength]; } pool = ((NioEndpoint)endpoint).getSelectorPool(); } @Override protected boolean fill(boolean block) throws IOException, EOFException { return fill(true,block); } protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid > headerBufferSize) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; } // ------------------------------------- InputStreamInputBuffer Inner Class /** * This class is an input buffer which will read its data from an input * stream. */ protected class SocketInputBuffer implements InputBuffer { /** * Read bytes into the specified chunk. */ @Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill(true,true)) //read body, must be blocking, as the thread is inside the app return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); } } }
54,947
Bug 54947 Http11NioProtocol generates HTTP 505 responses on valid requests if request is split across multiple packets
If an HTTP request is broken up across multiple packets *and* the first packet contains a GET request up to "\r" AND the "\n" terminating the first line of the request is included in the next packet Tomcat incorrectly throws an HTTP "505 Version Not Supported" response. This is with the Http11NioProtocol connector only - the default HTTP/1.1 connector does not exhibit this problem. An example request: Packet 1: GET / HTTP/1.1\r Packet 2: \nHost: localhost\r\n Packet 3: Connection: Close\r\n\r\n Response: HTTP/1.1 505 HTTP Version Not Supported Server: Apache-Coyote/1.1 Date: Thu, 09 May 2013 20:23:58 GMT Connection: close The following Python program reproduces the problem for me in both Tomcat 6.0.37 and Tomcat 7.0.39: """ #!/usr/bin/python import socket import time s = socket.socket() s.connect(("localhost",8080)) s.sendall("GET / HTTP/1.1\r") time.sleep(1.5) # make sure the above goes out in its own packet s.sendall("\nHost: localhost\r\n") s.sendall("Connection: close\r\n\r\n") print s.makefile().read() """ Moving the "\n" to from the second sendall to the end of the first sendall causes Tomcat to respond correctly.
resolved fixed
f763975
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T11:26:20Z
2013-05-10T01:40:00Z
test/org/apache/catalina/startup/SimpleHttpClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.startup; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.io.Writer; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.Locale; /** * Simple client for unit testing. It isn't robust, it isn't secure and * should not be used as the basis for production code. Its only purpose * is to do the bare minimum for the unit tests. */ public abstract class SimpleHttpClient { public static final String TEMP_DIR = System.getProperty("java.io.tmpdir"); public static final String CRLF = "\r\n"; public static final String INFO_100 = "HTTP/1.1 100"; public static final String OK_200 = "HTTP/1.1 200"; public static final String REDIRECT_302 = "HTTP/1.1 302"; public static final String FAIL_400 = "HTTP/1.1 400"; public static final String FAIL_404 = "HTTP/1.1 404"; public static final String TIMEOUT_408 = "HTTP/1.1 408"; public static final String FAIL_413 = "HTTP/1.1 413"; public static final String FAIL_50X = "HTTP/1.1 50"; public static final String FAIL_500 = "HTTP/1.1 500"; public static final String FAIL_501 = "HTTP/1.1 501"; private static final String CONTENT_LENGTH_HEADER_PREFIX = "Content-Length: "; protected static final String SESSION_COOKIE_NAME = "JSESSIONID"; protected static final String SESSION_PARAMETER_NAME = SESSION_COOKIE_NAME.toLowerCase(Locale.ENGLISH); private static final String COOKIE_HEADER_PREFIX = "Set-Cookie: "; private static final String SESSION_COOKIE_HEADER_PREFIX = COOKIE_HEADER_PREFIX + SESSION_COOKIE_NAME + "="; private static final String REDIRECT_HEADER_PREFIX = "Location: "; protected static final String SESSION_PATH_PARAMETER_PREFIX = SESSION_PARAMETER_NAME + "="; protected static final String SESSION_PATH_PARAMETER_TAILS = CRLF + ";?"; private static final String ELEMENT_HEAD = "<"; private static final String ELEMENT_TAIL = ">"; private static final String RESOURCE_TAG = "a"; private static final String LOGIN_TAG = "form"; private Socket socket; private Writer writer; private BufferedReader reader; private int port = 8080; private String[] request; private boolean useContinue = false; private boolean useCookies = true; private int requestPause = 1000; private String responseLine; private List<String> responseHeaders = new ArrayList<>(); private String sessionId; private boolean useContentLength; private int contentLength; private String redirectUri; private String responseBody; private List<String> bodyUriElements = null; public void setPort(int thePort) { port = thePort; } public void setRequest(String[] theRequest) { request = theRequest; } /* * Expect the server to reply with 100 Continue interim response */ public void setUseContinue(boolean theUseContinueFlag) { useContinue = theUseContinueFlag; } public boolean getUseContinue() { return useContinue; } public void setUseCookies(boolean theUseCookiesFlag) { useCookies = theUseCookiesFlag; } public boolean getUseCookies() { return useCookies; } public void setRequestPause(int theRequestPause) { requestPause = theRequestPause; } public String getResponseLine() { return responseLine; } public List<String> getResponseHeaders() { return responseHeaders; } public String getResponseBody() { return responseBody; } /** * Return opening tags of HTML elements that were extracted by the * {@link #extractUriElements()} method. * * <p> * Note, that {@link #extractUriElements()} method has to be called * explicitly. * * @return List of HTML tags, accumulated by {@link #extractUriElements()} * method, or {@code null} if the method has not been called yet. */ public List<String> getResponseBodyUriElements() { return bodyUriElements; } public void setUseContentLength(boolean b) { useContentLength = b; } public void setSessionId(String theSessionId) { sessionId = theSessionId; } public String getSessionId() { return sessionId; } public String getRedirectUri() { return redirectUri; } public void connect(int connectTimeout, int soTimeout) throws UnknownHostException, IOException { final String encoding = "ISO-8859-1"; SocketAddress addr = new InetSocketAddress("localhost", port); socket = new Socket(); socket.setSoTimeout(soTimeout); socket.connect(addr,connectTimeout); OutputStream os = socket.getOutputStream(); writer = new OutputStreamWriter(os, encoding); InputStream is = socket.getInputStream(); Reader r = new InputStreamReader(is, encoding); reader = new BufferedReader(r); } public void connect() throws UnknownHostException, IOException { connect(0,0); } public void processRequest() throws IOException, InterruptedException { processRequest(true); } public void processRequest(boolean wantBody) throws IOException, InterruptedException { sendRequest(); readResponse(wantBody); } /* * Send the component parts of the request * (be tolerant and simply skip null entries) */ public void sendRequest() throws InterruptedException, IOException { boolean first = true; for (String requestPart : request) { if (requestPart != null) { if (first) { first = false; } else { Thread.sleep(requestPause); } writer.write(requestPart); writer.flush(); } } } public void readResponse(boolean wantBody) throws IOException { // clear any residual data before starting on this response responseHeaders.clear(); responseBody = null; if (bodyUriElements != null) { bodyUriElements.clear(); } // Read the response status line responseLine = readLine(); // Is a 100 continue response expected? if (useContinue) { if (isResponse100()) { // Skip the blank after the 100 Continue response readLine(); // Now get the final response responseLine = readLine(); } else { throw new IOException("No 100 Continue response"); } } // Put the headers into a map, and process interesting ones processHeaders(); // Read the body, if requested and if one exists processBody(wantBody); if (isResponse408()) { // the session has timed out sessionId = null; } } /* * Accumulate the response headers into a map, and extract * interesting details at the same time */ private void processHeaders() throws IOException { // Reset response fields redirectUri = null; contentLength = -1; String line = readLine(); while ((line != null) && (line.length() > 0)) { responseHeaders.add(line); if (line.startsWith(CONTENT_LENGTH_HEADER_PREFIX)) { contentLength = Integer.parseInt(line.substring(16)); } else if (line.startsWith(COOKIE_HEADER_PREFIX)) { if (useCookies) { String temp = line.substring( SESSION_COOKIE_HEADER_PREFIX.length()); temp = temp.substring(0, temp.indexOf(';')); setSessionId(temp); } } else if (line.startsWith(REDIRECT_HEADER_PREFIX)) { redirectUri = line.substring(REDIRECT_HEADER_PREFIX.length()); } line = readLine(); } } /* * Read the body of the server response. Save its contents and * search it for uri-elements only if requested */ private void processBody(boolean wantBody) throws IOException { // Read the body, if one exists StringBuilder builder = new StringBuilder(); if (wantBody) { if (useContentLength && (contentLength > -1)) { char[] body = new char[contentLength]; reader.read(body); builder.append(body); } else { // not using content length, so just read it line by line String line = null; while ((line = readLine()) != null) { builder.append(line); } } } responseBody = builder.toString(); } /** * Scan the response body for opening tags of certain HTML elements * (&lt;a&gt;, &lt;form&gt;). If any are found, then accumulate them. * * <p> * Note: This method has the following limitations: a) It assumes that the * response is HTML. b) It searches for lowercase tags only. * * @see #getResponseBodyUriElements() */ public void extractUriElements() { bodyUriElements = new ArrayList<>(); if (responseBody.length() > 0) { int ix = 0; while ((ix = extractUriElement(responseBody, ix, RESOURCE_TAG)) > 0){ // loop } ix = 0; while ((ix = extractUriElement(responseBody, ix, LOGIN_TAG)) > 0){ // loop } } } /* * Scan an html body for a given html uri element, starting from the * given index into the source string. If any are found, simply * accumulate them as literal strings, including angle brackets. * note: nested elements will not be collected. * * @param body HTTP body of the response * @param startIx offset into the body to resume the scan (for iteration) * @param elementName to scan for (only one at a time) * @returns the index into the body to continue the scan (for iteration) */ private int extractUriElement(String body, int startIx, String elementName) { String detector = ELEMENT_HEAD + elementName + " "; int iStart = body.indexOf(detector, startIx); if (iStart > -1) { int iEnd = body.indexOf(ELEMENT_TAIL, iStart); if (iEnd < 0) { throw new IllegalArgumentException( "Response body check failure.\n" + "element [" + detector + "] is not terminated with [" + ELEMENT_TAIL + "]\nActual: [" + body + "]"); } String element = body.substring(iStart, iEnd); bodyUriElements.add(element); iStart += element.length(); } return iStart; } public String readLine() throws IOException { return reader.readLine(); } public void disconnect() throws IOException { writer.close(); reader.close(); socket.close(); } public void reset() { socket = null; writer = null; reader = null; request = null; requestPause = 1000; useContinue = false; responseLine = null; responseHeaders = new ArrayList<>(); responseBody = null; } public boolean isResponse100() { return getResponseLine().startsWith(INFO_100); } public boolean isResponse200() { return getResponseLine().startsWith(OK_200); } public boolean isResponse302() { return getResponseLine().startsWith(REDIRECT_302); } public boolean isResponse400() { return getResponseLine().startsWith(FAIL_400); } public boolean isResponse404() { return getResponseLine().startsWith(FAIL_404); } public boolean isResponse408() { return getResponseLine().startsWith(TIMEOUT_408); } public boolean isResponse413() { return getResponseLine().startsWith(FAIL_413); } public boolean isResponse50x() { return getResponseLine().startsWith(FAIL_50X); } public boolean isResponse500() { return getResponseLine().startsWith(FAIL_500); } public boolean isResponse501() { return getResponseLine().startsWith(FAIL_501); } public Socket getSocket() { return socket; } public abstract boolean isResponseBodyOK(); }
54,947
Bug 54947 Http11NioProtocol generates HTTP 505 responses on valid requests if request is split across multiple packets
If an HTTP request is broken up across multiple packets *and* the first packet contains a GET request up to "\r" AND the "\n" terminating the first line of the request is included in the next packet Tomcat incorrectly throws an HTTP "505 Version Not Supported" response. This is with the Http11NioProtocol connector only - the default HTTP/1.1 connector does not exhibit this problem. An example request: Packet 1: GET / HTTP/1.1\r Packet 2: \nHost: localhost\r\n Packet 3: Connection: Close\r\n\r\n Response: HTTP/1.1 505 HTTP Version Not Supported Server: Apache-Coyote/1.1 Date: Thu, 09 May 2013 20:23:58 GMT Connection: close The following Python program reproduces the problem for me in both Tomcat 6.0.37 and Tomcat 7.0.39: """ #!/usr/bin/python import socket import time s = socket.socket() s.connect(("localhost",8080)) s.sendall("GET / HTTP/1.1\r") time.sleep(1.5) # make sure the above goes out in its own packet s.sendall("\nHost: localhost\r\n") s.sendall("Connection: close\r\n\r\n") print s.makefile().read() """ Moving the "\n" to from the second sendall to the end of the first sendall causes Tomcat to respond correctly.
resolved fixed
f763975
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T11:26:20Z
2013-05-10T01:40:00Z
test/org/apache/coyote/http11/TestInternalInputBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; public class TestInternalInputBuffer extends TomcatBaseTest { /** * Test case for https://issues.apache.org/bugzilla/show_bug.cgi?id=48839 */ @Test public void testBug48839() { Bug48839Client client = new Bug48839Client(); client.doRequest(); assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); } /** * Bug 48839 test client. */ private class Bug48839Client extends SimpleHttpClient { private Exception doRequest() { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(root, "Bug48839", new Bug48839Servlet()); root.addServletMapping("/test", "Bug48839"); try { tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); // Open connection connect(); String[] request = new String[1]; request[0] = "GET http://localhost:8080/test HTTP/1.1" + CRLF + "X-Bug48839: abcd" + CRLF + "\tefgh" + CRLF + "Connection: close" + CRLF + CRLF; setRequest(request); processRequest(); // blocks until response has been read // Close the connection disconnect(); } catch (Exception e) { return e; } return null; } @Override public boolean isResponseBodyOK() { if (getResponseBody() == null) { return false; } if (!getResponseBody().contains("abcd\tefgh")) { return false; } return true; } } private static class Bug48839Servlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * Only interested in the request headers from a GET request */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the header value back as plain text resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); Enumeration<String> values = req.getHeaders("X-Bug48839"); while (values.hasMoreElements()) { out.println(values.nextElement()); } } } @Test public void testBug51557NoColon() { Bug51557Client client = new Bug51557Client("X-Bug51557NoColon"); client.doRequest(); assertTrue(client.isResponse200()); assertEquals("abcd", client.getResponseBody()); assertTrue(client.isResponseBodyOK()); } @Test public void testBug51557Separators() throws Exception { char httpSeparators[] = new char[] { '\t', ' ', '\"', '(', ')', ',', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '{', '}' }; for (char s : httpSeparators) { doTestBug51557Char(s); tearDown(); setUp(); } } @Test public void testBug51557Ctl() throws Exception { for (int i = 0; i < 31; i++) { doTestBug51557Char((char) i); tearDown(); setUp(); } doTestBug51557Char((char) 127); } @Test public void testBug51557Continuation() { Bug51557Client client = new Bug51557Client("X-Bug=51557NoColon", "foo" + SimpleHttpClient.CRLF + " bar"); client.doRequest(); assertTrue(client.isResponse200()); assertEquals("abcd", client.getResponseBody()); assertTrue(client.isResponseBodyOK()); } @Test public void testBug51557BoundaryStart() { Bug51557Client client = new Bug51557Client("=X-Bug51557", "invalid"); client.doRequest(); assertTrue(client.isResponse200()); assertEquals("abcd", client.getResponseBody()); assertTrue(client.isResponseBodyOK()); } @Test public void testBug51557BoundaryEnd() { Bug51557Client client = new Bug51557Client("X-Bug51557=", "invalid"); client.doRequest(); assertTrue(client.isResponse200()); assertEquals("abcd", client.getResponseBody()); assertTrue(client.isResponseBodyOK()); } private void doTestBug51557Char(char s) { Bug51557Client client = new Bug51557Client("X-Bug" + s + "51557", "invalid"); client.doRequest(); assertTrue(client.isResponse200()); assertEquals("abcd", client.getResponseBody()); assertTrue(client.isResponseBodyOK()); } /** * Bug 51557 test client. */ private class Bug51557Client extends SimpleHttpClient { private String headerName; private String headerLine; public Bug51557Client(String headerName) { this.headerName = headerName; this.headerLine = headerName; } public Bug51557Client(String headerName, String headerValue) { this.headerName = headerName; this.headerLine = headerName + ": " + headerValue; } private Exception doRequest() { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(root, "Bug51557", new Bug51557Servlet(headerName)); root.addServletMapping("/test", "Bug51557"); try { tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); // Open connection connect(); String[] request = new String[1]; request[0] = "GET http://localhost:8080/test HTTP/1.1" + CRLF + headerLine + CRLF + "X-Bug51557: abcd" + CRLF + "Connection: close" + CRLF + CRLF; setRequest(request); processRequest(); // blocks until response has been read // Close the connection disconnect(); } catch (Exception e) { return e; } return null; } @Override public boolean isResponseBodyOK() { if (getResponseBody() == null) { return false; } if (!getResponseBody().contains("abcd")) { return false; } return true; } } private static class Bug51557Servlet extends HttpServlet { private static final long serialVersionUID = 1L; private String invalidHeaderName; /** * @param invalidHeaderName The header name should be invalid and * therefore ignored by the header parsing code */ public Bug51557Servlet(String invalidHeaderName) { this.invalidHeaderName = invalidHeaderName; } /** * Only interested in the request headers from a GET request */ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Just echo the header value back as plain text resp.setContentType("text/plain"); PrintWriter out = resp.getWriter(); processHeaders(invalidHeaderName, req, out); processHeaders("X-Bug51557", req, out); } private void processHeaders(String header, HttpServletRequest req, PrintWriter out) { Enumeration<String> values = req.getHeaders(header); while (values.hasMoreElements()) { out.println(values.nextElement()); } } } /** * Test case for new lines at the start of a request. RFC2616 * does not permit any, but Tomcat is tolerant of them if they are present. */ @Test public void testNewLines() { NewLinesClient client = new NewLinesClient(10); client.doRequest(); assertTrue(client.isResponse200()); assertTrue(client.isResponseBodyOK()); } /** * Test case for new lines at the start of a request. RFC2616 * does not permit any, but Tomcat is tolerant of them if they are present. */ @Test public void testNewLinesExcessive() { NewLinesClient client = new NewLinesClient(10000); // If the connection is closed fast enough, writing the request will // fail and the response won't be read. Exception e = client.doRequest(); if (e == null) { assertTrue(client.isResponse400()); } assertFalse(client.isResponseBodyOK()); } private class NewLinesClient extends SimpleHttpClient { private final String newLines; private NewLinesClient(int count) { StringBuilder sb = new StringBuilder(count * 2); for (int i = 0; i < count; i++) { sb.append(CRLF); } newLines = sb.toString(); } private Exception doRequest() { Tomcat tomcat = getTomcatInstance(); Context root = tomcat.addContext("", TEMP_DIR); Tomcat.addServlet(root, "test", new TesterServlet()); root.addServletMapping("/test", "test"); try { tomcat.start(); setPort(tomcat.getConnector().getLocalPort()); // Open connection connect(); String[] request = new String[1]; request[0] = newLines + "GET http://localhost:8080/test HTTP/1.1" + CRLF + "X-Bug48839: abcd" + CRLF + "\tefgh" + CRLF + "Connection: close" + CRLF + CRLF; setRequest(request); processRequest(); // blocks until response has been read // Close the connection disconnect(); } catch (Exception e) { return e; } return null; } @Override public boolean isResponseBodyOK() { if (getResponseBody() == null) { return false; } if (!getResponseBody().contains("OK")) { return false; } return true; } } }
54,961
Bug 54961 Make "compress" configurable in SpdyProxyProtocol
null
resolved fixed
c25112b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T11:41:57Z
2013-05-14T05:40:00Z
java/org/apache/coyote/spdy/SpdyProxyProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.spdy; import java.io.IOException; import java.net.Socket; import org.apache.coyote.AbstractProtocol; import org.apache.coyote.ajp.Constants; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.spdy.NetSupportSocket; import org.apache.tomcat.spdy.SpdyConnection; import org.apache.tomcat.spdy.SpdyContext; import org.apache.tomcat.spdy.SpdyContext.SpdyHandler; import org.apache.tomcat.spdy.SpdyStream; import org.apache.tomcat.util.net.AbstractEndpoint.Handler; import org.apache.tomcat.util.net.JIoEndpoint; import org.apache.tomcat.util.net.SSLImplementation; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; /** * SPDY in 'proxy' mode - no SSL and no header compression. * This doesn't require JNI libraries, SSL/compression are off-loaded to * a reverse proxy ( apache, etc ). * * To configure: * <Connector port="8011" protocol="org.apache.coyote.spdy.SpdyProxyProtocol"/> * * To test, use * chrome --use-spdy=no-compress,no-ssl [--enable-websocket-over-spdy] * * TODO: Remote information (client ip, certs, etc ) will be sent in X- headers. * TODO: if spdy->spdy proxy, info about original spdy stream for pushes. * */ public class SpdyProxyProtocol extends AbstractProtocol { private static final Log log = LogFactory.getLog(SpdyProxyProtocol.class); private final JIoEndpoint.Handler cHandler = new TomcatJioHandler(); private SpdyContext spdyContext; public SpdyProxyProtocol() { endpoint = new JIoEndpoint(); ((JIoEndpoint) endpoint).setHandler(cHandler); setSoLinger(Constants.DEFAULT_CONNECTION_LINGER); setSoTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT); setTcpNoDelay(Constants.DEFAULT_TCP_NO_DELAY); } @Override protected Log getLog() { return log; } @Override protected String getNamePrefix() { return "spdy2-jio"; } @Override protected String getProtocolName() { return "spdy2"; } @Override protected Handler getHandler() { return cHandler; } @Override public void start() throws Exception { super.start(); spdyContext = new SpdyContext(); spdyContext.setTlsComprression(false, false); spdyContext.setHandler(new SpdyHandler() { @Override public void onStream(SpdyConnection con, SpdyStream ch) throws IOException { SpdyProcessor sp = new SpdyProcessor(con, endpoint); sp.setAdapter(getAdapter()); sp.onSynStream(ch); } }); spdyContext.setNetSupport(new NetSupportSocket()); spdyContext.setExecutor(endpoint.getExecutor()); } public class TomcatJioHandler implements JIoEndpoint.Handler { @Override public Object getGlobal() { return null; } @Override public void recycle() { } @Override public SocketState process(SocketWrapper<Socket> socket, SocketStatus status) { spdyContext.getNetSupport().onAccept(socket.getSocket()); return SocketState.CLOSED; } @Override public SSLImplementation getSslImplementation() { return null; } @Override public void beforeHandshake(SocketWrapper<Socket> socket) { } } }
54,963
Bug 54963 Concurrent issue of Spdy/NetSupportSocket
null
resolved fixed
6272fca
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T11:46:56Z
2013-05-14T11:13:20Z
java/org/apache/tomcat/spdy/NetSupportSocket.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.spdy; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.security.NoSuchAlgorithmException; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocket; public class NetSupportSocket extends SpdyContext.NetSupport { @Override public boolean isSpdy(Object socketW) { return false; } @Override public SpdyConnection getConnection(String host, int port) throws IOException { try { Socket sock = getSocket(host, port); sock.getInputStream(); SpdyConnectionSocket con = new SpdyConnectionSocket(ctx, sock); ctx.getExecutor().execute(con.inputThread); return con; } catch (IOException ex) { ex.printStackTrace(); throw ex; } } protected Socket getSocket(String host, int port) throws IOException { try { if (ctx.tls) { SSLContext sslCtx = SSLContext.getDefault(); SSLSocket socket = (SSLSocket) sslCtx.getSocketFactory().createSocket(host, port); //socket.setEnabledProtocols(new String[] {"TLS1"}); socket.startHandshake(); return socket; } else { return new Socket(host, port); } } catch (NoSuchAlgorithmException e) { throw new IOException(e); } } private boolean running = true; private ServerSocket serverSocket; @Override public void stop() throws IOException { running = false; serverSocket.close(); } @Override public void onAccept(Object socket) { SpdyConnectionSocket ch = new SpdyConnectionSocket(ctx, (Socket) socket); ctx.getExecutor().execute(ch.inputThread); ch.onBlockingSocket(); } @Override public void listen(final int port, String cert, String key) throws IOException { ctx.getExecutor().execute(new Runnable() { @Override public void run() { accept(port); } }); } private void accept(int port) { try { serverSocket = new ServerSocket(port); while (running) { final Socket socket = serverSocket.accept(); ctx.getExecutor().execute(new Runnable() { @Override public void run() { onAccept(socket); try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } }); } } catch (IOException ex) { if (running) { ex.printStackTrace(); } running = false; } } private static class SpdyConnectionSocket extends SpdyConnection { private Socket socket; Runnable inputThread = new Runnable() { @Override public void run() { onBlockingSocket(); try { inClosed = true; socket.close(); } catch (IOException e) { e.printStackTrace(); } } }; public SpdyConnectionSocket(SpdyContext spdyContext) { super(spdyContext); } public SpdyConnectionSocket(SpdyContext spdyContext, Socket socket) { super(spdyContext); this.socket = socket; } @Override public void close() throws IOException { socket.close(); } @Override public synchronized int write(byte[] data, int off, int len) throws IOException { socket.getOutputStream().write(data, off, len); return len; } @Override public int read(byte[] data, int off, int len) throws IOException { try { return socket.getInputStream().read(data, off, len); } catch (SocketTimeoutException ex) { return 0; } } } }
54,964
Bug 54964 Class loading issue of "TagPlugin" in TagPluginManager
null
resolved fixed
65ab66e
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T11:54:49Z
2013-05-14T11:13:20Z
java/org/apache/jasper/compiler/TagPluginManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import javax.servlet.ServletContext; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.tagplugin.TagPlugin; import org.apache.jasper.compiler.tagplugin.TagPluginContext; import org.apache.jasper.xmlparser.ParserUtils; import org.apache.jasper.xmlparser.TreeNode; /** * Manages tag plugin optimizations. * @author Kin-man Chung */ public class TagPluginManager { private static final String META_INF_JASPER_TAG_PLUGINS_XML = "META-INF/org.apache.jasper/tagPlugins.xml"; private static final String TAG_PLUGINS_XML = "/WEB-INF/tagPlugins.xml"; private static final String TAG_PLUGINS_ROOT_ELEM = "tag-plugins"; private boolean initialized = false; private HashMap<String, TagPlugin> tagPlugins = null; private final ServletContext ctxt; private PageInfo pageInfo; public TagPluginManager(ServletContext ctxt) { this.ctxt = ctxt; } public void apply(Node.Nodes page, ErrorDispatcher err, PageInfo pageInfo) throws JasperException { init(err); if (tagPlugins == null || tagPlugins.size() == 0) { return; } this.pageInfo = pageInfo; page.visit(new Node.Visitor() { @Override public void visit(Node.CustomTag n) throws JasperException { invokePlugin(n); visitBody(n); } }); } private void init(ErrorDispatcher err) throws JasperException { if (initialized) return; tagPlugins = new HashMap<>(); Enumeration<URL> urls = null; try { urls = ctxt.getClassLoader().getResources( META_INF_JASPER_TAG_PLUGINS_XML); } catch (IOException ioe) { throw new JasperException(ioe); } if (urls != null) { while(urls.hasMoreElements()) { URL url = urls.nextElement(); try (InputStream is = url.openStream()){ loadTagPlugins(err, is); } catch(IOException ioe) { throw new JasperException(ioe); } } } try (InputStream is = ctxt.getResourceAsStream(TAG_PLUGINS_XML)) { if (is != null) { loadTagPlugins(err, is); } } catch (IOException ioe) { throw new JasperException(ioe); } initialized = true; } private void loadTagPlugins(ErrorDispatcher err, InputStream is) throws JasperException { TreeNode root = (new ParserUtils()).parseXMLDocument(TAG_PLUGINS_XML, is); if (root == null) { return; } if (!TAG_PLUGINS_ROOT_ELEM.equals(root.getName())) { err.jspError("jsp.error.plugin.wrongRootElement", TAG_PLUGINS_XML, TAG_PLUGINS_ROOT_ELEM); } tagPlugins = new HashMap<>(); Iterator<TreeNode> pluginList = root.findChildren("tag-plugin"); while (pluginList.hasNext()) { TreeNode pluginNode = pluginList.next(); TreeNode tagClassNode = pluginNode.findChild("tag-class"); if (tagClassNode == null) { // Error return; } String tagClass = tagClassNode.getBody().trim(); TreeNode pluginClassNode = pluginNode.findChild("plugin-class"); if (pluginClassNode == null) { // Error return; } String pluginClassStr = pluginClassNode.getBody(); TagPlugin tagPlugin = null; try { Class<?> pluginClass = Class.forName(pluginClassStr); tagPlugin = (TagPlugin) pluginClass.newInstance(); } catch (Exception e) { throw new JasperException(e); } if (tagPlugin == null) { return; } tagPlugins.put(tagClass, tagPlugin); } initialized = true; } /** * Invoke tag plugin for the given custom tag, if a plugin exists for * the custom tag's tag handler. * * The given custom tag node will be manipulated by the plugin. */ private void invokePlugin(Node.CustomTag n) { TagPlugin tagPlugin = tagPlugins.get(n.getTagHandlerClass().getName()); if (tagPlugin == null) { return; } TagPluginContext tagPluginContext = new TagPluginContextImpl(n, pageInfo); n.setTagPluginContext(tagPluginContext); tagPlugin.doTag(tagPluginContext); } private static class TagPluginContextImpl implements TagPluginContext { private final Node.CustomTag node; private Node.Nodes curNodes; private final PageInfo pageInfo; private final HashMap<String, Object> pluginAttributes; TagPluginContextImpl(Node.CustomTag n, PageInfo pageInfo) { this.node = n; this.pageInfo = pageInfo; curNodes = new Node.Nodes(); n.setAtETag(curNodes); curNodes = new Node.Nodes(); n.setAtSTag(curNodes); n.setUseTagPlugin(true); pluginAttributes = new HashMap<>(); } @Override public TagPluginContext getParentContext() { Node parent = node.getParent(); if (! (parent instanceof Node.CustomTag)) { return null; } return ((Node.CustomTag) parent).getTagPluginContext(); } @Override public void setPluginAttribute(String key, Object value) { pluginAttributes.put(key, value); } @Override public Object getPluginAttribute(String key) { return pluginAttributes.get(key); } @Override public boolean isScriptless() { return node.getChildInfo().isScriptless(); } @Override public boolean isConstantAttribute(String attribute) { Node.JspAttribute attr = getNodeAttribute(attribute); if (attr == null) return false; return attr.isLiteral(); } @Override public String getConstantAttribute(String attribute) { Node.JspAttribute attr = getNodeAttribute(attribute); if (attr == null) return null; return attr.getValue(); } @Override public boolean isAttributeSpecified(String attribute) { return getNodeAttribute(attribute) != null; } @Override public String getTemporaryVariableName() { return node.getRoot().nextTemporaryVariableName(); } @Override public void generateImport(String imp) { pageInfo.addImport(imp); } @Override public void generateDeclaration(String id, String text) { if (pageInfo.isPluginDeclared(id)) { return; } curNodes.add(new Node.Declaration(text, node.getStart(), null)); } @Override public void generateJavaSource(String sourceCode) { curNodes.add(new Node.Scriptlet(sourceCode, node.getStart(), null)); } @Override public void generateAttribute(String attributeName) { curNodes.add(new Node.AttributeGenerator(node.getStart(), attributeName, node)); } @Override public void dontUseTagPlugin() { node.setUseTagPlugin(false); } @Override public void generateBody() { // Since we'll generate the body anyway, this is really a nop, // except for the fact that it lets us put the Java sources the // plugins produce in the correct order (w.r.t the body). curNodes = node.getAtETag(); } @Override public boolean isTagFile() { return pageInfo.isTagFile(); } private Node.JspAttribute getNodeAttribute(String attribute) { Node.JspAttribute[] attrs = node.getJspAttributes(); for (int i=0; attrs != null && i < attrs.length; i++) { if (attrs[i].getName().equals(attribute)) { return attrs[i]; } } return null; } } }
54,971
Bug 54971 javax.servlet.http.Part.write(String fileName) is not properly implemented
1. fileName parameter / relative vs absolute filaName parameter specification in <1><JSR-000315 Java Servlet 3.0 Final Release javadocs> is different from the <2><javax API tomcat refers to>. <1> <JSR-000315 Java Servlet 3.0 Final Release javadocs> Parameters:fileName - the name of the file to which the stream will be written. The file is created relative to the location as specified in the MultipartConfig <2> javax. API tomcat refers to * @param fileName The location into which the uploaded part should be * stored. Relative locations are relative to {@link * javax.servlet.MultipartConfigElement#getLocation()} Tomcat is implemented as specified in <2> so that it can process "absolute path", but it should only accept "relative path" as specified in <1> <JSR-000315 Java Servlet 3.0 Final Release javadocs> 2. If MultiPartConfig.location is not set, write( String relative path ) throws FileNotFound Exception. A default location needs to be set in order to avoid such exception. example) os: windows8 part.write("/test"); java.io.IOException: java.io.FileNotFoundException: \test (Access is denied) at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:123) at servlet.multipart.MultipleUploadServlet.doPost(MultipleUploadServlet.java:76) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:662)
resolved fixed
cccd0ac
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T14:37:50Z
2013-05-15T06:40:00Z
java/org/apache/catalina/connector/Request.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.connector; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.security.Principal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.NamingException; import javax.security.auth.Subject; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.MultipartConfigElement; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestAttributeEvent; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletResponse; import javax.servlet.SessionTrackingMode; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.Part; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Manager; import org.apache.catalina.Realm; import org.apache.catalina.Session; import org.apache.catalina.TomcatPrincipal; import org.apache.catalina.Wrapper; import org.apache.catalina.core.ApplicationPart; import org.apache.catalina.core.ApplicationSessionCookieConfig; import org.apache.catalina.core.AsyncContextImpl; import org.apache.catalina.mapper.MappingData; import org.apache.catalina.util.ParameterMap; import org.apache.catalina.util.StringParser; import org.apache.coyote.ActionCode; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.Cookies; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.Parameters; import org.apache.tomcat.util.http.ServerCookie; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileUploadBase; import org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; import org.apache.tomcat.util.res.StringManager; /** * Wrapper object for the Coyote request. * * @author Remy Maucherat * @author Craig R. McClanahan * @version $Id$ */ public class Request implements HttpServletRequest { private static final Log log = LogFactory.getLog(Request.class); // ----------------------------------------------------------- Constructors public Request() { formats[0].setTimeZone(GMT_ZONE); formats[1].setTimeZone(GMT_ZONE); formats[2].setTimeZone(GMT_ZONE); } // ------------------------------------------------------------- Properties /** * Coyote request. */ protected org.apache.coyote.Request coyoteRequest; /** * Set the Coyote request. * * @param coyoteRequest The Coyote request */ public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) { this.coyoteRequest = coyoteRequest; inputBuffer.setRequest(coyoteRequest); } /** * Get the Coyote request. */ public org.apache.coyote.Request getCoyoteRequest() { return (this.coyoteRequest); } // ----------------------------------------------------- Variables protected static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT"); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The set of cookies associated with this Request. */ protected Cookie[] cookies = null; /** * The set of SimpleDateFormat formats to use in getDateHeader(). * * Notice that because SimpleDateFormat is not thread-safe, we can't * declare formats[] as a static variable. */ protected final SimpleDateFormat formats[] = { new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE, Locale.US), new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; /** * The default Locale if none are specified. */ protected static final Locale defaultLocale = Locale.getDefault(); /** * The attributes associated with this Request, keyed by attribute name. */ protected final HashMap<String, Object> attributes = new HashMap<>(); /** * Flag that indicates if SSL attributes have been parsed to improve * performance for applications (usually frameworks) that make multiple * calls to {@link Request#getAttributeNames()}. */ protected boolean sslAttributesParsed = false; /** * List of read only attributes for this Request. */ private final HashMap<String,Object> readOnlyAttributes = new HashMap<>(); /** * The preferred Locales associated with this Request. */ protected final ArrayList<Locale> locales = new ArrayList<>(); /** * Internal notes associated with this request by Catalina components * and event listeners. */ private final transient HashMap<String, Object> notes = new HashMap<>(); /** * Authentication type. */ protected String authType = null; /** * Associated event. */ protected CometEventImpl event = null; /** * Comet state */ protected boolean comet = false; /** * The current dispatcher type. */ protected DispatcherType internalDispatcherType = null; /** * The associated input buffer. */ protected final InputBuffer inputBuffer = new InputBuffer(); /** * ServletInputStream. */ protected CoyoteInputStream inputStream = new CoyoteInputStream(inputBuffer); /** * Reader. */ protected CoyoteReader reader = new CoyoteReader(inputBuffer); /** * Using stream flag. */ protected boolean usingInputStream = false; /** * Using writer flag. */ protected boolean usingReader = false; /** * User principal. */ protected Principal userPrincipal = null; /** * Request parameters parsed flag. */ protected boolean parametersParsed = false; /** * Cookies parsed flag. */ protected boolean cookiesParsed = false; /** * Secure flag. */ protected boolean secure = false; /** * The Subject associated with the current AccessControllerContext */ protected transient Subject subject = null; /** * Post data buffer. */ protected static final int CACHED_POST_LEN = 8192; protected byte[] postData = null; /** * Hash map used in the getParametersMap method. */ protected ParameterMap<String, String[]> parameterMap = new ParameterMap<>(); /** * The parts, if any, uploaded with this request. */ protected Collection<Part> parts = null; /** * The exception thrown, if any when parsing the parts. */ protected Exception partsParseException = null; /** * The currently active session for this request. */ protected Session session = null; /** * The current request dispatcher path. */ protected Object requestDispatcherPath = null; /** * Was the requested session ID received in a cookie? */ protected boolean requestedSessionCookie = false; /** * The requested session ID (if any) for this request. */ protected String requestedSessionId = null; /** * Was the requested session ID received in a URL? */ protected boolean requestedSessionURL = false; /** * Was the requested session ID obtained from the SSL session? */ protected boolean requestedSessionSSL = false; /** * Parse locales. */ protected boolean localesParsed = false; /** * The string parser we will use for parsing request lines. */ private final StringParser parser = new StringParser(); /** * Local port */ protected int localPort = -1; /** * Remote address. */ protected String remoteAddr = null; /** * Remote host. */ protected String remoteHost = null; /** * Remote port */ protected int remotePort = -1; /** * Local address */ protected String localAddr = null; /** * Local address */ protected String localName = null; /** * AsyncContext */ protected volatile AsyncContextImpl asyncContext = null; protected Boolean asyncSupported = null; /** * Path parameters */ protected final Map<String,String> pathParameters = new HashMap<>(); // --------------------------------------------------------- Public Methods protected void addPathParameter(String name, String value) { pathParameters.put(name, value); } protected String getPathParameter(String name) { return pathParameters.get(name); } public void setAsyncSupported(boolean asyncSupported) { this.asyncSupported = Boolean.valueOf(asyncSupported); } /** * Release all object references, and initialize instance variables, in * preparation for reuse of this object. */ public void recycle() { context = null; wrapper = null; internalDispatcherType = null; requestDispatcherPath = null; comet = false; if (event != null) { event.clear(); event = null; } authType = null; inputBuffer.recycle(); usingInputStream = false; usingReader = false; userPrincipal = null; subject = null; parametersParsed = false; if (parts != null) { for (Part part: parts) { try { part.delete(); } catch (IOException ignored) { // ApplicationPart.delete() never throws an IOEx } } parts = null; } partsParseException = null; cookiesParsed = false; locales.clear(); localesParsed = false; secure = false; remoteAddr = null; remoteHost = null; remotePort = -1; localPort = -1; localAddr = null; localName = null; attributes.clear(); sslAttributesParsed = false; notes.clear(); cookies = null; if (session != null) { try { session.endAccess(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); } } session = null; requestedSessionCookie = false; requestedSessionId = null; requestedSessionURL = false; if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) { parameterMap = new ParameterMap<>(); } else { parameterMap.setLocked(false); parameterMap.clear(); } mappingData.recycle(); if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) { if (facade != null) { facade.clear(); facade = null; } if (inputStream != null) { inputStream.clear(); inputStream = null; } if (reader != null) { reader.clear(); reader = null; } } asyncSupported = null; if (asyncContext!=null) { asyncContext.recycle(); } asyncContext = null; pathParameters.clear(); } /** * Clear cached encoders (to save memory for Comet requests). */ public void clearEncoders() { inputBuffer.clearEncoders(); } /** * Clear cached encoders (to save memory for Comet requests). */ public boolean read() throws IOException { return (inputBuffer.realReadBytes(null, 0, 0) > 0); } // -------------------------------------------------------- Request Methods /** * Associated Catalina connector. */ protected Connector connector; /** * Return the Connector through which this Request was received. */ public Connector getConnector() { return this.connector; } /** * Set the Connector through which this Request was received. * * @param connector The new connector */ public void setConnector(Connector connector) { this.connector = connector; } /** * Associated context. */ protected Context context = null; /** * Return the Context within which this Request is being processed. */ public Context getContext() { return this.context; } /** * Set the Context within which this Request is being processed. This * must be called as soon as the appropriate Context is identified, because * it identifies the value to be returned by <code>getContextPath()</code>, * and thus enables parsing of the request URI. * * @param context The newly associated Context */ public void setContext(Context context) { this.context = context; } /** * Filter chain associated with the request. */ protected FilterChain filterChain = null; /** * Get filter chain associated with the request. */ public FilterChain getFilterChain() { return this.filterChain; } /** * Set filter chain associated with the request. * * @param filterChain new filter chain */ public void setFilterChain(FilterChain filterChain) { this.filterChain = filterChain; } /** * Return the Host within which this Request is being processed. */ public Host getHost() { return mappingData.host; } /** * Mapping data. */ protected final MappingData mappingData = new MappingData(); /** * Return mapping data. */ public MappingData getMappingData() { return mappingData; } /** * The facade associated with this request. */ protected RequestFacade facade = null; /** * Return the <code>ServletRequest</code> for which this object * is the facade. This method must be implemented by a subclass. */ public HttpServletRequest getRequest() { if (facade == null) { facade = new RequestFacade(this); } return facade; } /** * The response with which this request is associated. */ protected org.apache.catalina.connector.Response response = null; /** * Return the Response with which this Request is associated. */ public org.apache.catalina.connector.Response getResponse() { return this.response; } /** * Set the Response with which this Request is associated. * * @param response The new associated response */ public void setResponse(org.apache.catalina.connector.Response response) { this.response = response; } /** * Return the input stream associated with this Request. */ public InputStream getStream() { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * URI byte to char converter. */ protected B2CConverter URIConverter = null; /** * Return the URI converter. */ protected B2CConverter getURIConverter() { return URIConverter; } /** * Set the URI converter. * * @param URIConverter the new URI converter */ protected void setURIConverter(B2CConverter URIConverter) { this.URIConverter = URIConverter; } /** * Associated wrapper. */ protected Wrapper wrapper = null; /** * Return the Wrapper within which this Request is being processed. */ public Wrapper getWrapper() { return this.wrapper; } /** * Set the Wrapper within which this Request is being processed. This * must be called as soon as the appropriate Wrapper is identified, and * before the Request is ultimately passed to an application servlet. * @param wrapper The newly associated Wrapper */ public void setWrapper(Wrapper wrapper) { this.wrapper = wrapper; } // ------------------------------------------------- Request Public Methods /** * Create and return a ServletInputStream to read the content * associated with this Request. * * @exception IOException if an input/output error occurs */ public ServletInputStream createInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * Perform whatever actions are required to flush and close the input * stream or reader, in a single operation. * * @exception IOException if an input/output error occurs */ public void finishRequest() throws IOException { // Optionally disable swallowing of additional request data. Context context = getContext(); if (context != null && response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } } /** * Return the object bound with the specified name to the internal notes * for this request, or <code>null</code> if no such binding exists. * * @param name Name of the note to be returned */ public Object getNote(String name) { return notes.get(name); } /** * Remove any object bound to the specified name in the internal notes * for this request. * * @param name Name of the note to be removed */ public void removeNote(String name) { notes.remove(name); } /** * Set the port number of the server to process this request. * * @param port The server port */ public void setLocalPort(int port) { localPort = port; } /** * Bind an object to a specified name in the internal notes associated * with this request, replacing any existing binding for this name. * * @param name Name to which the object should be bound * @param value Object to be bound to the specified name */ public void setNote(String name, Object value) { notes.put(name, value); } /** * Set the IP address of the remote client associated with this Request. * * @param remoteAddr The remote IP address */ public void setRemoteAddr(String remoteAddr) { this.remoteAddr = remoteAddr; } /** * Set the fully qualified name of the remote client associated with this * Request. * * @param remoteHost The remote host name */ public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } /** * Set the value to be returned by <code>isSecure()</code> * for this Request. * * @param secure The new isSecure value */ public void setSecure(boolean secure) { this.secure = secure; } /** * Set the port number of the server to process this request. * * @param port The server port */ public void setServerPort(int port) { coyoteRequest.setServerPort(port); } // ------------------------------------------------- ServletRequest Methods /** * Return the specified request attribute if it exists; otherwise, return * <code>null</code>. * * @param name Name of the request attribute to return */ @Override public Object getAttribute(String name) { // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { return adapter.get(this, name); } Object attr=attributes.get(name); if(attr!=null) { return(attr); } attr = coyoteRequest.getAttribute(name); if(attr != null) { return attr; } if( isSSLAttribute(name) ) { coyoteRequest.action(ActionCode.REQ_SSL_ATTRIBUTE, coyoteRequest); attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR); if( attr != null) { attributes.put(Globals.CERTIFICATES_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR); if(attr != null) { attributes.put(Globals.CIPHER_SUITE_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR); if(attr != null) { attributes.put(Globals.KEY_SIZE_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR); if(attr != null) { attributes.put(Globals.SSL_SESSION_ID_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_MGR_ATTR); if(attr != null) { attributes.put(Globals.SSL_SESSION_MGR_ATTR, attr); } attr = attributes.get(name); sslAttributesParsed = true; } return attr; } @Override public long getContentLengthLong() { return coyoteRequest.getContentLengthLong(); } /** * Test if a given name is one of the special Servlet-spec SSL attributes. */ static boolean isSSLAttribute(String name) { return Globals.CERTIFICATES_ATTR.equals(name) || Globals.CIPHER_SUITE_ATTR.equals(name) || Globals.KEY_SIZE_ATTR.equals(name) || Globals.SSL_SESSION_ID_ATTR.equals(name) || Globals.SSL_SESSION_MGR_ATTR.equals(name); } /** * Return the names of all request attributes for this Request, or an * empty <code>Enumeration</code> if there are none. Note that the attribute * names returned will only be those for the attributes set via * {@link #setAttribute(String, Object)}. Tomcat internal attributes will * not be included although they are accessible via * {@link #getAttribute(String)}. The Tomcat internal attributes include: * <ul> * <li>{@link Globals#DISPATCHER_TYPE_ATTR}</li> * <li>{@link Globals#DISPATCHER_REQUEST_PATH_ATTR}</li> * <li>{@link Globals#ASYNC_SUPPORTED_ATTR}</li> * <li>{@link Globals#CERTIFICATES_ATTR} (SSL connections only)</li> * <li>{@link Globals#CIPHER_SUITE_ATTR} (SSL connections only)</li> * <li>{@link Globals#KEY_SIZE_ATTR} (SSL connections only)</li> * <li>{@link Globals#SSL_SESSION_ID_ATTR} (SSL connections only)</li> * <li>{@link Globals#SSL_SESSION_MGR_ATTR} (SSL connections only)</li> * <li>{@link Globals#PARAMETER_PARSE_FAILED_ATTR}</li> * </ul> * The underlying connector may also expose request attributes. These all * have names starting with "org.apache.tomcat" and include: * <ul> * <li>{@link Globals#SENDFILE_SUPPORTED_ATTR}</li> * <li>{@link Globals#COMET_SUPPORTED_ATTR}</li> * <li>{@link Globals#COMET_TIMEOUT_SUPPORTED_ATTR}</li> * </ul> * Connector implementations may return some, all or none of these * attributes and may also support additional attributes. */ @Override public Enumeration<String> getAttributeNames() { if (isSecure() && !sslAttributesParsed) { getAttribute(Globals.CERTIFICATES_ATTR); } // Take a copy to prevent ConncurrentModificationExceptions if used to // remove attributes Set<String> names = new HashSet<>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); } /** * Return the character encoding for this Request. */ @Override public String getCharacterEncoding() { return coyoteRequest.getCharacterEncoding(); } /** * Return the content length for this Request. */ @Override public int getContentLength() { return coyoteRequest.getContentLength(); } /** * Return the content type for this Request. */ @Override public String getContentType() { return coyoteRequest.getContentType(); } /** * Set the content type for this Request. */ public void setContentType(String contentType) { coyoteRequest.setContentType(contentType); } /** * Return the servlet input stream for this Request. The default * implementation returns a servlet input stream created by * <code>createInputStream()</code>. * * @exception IllegalStateException if <code>getReader()</code> has * already been called for this request * @exception IOException if an input/output error occurs */ @Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * Return the preferred Locale that the client will accept content in, * based on the value for the first <code>Accept-Language</code> header * that was encountered. If the request did not specify a preferred * language, the server's default Locale is returned. */ @Override public Locale getLocale() { if (!localesParsed) { parseLocales(); } if (locales.size() > 0) { return locales.get(0); } return defaultLocale; } /** * Return the set of preferred Locales that the client will accept * content in, based on the values for any <code>Accept-Language</code> * headers that were encountered. If the request did not specify a * preferred language, the server's default Locale is returned. */ @Override public Enumeration<Locale> getLocales() { if (!localesParsed) { parseLocales(); } if (locales.size() > 0) { return Collections.enumeration(locales); } ArrayList<Locale> results = new ArrayList<>(); results.add(defaultLocale); return Collections.enumeration(results); } /** * Return the value of the specified request parameter, if any; otherwise, * return <code>null</code>. If there is more than one value defined, * return only the first one. * * @param name Name of the desired request parameter */ @Override public String getParameter(String name) { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameter(name); } /** * Returns a <code>Map</code> of the parameters of this request. * Request parameters are extra information sent with the request. * For HTTP servlets, parameters are contained in the query string * or posted form data. * * @return A <code>Map</code> containing parameter names as keys * and parameter values as map values. */ @Override public Map<String, String[]> getParameterMap() { if (parameterMap.isLocked()) { return parameterMap; } Enumeration<String> enumeration = getParameterNames(); while (enumeration.hasMoreElements()) { String name = enumeration.nextElement(); String[] values = getParameterValues(name); parameterMap.put(name, values); } parameterMap.setLocked(true); return parameterMap; } /** * Return the names of all defined request parameters for this request. */ @Override public Enumeration<String> getParameterNames() { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameterNames(); } /** * Return the defined values for the specified request parameter, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired request parameter */ @Override public String[] getParameterValues(String name) { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameterValues(name); } /** * Return the protocol and version used to make this Request. */ @Override public String getProtocol() { return coyoteRequest.protocol().toString(); } /** * Read the Reader wrapping the input stream for this Request. The * default implementation wraps a <code>BufferedReader</code> around the * servlet input stream returned by <code>createInputStream()</code>. * * @exception IllegalStateException if <code>getInputStream()</code> * has already been called for this request * @exception IOException if an input/output error occurs */ @Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; } /** * Return the real path of the specified virtual path. * * @param path Path to be translated * * @deprecated As of version 2.1 of the Java Servlet API, use * <code>ServletContext.getRealPath()</code>. */ @Override @Deprecated public String getRealPath(String path) { if (context == null) { return null; } ServletContext servletContext = context.getServletContext(); if (servletContext == null) { return null; } try { return (servletContext.getRealPath(path)); } catch (IllegalArgumentException e) { return null; } } /** * Return the remote IP address making this Request. */ @Override public String getRemoteAddr() { if (remoteAddr == null) { coyoteRequest.action (ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest); remoteAddr = coyoteRequest.remoteAddr().toString(); } return remoteAddr; } /** * Return the remote host name making this Request. */ @Override public String getRemoteHost() { if (remoteHost == null) { if (!connector.getEnableLookups()) { remoteHost = getRemoteAddr(); } else { coyoteRequest.action (ActionCode.REQ_HOST_ATTRIBUTE, coyoteRequest); remoteHost = coyoteRequest.remoteHost().toString(); } } return remoteHost; } /** * Returns the Internet Protocol (IP) source port of the client * or last proxy that sent the request. */ @Override public int getRemotePort(){ if (remotePort == -1) { coyoteRequest.action (ActionCode.REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest); remotePort = coyoteRequest.getRemotePort(); } return remotePort; } /** * Returns the host name of the Internet Protocol (IP) interface on * which the request was received. */ @Override public String getLocalName(){ if (localName == null) { coyoteRequest.action (ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest); localName = coyoteRequest.localName().toString(); } return localName; } /** * Returns the Internet Protocol (IP) address of the interface on * which the request was received. */ @Override public String getLocalAddr(){ if (localAddr == null) { coyoteRequest.action (ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest); localAddr = coyoteRequest.localAddr().toString(); } return localAddr; } /** * Returns the Internet Protocol (IP) port number of the interface * on which the request was received. */ @Override public int getLocalPort(){ if (localPort == -1){ coyoteRequest.action (ActionCode.REQ_LOCALPORT_ATTRIBUTE, coyoteRequest); localPort = coyoteRequest.getLocalPort(); } return localPort; } /** * Return a RequestDispatcher that wraps the resource at the specified * path, which may be interpreted as relative to the current request path. * * @param path Path of the resource to be wrapped */ @Override public RequestDispatcher getRequestDispatcher(String path) { if (context == null) { return null; } // If the path is already context-relative, just pass it through if (path == null) { return null; } else if (path.startsWith("/")) { return (context.getServletContext().getRequestDispatcher(path)); } // Convert a request-relative path to a context-relative one String servletPath = (String) getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (servletPath == null) { servletPath = getServletPath(); } // Add the path info, if there is any String pathInfo = getPathInfo(); String requestPath = null; if (pathInfo == null) { requestPath = servletPath; } else { requestPath = servletPath + pathInfo; } int pos = requestPath.lastIndexOf('/'); String relative = null; if (pos >= 0) { relative = requestPath.substring(0, pos + 1) + path; } else { relative = requestPath + path; } return context.getServletContext().getRequestDispatcher(relative); } /** * Return the scheme used to make this Request. */ @Override public String getScheme() { return coyoteRequest.scheme().toString(); } /** * Return the server name responding to this Request. */ @Override public String getServerName() { return coyoteRequest.serverName().toString(); } /** * Return the server port responding to this Request. */ @Override public int getServerPort() { return coyoteRequest.getServerPort(); } /** * Was this request received on a secure connection? */ @Override public boolean isSecure() { return secure; } /** * Remove the specified request attribute if it exists. * * @param name Name of the request attribute to remove */ @Override public void removeAttribute(String name) { // Remove the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.getAttributes().remove(name); } boolean found = attributes.containsKey(name); if (found) { Object value = attributes.get(name); attributes.remove(name); // Notify interested application event listeners notifyAttributeRemoved(name, value); } else { return; } } /** * Set the specified request attribute to the specified value. * * @param name Name of the request attribute to set * @param value The associated value */ @Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); } /** * Notify interested listeners that attribute has been assigned a value. */ private void notifyAttributeAssigned(String name, Object value, Object oldValue) { Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) { return; } boolean replaced = (oldValue != null); ServletRequestAttributeEvent event = null; if (replaced) { event = new ServletRequestAttributeEvent( context.getServletContext(), getRequest(), name, oldValue); } else { event = new ServletRequestAttributeEvent( context.getServletContext(), getRequest(), name, value); } for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletRequestAttributeListener)) { continue; } ServletRequestAttributeListener listener = (ServletRequestAttributeListener) listeners[i]; try { if (replaced) { listener.attributeReplaced(event); } else { listener.attributeAdded(event); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); } } } /** * Notify interested listeners that attribute has been removed. */ private void notifyAttributeRemoved(String name, Object value) { Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) { return; } ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(context.getServletContext(), getRequest(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletRequestAttributeListener)) { continue; } ServletRequestAttributeListener listener = (ServletRequestAttributeListener) listeners[i]; try { listener.attributeRemoved(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); } } } /** * Overrides the name of the character encoding used in the body of * this request. This method must be called prior to reading request * parameters or reading input using <code>getReader()</code>. * * @param enc The character encoding to be used * * @exception UnsupportedEncodingException if the specified encoding * is not supported * * @since Servlet 2.3 */ @Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { if (usingReader) { return; } // Ensure that the specified encoding is valid byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; // Confirm that the encoding name is valid B2CConverter.getCharset(enc); // Save the validated encoding coyoteRequest.setCharacterEncoding(enc); } @Override public ServletContext getServletContext() { return context.getServletContext(); } @Override public AsyncContext startAsync() { return startAsync(getRequest(),response.getResponse()); } @Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) { if (!isAsyncSupported()) { throw new IllegalStateException("Not supported."); } if (asyncContext == null) { asyncContext = new AsyncContextImpl(this); } asyncContext.setStarted(getContext(), request, response, request==getRequest() && response==getResponse().getResponse()); asyncContext.setTimeout(getConnector().getAsyncTimeout()); return asyncContext; } @Override public boolean isAsyncStarted() { if (asyncContext == null) { return false; } return asyncContext.isStarted(); } public boolean isAsyncDispatching() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_DISPATCHING, result); return result.get(); } public boolean isAsync() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC, result); return result.get(); } @Override public boolean isAsyncSupported() { if (this.asyncSupported == null) { return true; } return asyncSupported.booleanValue(); } @Override public AsyncContext getAsyncContext() { return this.asyncContext; } @Override public DispatcherType getDispatcherType() { if (internalDispatcherType == null) { return DispatcherType.REQUEST; } return this.internalDispatcherType; } // ---------------------------------------------------- HttpRequest Methods /** * Add a Cookie to the set of Cookies associated with this Request. * * @param cookie The new cookie */ public void addCookie(Cookie cookie) { if (!cookiesParsed) { parseCookies(); } int size = 0; if (cookies != null) { size = cookies.length; } Cookie[] newCookies = new Cookie[size + 1]; for (int i = 0; i < size; i++) { newCookies[i] = cookies[i]; } newCookies[size] = cookie; cookies = newCookies; } /** * Add a Locale to the set of preferred Locales for this Request. The * first added Locale will be the first one returned by getLocales(). * * @param locale The new preferred Locale */ public void addLocale(Locale locale) { locales.add(locale); } /** * Clear the collection of Cookies associated with this Request. */ public void clearCookies() { cookiesParsed = true; cookies = null; } /** * Clear the collection of Locales associated with this Request. */ public void clearLocales() { locales.clear(); } /** * Set the authentication type used for this request, if any; otherwise * set the type to <code>null</code>. Typical values are "BASIC", * "DIGEST", or "SSL". * * @param type The authentication type used */ public void setAuthType(String type) { this.authType = type; } /** * Set the path information for this Request. This will normally be called * when the associated Context is mapping the Request to a particular * Wrapper. * * @param path The path information */ public void setPathInfo(String path) { mappingData.pathInfo.setString(path); } /** * Set a flag indicating whether or not the requested session ID for this * request came in through a cookie. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionCookie(boolean flag) { this.requestedSessionCookie = flag; } /** * Set the requested session ID for this request. This is normally called * by the HTTP Connector, when it parses the request headers. * * @param id The new session id */ public void setRequestedSessionId(String id) { this.requestedSessionId = id; } /** * Set a flag indicating whether or not the requested session ID for this * request came in through a URL. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionURL(boolean flag) { this.requestedSessionURL = flag; } /** * Set a flag indicating whether or not the requested session ID for this * request came in through SSL. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionSSL(boolean flag) { this.requestedSessionSSL = flag; } /** * Get the decoded request URI. * * @return the URL decoded request URI */ public String getDecodedRequestURI() { return coyoteRequest.decodedURI().toString(); } /** * Get the decoded request URI. * * @return the URL decoded request URI */ public MessageBytes getDecodedRequestURIMB() { return coyoteRequest.decodedURI(); } /** * Set the Principal who has been authenticated for this Request. This * value is also used to calculate the value to be returned by the * <code>getRemoteUser()</code> method. * * @param principal The user Principal */ public void setUserPrincipal(Principal principal) { if (Globals.IS_SECURITY_ENABLED){ HttpSession session = getSession(false); if ( (subject != null) && (!subject.getPrincipals().contains(principal)) ){ subject.getPrincipals().add(principal); } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) { subject = new Subject(); subject.getPrincipals().add(principal); } if (session != null){ session.setAttribute(Globals.SUBJECT_ATTR, subject); } } this.userPrincipal = principal; } // --------------------------------------------- HttpServletRequest Methods /** * {@inheritDoc} * * @since Servlet 3.1 */ @Override public <T extends HttpUpgradeHandler> T upgrade( Class<T> httpUpgradeHandlerClass) throws java.io.IOException { T handler; try { handler = (T) context.getInstanceManager().newInstance(httpUpgradeHandlerClass); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NamingException e) { throw new IOException(e); } coyoteRequest.action(ActionCode.UPGRADE, handler); // Output required by RFC2616. Protocol specific headers should have // already been set. response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); response.flushBuffer(); return handler; } /** * Return the authentication type used for this Request. */ @Override public String getAuthType() { return authType; } /** * Return the portion of the request URI used to select the Context * of the Request. */ @Override public String getContextPath() { return mappingData.contextPath.toString(); } /** * Return the set of Cookies received with this Request. */ @Override public Cookie[] getCookies() { if (!cookiesParsed) { parseCookies(); } return cookies; } /** * Return the value of the specified date header, if any; otherwise * return -1. * * @param name Name of the requested date header * * @exception IllegalArgumentException if the specified header value * cannot be converted to a date */ @Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return (-1L); } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat.parseDate(value, formats); if (result != (-1L)) { return result; } throw new IllegalArgumentException(value); } /** * Return the first value of the specified header, if any; otherwise, * return <code>null</code> * * @param name Name of the requested header */ @Override public String getHeader(String name) { return coyoteRequest.getHeader(name); } /** * Return all of the values of the specified header, if any; otherwise, * return an empty enumeration. * * @param name Name of the requested header */ @Override public Enumeration<String> getHeaders(String name) { return coyoteRequest.getMimeHeaders().values(name); } /** * Return the names of all headers received with this request. */ @Override public Enumeration<String> getHeaderNames() { return coyoteRequest.getMimeHeaders().names(); } /** * Return the value of the specified header as an integer, or -1 if there * is no such header for this request. * * @param name Name of the requested header * * @exception IllegalArgumentException if the specified header value * cannot be converted to an integer */ @Override public int getIntHeader(String name) { String value = getHeader(name); if (value == null) { return (-1); } return Integer.parseInt(value); } /** * Return the HTTP request method used in this Request. */ @Override public String getMethod() { return coyoteRequest.method().toString(); } /** * Return the path information associated with this Request. */ @Override public String getPathInfo() { return mappingData.pathInfo.toString(); } /** * Return the extra path information for this request, translated * to a real path. */ @Override public String getPathTranslated() { if (context == null) { return null; } if (getPathInfo() == null) { return null; } return context.getServletContext().getRealPath(getPathInfo()); } /** * Return the query string associated with this request. */ @Override public String getQueryString() { return coyoteRequest.queryString().toString(); } /** * Return the name of the remote user that has been authenticated * for this Request. */ @Override public String getRemoteUser() { if (userPrincipal == null) { return null; } return userPrincipal.getName(); } /** * Get the request path. * * @return the request path */ public MessageBytes getRequestPathMB() { return mappingData.requestPath; } /** * Return the session identifier included in this request, if any. */ @Override public String getRequestedSessionId() { return requestedSessionId; } /** * Return the request URI for this request. */ @Override public String getRequestURI() { return coyoteRequest.requestURI().toString(); } /** * Reconstructs the URL the client used to make the request. * The returned URL contains a protocol, server name, port * number, and server path, but it does not include query * string parameters. * <p> * Because this method returns a <code>StringBuffer</code>, * not a <code>String</code>, you can modify the URL easily, * for example, to append query parameters. * <p> * This method is useful for creating redirect messages and * for reporting errors. * * @return A <code>StringBuffer</code> object containing the * reconstructed URL */ @Override public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); String scheme = getScheme(); int port = getServerPort(); if (port < 0) { port = 80; // Work around java.net.URL bug } url.append(scheme); url.append("://"); url.append(getServerName()); if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) { url.append(':'); url.append(port); } url.append(getRequestURI()); return url; } /** * Return the portion of the request URI used to select the servlet * that will process this request. */ @Override public String getServletPath() { return (mappingData.wrapperPath.toString()); } /** * Return the session associated with this Request, creating one * if necessary. */ @Override public HttpSession getSession() { Session session = doGetSession(true); if (session == null) { return null; } return session.getSession(); } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ @Override public HttpSession getSession(boolean create) { Session session = doGetSession(create); if (session == null) { return null; } return session.getSession(); } /** * Return <code>true</code> if the session identifier included in this * request came from a cookie. */ @Override public boolean isRequestedSessionIdFromCookie() { if (requestedSessionId == null) { return false; } return requestedSessionCookie; } /** * Return <code>true</code> if the session identifier included in this * request came from the request URI. */ @Override public boolean isRequestedSessionIdFromURL() { if (requestedSessionId == null) { return false; } return requestedSessionURL; } /** * Return <code>true</code> if the session identifier included in this * request came from the request URI. * * @deprecated As of Version 2.1 of the Java Servlet API, use * <code>isRequestedSessionIdFromURL()</code> instead. */ @Override @Deprecated public boolean isRequestedSessionIdFromUrl() { return (isRequestedSessionIdFromURL()); } /** * Return <code>true</code> if the session identifier included in this * request identifies a valid session. */ @Override public boolean isRequestedSessionIdValid() { if (requestedSessionId == null) { return false; } if (context == null) { return false; } Manager manager = context.getManager(); if (manager == null) { return false; } Session session = null; try { session = manager.findSession(requestedSessionId); } catch (IOException e) { // Can't find the session } if ((session == null) || !session.isValid()) { // Check for parallel deployment contexts if (getMappingData().contexts == null) { return false; } else { for (int i = (getMappingData().contexts.length); i > 0; i--) { Context ctxt = getMappingData().contexts[i - 1]; try { if (ctxt.getManager().findSession(requestedSessionId) != null) { return true; } } catch (IOException e) { // Ignore } } return false; } } return true; } /** * Return <code>true</code> if the authenticated user principal * possesses the specified role name. * * @param role Role name to be validated */ @Override public boolean isUserInRole(String role) { // Have we got an authenticated principal at all? if (userPrincipal == null) { return false; } // Identify the Realm we will use for checking role assignments if (context == null) { return false; } Realm realm = context.getRealm(); if (realm == null) { return false; } // Check for a role defined directly as a <security-role> return (realm.hasRole(wrapper, userPrincipal, role)); } /** * Return the principal that has been authenticated for this Request. */ public Principal getPrincipal() { return userPrincipal; } /** * Return the principal that has been authenticated for this Request. */ @Override public Principal getUserPrincipal() { if (userPrincipal instanceof TomcatPrincipal) { return ((TomcatPrincipal) userPrincipal).getUserPrincipal(); } return userPrincipal; } /** * Return the session associated with this Request, creating one * if necessary. */ public Session getSessionInternal() { return doGetSession(true); } /** * Change the ID of the session that this request is associated with. There * are several things that may trigger an ID change. These include moving * between nodes in a cluster and session fixation prevention during the * authentication process. * * @param newSessionId The session to change the session ID for */ public void changeSessionId(String newSessionId) { // This should only ever be called if there was an old session ID but // double check to be sure if (requestedSessionId != null && requestedSessionId.length() > 0) { requestedSessionId = newSessionId; } if (context != null && !context.getServletContext() .getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { return; } if (response != null) { Cookie newCookie = ApplicationSessionCookieConfig.createSessionCookie(context, newSessionId, secure); response.addSessionCookieInternal(newCookie); } } /** * Changes the session ID of the session associated with this request. * * @return the old session ID before it was changed * @see javax.servlet.http.HttpSessionIdListener * @since Servlet 3.1 */ @Override public String changeSessionId() { Session session = this.getSessionInternal(false); if (session == null) { throw new IllegalStateException( sm.getString("coyoteRequest.changeSessionId")); } Manager manager = this.getContext().getManager(); manager.changeSessionId(session); String newSessionId = session.getId(); this.changeSessionId(newSessionId); return newSessionId; } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ public Session getSessionInternal(boolean create) { return doGetSession(create); } /** * Get the event associated with the request. * @return the event */ public CometEventImpl getEvent() { if (event == null) { event = new CometEventImpl(this, response); } return event; } /** * Return true if the current request is handling Comet traffic. */ public boolean isComet() { return comet; } /** * Set comet state. */ public void setComet(boolean comet) { this.comet = comet; } /** * return true if we have parsed parameters */ public boolean isParametersParsed() { return parametersParsed; } /** * Return true if bytes are available. */ public boolean getAvailable() { return (inputBuffer.available() > 0); } /** * Return true if an attempt has been made to read the request body and all * of the request body has been read */ public boolean isFinished() { AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.REQUEST_BODY_FULLY_READ, result); return result.get(); } /** * Disable swallowing of remaining input if configured */ protected void checkSwallowInput() { Context context = getContext(); if (context != null && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } } public void cometClose() { coyoteRequest.action(ActionCode.COMET_CLOSE,getEvent()); setComet(false); } public void setCometTimeout(long timeout) { coyoteRequest.action(ActionCode.COMET_SETTIMEOUT, Long.valueOf(timeout)); } /** * @throws IOException If an I/O error occurs * @throws IllegalStateException If the response has been committed * @throws ServletException If the caller is responsible for handling the * error and the container has NOT set the HTTP response code etc. */ @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { if (response.isCommitted()) { throw new IllegalStateException( sm.getString("coyoteRequest.authenticate.ise")); } return context.getAuthenticator().authenticate(this, response); } /** * {@inheritDoc} */ @Override public void login(String username, String password) throws ServletException { if (getAuthType() != null || getRemoteUser() != null || getUserPrincipal() != null) { throw new ServletException( sm.getString("coyoteRequest.alreadyAuthenticated")); } if (context.getAuthenticator() == null) { throw new ServletException("no authenticator"); } context.getAuthenticator().login(username, password, this); } /** * {@inheritDoc} */ @Override public void logout() throws ServletException { context.getAuthenticator().logout(this); } /** * {@inheritDoc} */ @Override public Collection<Part> getParts() throws IOException, IllegalStateException, ServletException { parseParts(); if (partsParseException != null) { if (partsParseException instanceof IOException) { throw (IOException) partsParseException; } else if (partsParseException instanceof IllegalStateException) { throw (IllegalStateException) partsParseException; } else if (partsParseException instanceof ServletException) { throw (ServletException) partsParseException; } } return parts; } private void parseParts() { // Return immediately if the parts have already been parsed if (parts != null || partsParseException != null) { return; } MultipartConfigElement mce = getWrapper().getMultipartConfigElement(); if (mce == null) { if(getContext().getAllowCasualMultipartParsing()) { mce = new MultipartConfigElement(null, connector.getMaxPostSize(), connector.getMaxPostSize(), connector.getMaxPostSize()); } else { parts = Collections.emptyList(); return; } } Parameters parameters = coyoteRequest.getParameters(); parameters.setLimit(getConnector().getMaxParameterCount()); boolean success = false; try { File location; String locationStr = mce.getLocation(); if (locationStr == null || locationStr.length() == 0) { location = ((File) context.getServletContext().getAttribute( ServletContext.TEMPDIR)); } else { // If relative, it is relative to TEMPDIR location = new File(locationStr); if (!location.isAbsolute()) { location = new File( (File) context.getServletContext().getAttribute( ServletContext.TEMPDIR), locationStr).getAbsoluteFile(); } } if (!location.isDirectory()) { partsParseException = new IOException( sm.getString("coyoteRequest.uploadLocationInvalid", location)); return; } // Create a new file upload handler DiskFileItemFactory factory = new DiskFileItemFactory(); try { factory.setRepository(location.getCanonicalFile()); } catch (IOException ioe) { partsParseException = ioe; return; } factory.setSizeThreshold(mce.getFileSizeThreshold()); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); upload.setFileSizeMax(mce.getMaxFileSize()); upload.setSizeMax(mce.getMaxRequestSize()); parts = new ArrayList<>(); try { List<FileItem> items = upload.parseRequest(new ServletRequestContext(this)); int maxPostSize = getConnector().getMaxPostSize(); int postSize = 0; String enc = getCharacterEncoding(); Charset charset = null; if (enc != null) { try { charset = B2CConverter.getCharset(enc); } catch (UnsupportedEncodingException e) { // Ignore } } for (FileItem item : items) { ApplicationPart part = new ApplicationPart(item, mce); parts.add(part); if (part.getSubmittedFileName() == null) { String name = part.getName(); String value = null; try { String encoding = parameters.getEncoding(); if (encoding == null) { if (enc == null) { encoding = Parameters.DEFAULT_ENCODING; } else { encoding = enc; } } value = part.getString(encoding); } catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } } if (maxPostSize > 0) { // Have to calculate equivalent size. Not completely // accurate but close enough. if (charset == null) { // Name length postSize += name.getBytes().length; } else { postSize += name.getBytes(charset).length; } if (value != null) { // Equals sign postSize++; // Value length postSize += part.getSize(); } // Value separator postSize++; if (postSize > maxPostSize) { throw new IllegalStateException(sm.getString( "coyoteRequest.maxPostSizeExceeded")); } } parameters.addParameter(name, value); } } success = true; } catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); } catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); } catch (FileUploadException e) { partsParseException = new IOException(e); } catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; } } finally { if (partsParseException != null || !success) { parameters.setParseFailed(true); } } } /** * {@inheritDoc} */ @Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; } // ------------------------------------------------------ Protected Methods protected Session doGetSession(boolean create) { // There cannot be a session if no context has been assigned yet if (context == null) { return (null); } // Return the current session if it exists and is valid if ((session != null) && !session.isValid()) { session = null; } if (session != null) { return (session); } // Return the requested session if it exists and is valid Manager manager = null; if (context != null) { manager = context.getManager(); } if (manager == null) { return (null); // Sessions are not supported } if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) { session = null; } if (session != null) { session.access(); return (session); } } // Create a new session if requested and the response is not committed if (!create) { return (null); } if ((context != null) && (response != null) && context.getServletContext().getEffectiveSessionTrackingModes(). contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) { throw new IllegalStateException (sm.getString("coyoteRequest.sessionCreateCommitted")); } // Attempt to reuse session id if one was submitted in a cookie // Do not reuse the session id if it is from a URL, to prevent possible // phishing attacks // Use the SSL session ID if one is present. if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie()) || requestedSessionSSL ) { session = manager.createSession(getRequestedSessionId()); } else { session = manager.createSession(null); } // Creating a new session cookie based on that session if ((session != null) && (getContext() != null) && getContext().getServletContext(). getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } if (session == null) { return null; } session.access(); return session; } protected String unescape(String s) { if (s==null) { return null; } if (s.indexOf('\\') == -1) { return s; } StringBuilder buf = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c!='\\') { buf.append(c); } else { if (++i >= s.length()) { throw new IllegalArgumentException();//invalid escape, hence invalid cookie } c = s.charAt(i); buf.append(c); } } return buf.toString(); } /** * Parse cookies. */ protected void parseCookies() { cookiesParsed = true; Cookies serverCookies = coyoteRequest.getCookies(); int count = serverCookies.getCookieCount(); if (count <= 0) { return; } cookies = new Cookie[count]; int idx=0; for (int i = 0; i < count; i++) { ServerCookie scookie = serverCookies.getCookie(i); try { /* we must unescape the '\\' escape character */ Cookie cookie = new Cookie(scookie.getName().toString(),null); int version = scookie.getVersion(); cookie.setVersion(version); cookie.setValue(unescape(scookie.getValue().toString())); cookie.setPath(unescape(scookie.getPath().toString())); String domain = scookie.getDomain().toString(); if (domain!=null) { cookie.setDomain(unescape(domain));//avoid NPE } String comment = scookie.getComment().toString(); cookie.setComment(version==1?unescape(comment):null); cookies[idx++] = cookie; } catch(IllegalArgumentException e) { // Ignore bad cookie } } if( idx < count ) { Cookie [] ncookies = new Cookie[idx]; System.arraycopy(cookies, 0, ncookies, 0, idx); cookies = ncookies; } } /** * Parse request parameters. */ protected void parseParameters() { parametersParsed = true; Parameters parameters = coyoteRequest.getParameters(); boolean success = false; try { // Set this every time in case limit has been changed via JMX parameters.setLimit(getConnector().getMaxParameterCount()); // getCharacterEncoding() may have been overridden to search for // hidden form field containing request encoding String enc = getCharacterEncoding(); boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI(); if (enc != null) { parameters.setEncoding(enc); if (useBodyEncodingForURI) { parameters.setQueryStringEncoding(enc); } } else { parameters.setEncoding (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); if (useBodyEncodingForURI) { parameters.setQueryStringEncoding (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); } } parameters.handleQueryParameters(); if (usingInputStream || usingReader) { success = true; return; } if( !getConnector().isParseBodyMethod(getMethod()) ) { success = true; return; } String contentType = getContentType(); if (contentType == null) { contentType = ""; } int semicolon = contentType.indexOf(';'); if (semicolon >= 0) { contentType = contentType.substring(0, semicolon).trim(); } else { contentType = contentType.trim(); } if ("multipart/form-data".equals(contentType)) { parseParts(); success = true; return; } if (!("application/x-www-form-urlencoded".equals(contentType))) { success = true; return; } int len = getContentLength(); if (len > 0) { int maxPostSize = connector.getMaxPostSize(); if ((maxPostSize > 0) && (len > maxPostSize)) { if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.postTooLarge")); } checkSwallowInput(); return; } byte[] formData = null; if (len < CACHED_POST_LEN) { if (postData == null) { postData = new byte[CACHED_POST_LEN]; } formData = postData; } else { formData = new byte[len]; } try { if (readPostBody(formData, len) != len) { return; } } catch (IOException e) { // Client disconnect if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; } parameters.processParameters(formData, 0, len); } else if ("chunked".equalsIgnoreCase( coyoteRequest.getHeader("transfer-encoding"))) { byte[] formData = null; try { formData = readChunkedPostBody(); } catch (IOException e) { // Client disconnect or chunkedPostTooLarge error if (context.getLogger().isDebugEnabled()) { context.getLogger().debug( sm.getString("coyoteRequest.parseParameters"), e); } return; } if (formData != null) { parameters.processParameters(formData, 0, formData.length); } } success = true; } finally { if (!success) { parameters.setParseFailed(true); } } } /** * Read post body in an array. */ protected int readPostBody(byte body[], int len) throws IOException { int offset = 0; do { int inputLen = getStream().read(body, offset, len - offset); if (inputLen <= 0) { return offset; } offset += inputLen; } while ((len - offset) > 0); return len; } /** * Read chunked post body. */ protected byte[] readChunkedPostBody() throws IOException { ByteChunk body = new ByteChunk(); byte[] buffer = new byte[CACHED_POST_LEN]; int len = 0; while (len > -1) { len = getStream().read(buffer, 0, CACHED_POST_LEN); if (connector.getMaxPostSize() > 0 && (body.getLength() + len) > connector.getMaxPostSize()) { // Too much data checkSwallowInput(); throw new IOException( sm.getString("coyoteRequest.chunkedPostTooLarge")); } if (len > 0) { body.append(buffer, 0, len); } } if (body.getLength() == 0) { return null; } if (body.getLength() < body.getBuffer().length) { int length = body.getLength(); byte[] result = new byte[length]; System.arraycopy(body.getBuffer(), 0, result, 0, length); return result; } return body.getBuffer(); } /** * Parse request locales. */ protected void parseLocales() { localesParsed = true; Enumeration<String> values = getHeaders("accept-language"); while (values.hasMoreElements()) { String value = values.nextElement(); parseLocalesHeader(value); } } /** * Parse accept-language header value. */ protected void parseLocalesHeader(String value) { // Store the accumulated languages that have been requested in // a local collection, sorted by the quality value (so we can // add Locales in descending order). The values will be ArrayLists // containing the corresponding Locales to be added TreeMap<Double, ArrayList<Locale>> locales = new TreeMap<>(); // Preprocess the value to remove all whitespace int white = value.indexOf(' '); if (white < 0) { white = value.indexOf('\t'); } if (white >= 0) { StringBuilder sb = new StringBuilder(); int len = value.length(); for (int i = 0; i < len; i++) { char ch = value.charAt(i); if ((ch != ' ') && (ch != '\t')) { sb.append(ch); } } parser.setString(sb.toString()); } else { parser.setString(value); } // Process each comma-delimited language specification int length = parser.getLength(); while (true) { // Extract the next comma-delimited entry int start = parser.getIndex(); if (start >= length) { break; } int end = parser.findChar(','); String entry = parser.extract(start, end).trim(); parser.advance(); // For the following entry // Extract the quality factor for this entry double quality = 1.0; int semi = entry.indexOf(";q="); if (semi >= 0) { try { String strQuality = entry.substring(semi + 3); if (strQuality.length() <= 5) { quality = Double.parseDouble(strQuality); } else { quality = 0.0; } } catch (NumberFormatException e) { quality = 0.0; } entry = entry.substring(0, semi); } // Skip entries we are not going to keep track of if (quality < 0.00005) { continue; // Zero (or effectively zero) quality factors } if ("*".equals(entry)) { continue; // FIXME - "*" entries are not handled } // Extract the language and country for this entry String language = null; String country = null; String variant = null; int dash = entry.indexOf('-'); if (dash < 0) { language = entry; country = ""; variant = ""; } else { language = entry.substring(0, dash); country = entry.substring(dash + 1); int vDash = country.indexOf('-'); if (vDash > 0) { String cTemp = country.substring(0, vDash); variant = country.substring(vDash + 1); country = cTemp; } else { variant = ""; } } if (!isAlpha(language) || !isAlpha(country) || !isAlpha(variant)) { continue; } // Add a new Locale to the list of Locales for this quality level Locale locale = new Locale(language, country, variant); Double key = new Double(-quality); // Reverse the order ArrayList<Locale> values = locales.get(key); if (values == null) { values = new ArrayList<>(); locales.put(key, values); } values.add(locale); } // Process the quality values in highest->lowest order (due to // negating the Double value when creating the key) for (ArrayList<Locale> list : locales.values()) { for (Locale locale : list) { addLocale(locale); } } } protected static final boolean isAlpha(String value) { for (int i = 0; i < value.length(); i++) { char c = value.charAt(i); if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) { return false; } } return true; } // ----------------------------------------------------- Special attributes handling private static interface SpecialAttributeAdapter { Object get(Request request, String name); void set(Request request, String name, Object value); // None of special attributes support removal // void remove(Request request, String name); } private static final Map<String, SpecialAttributeAdapter> specialAttributes = new HashMap<>(); static { specialAttributes.put(Globals.DISPATCHER_TYPE_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return (request.internalDispatcherType == null) ? DispatcherType.REQUEST : request.internalDispatcherType; } @Override public void set(Request request, String name, Object value) { request.internalDispatcherType = (DispatcherType) value; } }); specialAttributes.put(Globals.DISPATCHER_REQUEST_PATH_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return (request.requestDispatcherPath == null) ? request .getRequestPathMB().toString() : request.requestDispatcherPath.toString(); } @Override public void set(Request request, String name, Object value) { request.requestDispatcherPath = value; } }); specialAttributes.put(Globals.ASYNC_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return request.asyncSupported; } @Override public void set(Request request, String name, Object value) { Boolean oldValue = request.asyncSupported; request.asyncSupported = (Boolean)value; request.notifyAttributeAssigned(name, value, oldValue); } }); specialAttributes.put(Globals.GSS_CREDENTIAL_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { if (request.userPrincipal instanceof TomcatPrincipal) { return ((TomcatPrincipal) request.userPrincipal) .getGssCredential(); } return null; } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.PARAMETER_PARSE_FAILED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { if (request.getCoyoteRequest().getParameters() .isParseFailed()) { return Boolean.TRUE; } return null; } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.COMET_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return Boolean.valueOf( request.getConnector().getProtocolHandler( ).isCometSupported()); } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.COMET_TIMEOUT_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return Boolean.valueOf( request.getConnector().getProtocolHandler( ).isCometTimeoutSupported()); } @Override public void set(Request request, String name, Object value) { // NO-OP } }); specialAttributes.put(Globals.SENDFILE_SUPPORTED_ATTR, new SpecialAttributeAdapter() { @Override public Object get(Request request, String name) { return Boolean.valueOf( request.getConnector().getProtocolHandler( ).isSendfileSupported()); } @Override public void set(Request request, String name, Object value) { // NO-OP } }); } }
54,971
Bug 54971 javax.servlet.http.Part.write(String fileName) is not properly implemented
1. fileName parameter / relative vs absolute filaName parameter specification in <1><JSR-000315 Java Servlet 3.0 Final Release javadocs> is different from the <2><javax API tomcat refers to>. <1> <JSR-000315 Java Servlet 3.0 Final Release javadocs> Parameters:fileName - the name of the file to which the stream will be written. The file is created relative to the location as specified in the MultipartConfig <2> javax. API tomcat refers to * @param fileName The location into which the uploaded part should be * stored. Relative locations are relative to {@link * javax.servlet.MultipartConfigElement#getLocation()} Tomcat is implemented as specified in <2> so that it can process "absolute path", but it should only accept "relative path" as specified in <1> <JSR-000315 Java Servlet 3.0 Final Release javadocs> 2. If MultiPartConfig.location is not set, write( String relative path ) throws FileNotFound Exception. A default location needs to be set in order to avoid such exception. example) os: windows8 part.write("/test"); java.io.IOException: java.io.FileNotFoundException: \test (Access is denied) at org.apache.catalina.core.ApplicationPart.write(ApplicationPart.java:123) at servlet.multipart.MultipleUploadServlet.doPost(MultipleUploadServlet.java:76) at javax.servlet.http.HttpServlet.service(HttpServlet.java:647) at javax.servlet.http.HttpServlet.service(HttpServlet.java:728) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918) at java.lang.Thread.run(Thread.java:662)
resolved fixed
cccd0ac
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-28T14:37:50Z
2013-05-15T06:40:00Z
java/org/apache/catalina/core/ApplicationPart.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.Locale; import java.util.Map; import javax.servlet.MultipartConfigElement; import javax.servlet.http.Part; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.ParameterParser; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItem; /** * Adaptor to allow {@link FileItem} objects generated by the package renamed * commons-upload to be used by the Servlet 3.0 upload API that expects * {@link Part}s. */ public class ApplicationPart implements Part { private final FileItem fileItem; private final MultipartConfigElement mce; public ApplicationPart(FileItem fileItem, MultipartConfigElement mce) { this.fileItem = fileItem; this.mce = mce; } @Override public void delete() throws IOException { fileItem.delete(); } @Override public String getContentType() { return fileItem.getContentType(); } @Override public String getHeader(String name) { if (fileItem instanceof DiskFileItem) { return ((DiskFileItem) fileItem).getHeaders().getHeader(name); } return null; } @Override public Collection<String> getHeaderNames() { if (fileItem instanceof DiskFileItem) { HashSet<String> headerNames = new HashSet<>(); Iterator<String> iter = ((DiskFileItem) fileItem).getHeaders().getHeaderNames(); while (iter.hasNext()) { headerNames.add(iter.next()); } return headerNames; } return Collections.emptyList(); } @Override public Collection<String> getHeaders(String name) { if (fileItem instanceof DiskFileItem) { HashSet<String> headers = new HashSet<>(); Iterator<String> iter = ((DiskFileItem) fileItem).getHeaders().getHeaders(name); while (iter.hasNext()) { headers.add(iter.next()); } return headers; } return Collections.emptyList(); } @Override public InputStream getInputStream() throws IOException { return fileItem.getInputStream(); } @Override public String getName() { return fileItem.getFieldName(); } @Override public long getSize() { return fileItem.getSize(); } @Override public void write(String fileName) throws IOException { File file = new File(fileName); if (!file.isAbsolute()) { file = new File(mce.getLocation(), fileName); } try { fileItem.write(file); } catch (Exception e) { throw new IOException(e); } } public String getString(String encoding) throws UnsupportedEncodingException { return fileItem.getString(encoding); } /* * Adapted from FileUploadBase.getFileName() */ @Override public String getSubmittedFileName() { String fileName = null; String cd = getHeader("Content-Disposition"); if (cd != null) { String cdl = cd.toLowerCase(Locale.ENGLISH); if (cdl.startsWith("form-data") || cdl.startsWith("attachment")) { ParameterParser paramParser = new ParameterParser(); paramParser.setLowerCaseNames(true); // Parameter parser can handle null input Map<String,String> params = paramParser.parse(cd, ';'); if (params.containsKey("filename")) { fileName = params.get("filename"); if (fileName != null) { fileName = fileName.trim(); } else { // Even if there is no value, the parameter is present, // so we return an empty file name rather than no file // name. fileName = ""; } } } } return fileName; } }
54,997
Bug 54997 SSL Handshake implementation in AsycnChannelWrapperSecure does not handle SSLEngineResult.Status.BUFFER_UNDERFLOW and SSLEngineResult.Status.BUFFER_OVERFLOW states
null
resolved fixed
6c6b25c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-29T10:17:20Z
2013-05-21T12:40:00Z
java/org/apache/tomcat/websocket/AsyncChannelWrapperSecure.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; /** * Wraps the {@link AsynchronousSocketChannel} with SSL/TLS. This needs a lot * more testing before it can be considered robust. */ public class AsyncChannelWrapperSecure implements AsyncChannelWrapper { private static final ByteBuffer DUMMY = ByteBuffer.allocate(8192); private final AsynchronousSocketChannel socketChannel; private final SSLEngine sslEngine; private final ByteBuffer socketReadBuffer; private final ByteBuffer socketWriteBuffer; // One thread for read, one for write private final ExecutorService executor = Executors.newFixedThreadPool(2); private AtomicBoolean writing = new AtomicBoolean(false); private AtomicBoolean reading = new AtomicBoolean(false); public AsyncChannelWrapperSecure(AsynchronousSocketChannel socketChannel, SSLEngine sslEngine) { this.socketChannel = socketChannel; this.sslEngine = sslEngine; int socketBufferSize = sslEngine.getSession().getPacketBufferSize(); socketReadBuffer = ByteBuffer.allocateDirect(socketBufferSize); socketWriteBuffer = ByteBuffer.allocateDirect(socketBufferSize); } @Override public Future<Integer> read(ByteBuffer dst) { WrapperFuture<Integer,Void> future = new WrapperFuture<>(); if (!reading.compareAndSet(false, true)) { // TODO throw new IllegalStateException(); } ReadTask readTask = new ReadTask(dst, future); executor.execute(readTask); return future; } @Override public <A> void read(ByteBuffer dst, A attachment, CompletionHandler<Integer,? super A> handler) { WrapperFuture<Integer,? super A> future = new WrapperFuture<>(handler, attachment); if (!reading.compareAndSet(false, true)) { // TODO throw new IllegalStateException(); } ReadTask readTask = new ReadTask(dst, future); executor.execute(readTask); } @Override public Future<Integer> write(ByteBuffer src) { WrapperFuture<Long,Void> inner = new WrapperFuture<>(); if (!writing.compareAndSet(false, true)) { // TODO throw new IllegalStateException(); } WriteTask writeTask = new WriteTask(new ByteBuffer[] {src}, 0, 1, inner); executor.execute(writeTask); Future<Integer> future = new LongToIntegerFuture(inner); return future; } @Override public <A> void write(ByteBuffer[] srcs, int offset, int length, long timeout, TimeUnit unit, A attachment, CompletionHandler<Long,? super A> handler) { WrapperFuture<Long,? super A> future = new WrapperFuture<>(handler, attachment); if (!writing.compareAndSet(false, true)) { // TODO throw new IllegalStateException(); } WriteTask writeTask = new WriteTask(srcs, offset, length, future); executor.execute(writeTask); } @Override public void close() { try { socketChannel.close(); } catch (IOException e) { // TODO } } @Override public Future<Void> handshake() throws SSLException { WrapperFuture<Void,Void> wFuture = new WrapperFuture<>(); Thread t = new WebSocketSslHandshakeThread(wFuture); t.start(); return wFuture; } private class WriteTask implements Runnable { private final ByteBuffer[] srcs; private final int offset; private final int length; private final WrapperFuture<Long,?> future; public WriteTask(ByteBuffer[] srcs, int offset, int length, WrapperFuture<Long,?> future) { this.srcs = srcs; this.future = future; this.offset = offset; this.length = length; } @Override public void run() { long written = 0; try { for (int i = offset; i < offset + length; i++) { ByteBuffer src = srcs[i]; while (src.hasRemaining()) { socketWriteBuffer.clear(); // Encrypt the data SSLEngineResult r = sslEngine.wrap(src, socketWriteBuffer); written += r.bytesConsumed(); Status s = r.getStatus(); if (s == Status.OK || s == Status.BUFFER_OVERFLOW) { // Need to write out the bytes and may need to read from // the source again to empty it } else { // Status.BUFFER_UNDERFLOW - only happens on unwrap // Status.CLOSED - unexpected // TODO throw new IllegalStateException(); } // Check for tasks if (r.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable = sslEngine.getDelegatedTask(); while (runnable != null) { runnable.run(); runnable = sslEngine.getDelegatedTask(); } } socketWriteBuffer.flip(); // Do the write Future<Integer> f = socketChannel.write(socketWriteBuffer); Integer socketWrite = f.get(); if (socketWrite.intValue() != r.bytesProduced()) { throw new IOException(); } } } if (writing.compareAndSet(true, false)) { future.complete(Long.valueOf(written)); } else { // TODO future.fail(new IllegalStateException()); } } catch (Exception e) { future.fail(e); } } } private class ReadTask implements Runnable { private final ByteBuffer dest; private final WrapperFuture<Integer,?> future; public ReadTask(ByteBuffer dest, WrapperFuture<Integer,?> future) { this.dest = dest; this.future = future; } @Override public void run() { int read = 0; boolean forceRead = false; try { while (read == 0) { socketReadBuffer.compact(); if (forceRead) { Future<Integer> f = socketChannel.read(socketReadBuffer); Integer socketRead = f.get(); if (socketRead.intValue() == -1) { // TODO throw new EOFException(); } } socketReadBuffer.flip(); if (socketReadBuffer.hasRemaining()) { // Decrypt the data in the buffer SSLEngineResult r = sslEngine.unwrap(socketReadBuffer, dest); read += r.bytesProduced(); Status s = r.getStatus(); if (s == Status.OK || s == Status.BUFFER_OVERFLOW) { // Bytes available for reading and there may be // sufficientNeed data in the socketReadBuffer to // support further reads without reading from the // socket } else if (s == Status.BUFFER_UNDERFLOW) { // There is partial data in the socketReadBuffer if (read == 0) { // Need more data before the partial data can be // processed and some output generated forceRead = true; } // else return the data we have and deal with the // partial data on the next read } else { // Status.CLOSED - unexpected // TODO throw new IllegalStateException(); } // Check for tasks if (r.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable = sslEngine.getDelegatedTask(); while (runnable != null) { runnable.run(); runnable = sslEngine.getDelegatedTask(); } } } else { forceRead = true; } } if (reading.compareAndSet(true, false)) { future.complete(Integer.valueOf(read)); } else { // TODO future.fail(new IllegalStateException()); } } catch (Exception e) { future.fail(e); } } } private class WebSocketSslHandshakeThread extends Thread { private final WrapperFuture<Void,Void> hFuture; public WebSocketSslHandshakeThread(WrapperFuture<Void,Void> hFuture) { this.hFuture = hFuture; } @Override public void run() { try { sslEngine.beginHandshake(); // So the first compact does the right thing socketReadBuffer.position(socketReadBuffer.limit()); HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus(); boolean handshaking = true; while(handshaking) { switch (handshakeStatus) { case NEED_WRAP: { socketWriteBuffer.clear(); SSLEngineResult r = sslEngine.wrap(DUMMY, socketWriteBuffer); handshakeStatus = checkResult(r, true); socketWriteBuffer.flip(); Future<Integer> fWrite = socketChannel.write(socketWriteBuffer); fWrite.get(); break; } case NEED_UNWRAP: { socketReadBuffer.compact(); if (socketReadBuffer.position() == 0) { Future<Integer> fRead = socketChannel.read(socketReadBuffer); fRead.get(); } socketReadBuffer.flip(); SSLEngineResult r = sslEngine.unwrap(socketReadBuffer, DUMMY); handshakeStatus = checkResult(r, false); break; } case NEED_TASK: { Runnable r = null; while ((r = sslEngine.getDelegatedTask()) != null) { r.run(); } handshakeStatus = sslEngine.getHandshakeStatus(); break; } case FINISHED: { handshaking = false; break; } default: { throw new SSLException("TODO"); } } } } catch (SSLException | InterruptedException | ExecutionException e) { hFuture.fail(e); } hFuture.complete(null); } private HandshakeStatus checkResult(SSLEngineResult result, boolean wrap) throws SSLException { if (result.getStatus() != Status.OK) { throw new SSLException("TODO"); } if (wrap && result.bytesConsumed() != 0) { throw new SSLException("TODO"); } if (!wrap && result.bytesProduced() != 0) { throw new SSLException("TODO"); } return result.getHandshakeStatus(); } } private static class WrapperFuture<T,A> implements Future<T> { private final CompletionHandler<T,A> handler; private final A attachment; private volatile T result = null; private volatile Throwable throwable = null; private CountDownLatch completionLatch = new CountDownLatch(1); public WrapperFuture() { this(null, null); } public WrapperFuture(CompletionHandler<T,A> handler, A attachment) { this.handler = handler; this.attachment = attachment; } public void complete(T result) { this.result = result; completionLatch.countDown(); if (handler != null) { handler.completed(result, attachment); } } public void fail(Throwable t) { throwable = t; completionLatch.countDown(); if (handler != null) { handler.failed(throwable, attachment); } } @Override public final boolean cancel(boolean mayInterruptIfRunning) { // Could support cancellation by closing the connection return false; } @Override public final boolean isCancelled() { // Could support cancellation by closing the connection return false; } @Override public final boolean isDone() { return completionLatch.getCount() > 0; } @Override public T get() throws InterruptedException, ExecutionException { completionLatch.await(); if (throwable != null) { throw new ExecutionException(throwable); } return result; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { completionLatch.await(timeout, unit); if (throwable != null) { throw new ExecutionException(throwable); } return result; } } private static final class LongToIntegerFuture implements Future<Integer> { private final Future<Long> wrapped; public LongToIntegerFuture(Future<Long> wrapped) { this.wrapped = wrapped; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return wrapped.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return wrapped.isCancelled(); } @Override public boolean isDone() { return wrapped.isDone(); } @Override public Integer get() throws InterruptedException, ExecutionException { Long result = wrapped.get(); if (result.longValue() > Integer.MAX_VALUE) { // TODO throw new ExecutionException("Result too big", null); } return new Integer(result.intValue()); } @Override public Integer get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Long result = wrapped.get(timeout, unit); if (result.longValue() > Integer.MAX_VALUE) { // TODO throw new ExecutionException("Result too big", null); } return new Integer(result.intValue()); } } }
54,999
Bug 54999 JSESSIONIDSSO not re-created upon re-authentication on the same request - logout() and login(username,password)
In testing I found that the JSESSIONIDSSO was not re-created upon re-authentication via logout() and login(username,password) in the same request. The problem stemmed from the REQ_SSOID_NOTE that was was not reset upon request.logout(), whereas the documentation indicates that a logout() from any web-app should logout() from all web-apps. When the REQ_SSOID_NOTE is not removed upon logout(), a subsequent login(username,password) on the same request will re-create a JSESSIONID for the current web-app but fails to re-create a JSESSIONIDSSO since the REQ_SSO_ID_NOTE still lingers on the request. AuthenticatorBase.java adjustment for logout(request) that removes the REQ_SSOID_NOTE so that a subsequent login(username,password) will work on the same request: @Override public void logout(Request request) throws ServletException { register(request, request.getResponse(), null, null, null, null); request.removeNote(Constants.REQ_SSOID_NOTE); } I'll upload a diff-patch against the trunk and for 7.0.40.
resolved fixed
6d789fe
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-05-30T13:49:40Z
2013-05-21T23:46:40Z
java/org/apache/catalina/authenticator/AuthenticatorBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.io.IOException; import java.security.Principal; import java.security.cert.X509Certificate; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Authenticator; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.LifecycleException; import org.apache.catalina.Manager; import org.apache.catalina.Realm; import org.apache.catalina.Session; import org.apache.catalina.Valve; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.util.SessionIdGenerator; import org.apache.catalina.valves.ValveBase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.res.StringManager; /** * Basic implementation of the <b>Valve</b> interface that enforces the * <code>&lt;security-constraint&gt;</code> elements in the web application * deployment descriptor. This functionality is implemented as a Valve * so that it can be omitted in environments that do not require these * features. Individual implementations of each supported authentication * method can subclass this base class as required. * <p> * <b>USAGE CONSTRAINT</b>: When this class is utilized, the Context to * which it is attached (or a parent Container in a hierarchy) must have an * associated Realm that can be used for authenticating users and enumerating * the roles to which they have been assigned. * <p> * <b>USAGE CONSTRAINT</b>: This Valve is only useful when processing HTTP * requests. Requests of any other type will simply be passed through. * * @author Craig R. McClanahan * @version $Id$ */ public abstract class AuthenticatorBase extends ValveBase implements Authenticator { private static final Log log = LogFactory.getLog(AuthenticatorBase.class); //------------------------------------------------------ Constructor public AuthenticatorBase() { super(true); } // ----------------------------------------------------- Instance Variables /** * Authentication header */ protected static final String AUTH_HEADER_NAME = "WWW-Authenticate"; /** * Default authentication realm name. */ protected static final String REALM_NAME = "Authentication required"; /** * Should a session always be used once a user is authenticated? This may * offer some performance benefits since the session can then be used to * cache the authenticated Principal, hence removing the need to * authenticate the user via the Realm on every request. This may be of help * for combinations such as BASIC authentication used with the JNDIRealm or * DataSourceRealms. However there will also be the performance cost of * creating and GC'ing the session. By default, a session will not be * created. */ protected boolean alwaysUseSession = false; /** * Should we cache authenticated Principals if the request is part of * an HTTP session? */ protected boolean cache = true; /** * Should the session ID, if any, be changed upon a successful * authentication to prevent a session fixation attack? */ protected boolean changeSessionIdOnAuthentication = true; /** * The Context to which this Valve is attached. */ protected Context context = null; /** * Flag to determine if we disable proxy caching, or leave the issue * up to the webapp developer. */ protected boolean disableProxyCaching = true; /** * Flag to determine if we disable proxy caching with headers incompatible * with IE. */ protected boolean securePagesWithPragma = false; /** * The Java class name of the secure random number generator class to be * used when generating SSO session identifiers. The random number generator * class must be self-seeding and have a zero-argument constructor. If not * specified, an instance of {@link java.security.SecureRandom} will be * generated. */ protected String secureRandomClass = null; /** * The name of the algorithm to use to create instances of * {@link java.security.SecureRandom} which are used to generate SSO session * IDs. If no algorithm is specified, SHA1PRNG is used. To use the platform * default (which may be SHA1PRNG), specify the empty string. If an invalid * algorithm and/or provider is specified the SecureRandom instances will be * created using the defaults. If that fails, the SecureRandom instances * will be created using platform defaults. */ protected String secureRandomAlgorithm = "SHA1PRNG"; /** * The name of the provider to use to create instances of * {@link java.security.SecureRandom} which are used to generate session SSO * IDs. If no algorithm is specified the of SHA1PRNG default is used. If an * invalid algorithm and/or provider is specified the SecureRandom instances * will be created using the defaults. If that fails, the SecureRandom * instances will be created using platform defaults. */ protected String secureRandomProvider = null; protected SessionIdGenerator sessionIdGenerator = null; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The SingleSignOn implementation in our request processing chain, * if there is one. */ protected SingleSignOn sso = null; /** * "Expires" header always set to Date(1), so generate once only */ private static final String DATE_ONE = (new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE, Locale.US)).format(new Date(1)); protected static String getRealmName(Context context) { if (context == null) { // Very unlikely return REALM_NAME; } LoginConfig config = context.getLoginConfig(); if (config == null) { return REALM_NAME; } String result = config.getRealmName(); if (result == null) { return REALM_NAME; } return result; } // ------------------------------------------------------------- Properties public boolean getAlwaysUseSession() { return alwaysUseSession; } public void setAlwaysUseSession(boolean alwaysUseSession) { this.alwaysUseSession = alwaysUseSession; } /** * Return the cache authenticated Principals flag. */ public boolean getCache() { return (this.cache); } /** * Set the cache authenticated Principals flag. * * @param cache The new cache flag */ public void setCache(boolean cache) { this.cache = cache; } /** * Return the Container to which this Valve is attached. */ @Override public Container getContainer() { return (this.context); } /** * Set the Container to which this Valve is attached. * * @param container The container to which we are attached */ @Override public void setContainer(Container container) { if (container != null && !(container instanceof Context)) { throw new IllegalArgumentException (sm.getString("authenticator.notContext")); } super.setContainer(container); this.context = (Context) container; } /** * Return the flag that states if we add headers to disable caching by * proxies. */ public boolean getDisableProxyCaching() { return disableProxyCaching; } /** * Set the value of the flag that states if we add headers to disable * caching by proxies. * @param nocache <code>true</code> if we add headers to disable proxy * caching, <code>false</code> if we leave the headers alone. */ public void setDisableProxyCaching(boolean nocache) { disableProxyCaching = nocache; } /** * Return the flag that states, if proxy caching is disabled, what headers * we add to disable the caching. */ public boolean getSecurePagesWithPragma() { return securePagesWithPragma; } /** * Set the value of the flag that states what headers we add to disable * proxy caching. * @param securePagesWithPragma <code>true</code> if we add headers which * are incompatible with downloading office documents in IE under SSL but * which fix a caching problem in Mozilla. */ public void setSecurePagesWithPragma(boolean securePagesWithPragma) { this.securePagesWithPragma = securePagesWithPragma; } /** * Return the flag that states if we should change the session ID of an * existing session upon successful authentication. * * @return <code>true</code> to change session ID upon successful * authentication, <code>false</code> to do not perform the change. */ public boolean getChangeSessionIdOnAuthentication() { return changeSessionIdOnAuthentication; } /** * Set the value of the flag that states if we should change the session ID * of an existing session upon successful authentication. * * @param changeSessionIdOnAuthentication * <code>true</code> to change session ID upon successful * authentication, <code>false</code> to do not perform the * change. */ public void setChangeSessionIdOnAuthentication( boolean changeSessionIdOnAuthentication) { this.changeSessionIdOnAuthentication = changeSessionIdOnAuthentication; } /** * Return the secure random number generator class name. */ public String getSecureRandomClass() { return (this.secureRandomClass); } /** * Set the secure random number generator class name. * * @param secureRandomClass The new secure random number generator class * name */ public void setSecureRandomClass(String secureRandomClass) { this.secureRandomClass = secureRandomClass; } /** * Return the secure random number generator algorithm name. */ public String getSecureRandomAlgorithm() { return secureRandomAlgorithm; } /** * Set the secure random number generator algorithm name. * * @param secureRandomAlgorithm The new secure random number generator * algorithm name */ public void setSecureRandomAlgorithm(String secureRandomAlgorithm) { this.secureRandomAlgorithm = secureRandomAlgorithm; } /** * Return the secure random number generator provider name. */ public String getSecureRandomProvider() { return secureRandomProvider; } /** * Set the secure random number generator provider name. * * @param secureRandomProvider The new secure random number generator * provider name */ public void setSecureRandomProvider(String secureRandomProvider) { this.secureRandomProvider = secureRandomProvider; } // --------------------------------------------------------- Public Methods /** * Enforce the security restrictions in the web application deployment * descriptor of our associated Context. * * @param request Request to be processed * @param response Response to be processed * * @exception IOException if an input/output error occurs * @exception ServletException if thrown by a processing element */ @Override public void invoke(Request request, Response response) throws IOException, ServletException { if (log.isDebugEnabled()) { log.debug("Security checking request " + request.getMethod() + " " + request.getRequestURI()); } // Have we got a cached authenticated Principal to record? if (cache) { Principal principal = request.getUserPrincipal(); if (principal == null) { Session session = request.getSessionInternal(false); if (session != null) { principal = session.getPrincipal(); if (principal != null) { if (log.isDebugEnabled()) { log.debug("We have cached auth type " + session.getAuthType() + " for principal " + session.getPrincipal()); } request.setAuthType(session.getAuthType()); request.setUserPrincipal(principal); } } } } // Special handling for form-based logins to deal with the case // where the login form (and therefore the "j_security_check" URI // to which it submits) might be outside the secured area String contextPath = this.context.getPath(); String requestURI = request.getDecodedRequestURI(); if (requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION)) { if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test ??" + requestURI ); } return; } } // The Servlet may specify security constraints through annotations. // Ensure that they have been processed before constraints are checked Wrapper wrapper = request.getMappingData().wrapper; if (wrapper != null) { wrapper.servletSecurityAnnotationScan(); } Realm realm = this.context.getRealm(); // Is this request URI subject to a security constraint? SecurityConstraint [] constraints = realm.findSecurityConstraints(request, this.context); if (constraints == null && !context.getPreemptiveAuthentication()) { if (log.isDebugEnabled()) { log.debug(" Not subject to any constraint"); } getNext().invoke(request, response); return; } // Make sure that constrained resources are not cached by web proxies // or browsers as caching can provide a security hole if (constraints != null && disableProxyCaching && !"POST".equalsIgnoreCase(request.getMethod())) { if (securePagesWithPragma) { // Note: These can cause problems with downloading files with IE response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); } else { response.setHeader("Cache-Control", "private"); } response.setHeader("Expires", DATE_ONE); } int i; if (constraints != null) { // Enforce any user data constraint for this security constraint if (log.isDebugEnabled()) { log.debug(" Calling hasUserDataPermission()"); } if (!realm.hasUserDataPermission(request, response, constraints)) { if (log.isDebugEnabled()) { log.debug(" Failed hasUserDataPermission() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything special */ return; } } // Since authenticate modifies the response on failure, // we have to check for allow-from-all first. boolean authRequired; if (constraints == null) { authRequired = false; } else { authRequired = true; for(i=0; i < constraints.length && authRequired; i++) { if(!constraints[i].getAuthConstraint()) { authRequired = false; } else if(!constraints[i].getAllRoles()) { String [] roles = constraints[i].findAuthRoles(); if(roles == null || roles.length == 0) { authRequired = false; } } } } if (!authRequired && context.getPreemptiveAuthentication()) { authRequired = request.getCoyoteRequest().getMimeHeaders().getValue( "authorization") != null; } if (!authRequired && context.getPreemptiveAuthentication()) { X509Certificate[] certs = (X509Certificate[]) request.getAttribute( Globals.CERTIFICATES_ATTR); authRequired = certs != null && certs.length > 0; } if(authRequired) { if (log.isDebugEnabled()) { log.debug(" Calling authenticate()"); } if (!authenticate(request, response)) { if (log.isDebugEnabled()) { log.debug(" Failed authenticate() test"); } /* * ASSERT: Authenticator already set the appropriate * HTTP status code, so we do not have to do anything * special */ return; } } if (constraints != null) { if (log.isDebugEnabled()) { log.debug(" Calling accessControl()"); } if (!realm.hasResourcePermission(request, response, constraints, this.context)) { if (log.isDebugEnabled()) { log.debug(" Failed accessControl() test"); } /* * ASSERT: AccessControl method has already set the * appropriate HTTP status code, so we do not have to do * anything special */ return; } } // Any and all specified constraints have been satisfied if (log.isDebugEnabled()) { log.debug(" Successfully passed all security constraints"); } getNext().invoke(request, response); } // ------------------------------------------------------ Protected Methods /** * Associate the specified single sign on identifier with the * specified Session. * * @param ssoId Single sign on identifier * @param session Session to be associated */ protected void associate(String ssoId, Session session) { if (sso == null) { return; } sso.associate(ssoId, session); } /** * Authenticate the user making this request, based on the login * configuration of the {@link Context} with which this Authenticator is * associated. Return <code>true</code> if any specified constraint has * been satisfied, or <code>false</code> if we have created a response * challenge already. * * @param request Request we are processing * @param response Response we are populating * * @exception IOException if an input/output error occurs */ @Override public abstract boolean authenticate(Request request, HttpServletResponse response) throws IOException; /** * Attempts reauthentication to the <code>Realm</code> using * the credentials included in argument <code>entry</code>. * * @param ssoId identifier of SingleSignOn session with which the * caller is associated * @param request the request that needs to be authenticated */ protected boolean reauthenticateFromSSO(String ssoId, Request request) { if (sso == null || ssoId == null) { return false; } boolean reauthenticated = false; Container parent = getContainer(); if (parent != null) { Realm realm = parent.getRealm(); if (realm != null) { reauthenticated = sso.reauthenticate(ssoId, realm, request); } } if (reauthenticated) { associate(ssoId, request.getSessionInternal(true)); if (log.isDebugEnabled()) { log.debug(" Reauthenticated cached principal '" + request.getUserPrincipal().getName() + "' with auth type '" + request.getAuthType() + "'"); } } return reauthenticated; } /** * Register an authenticated Principal and authentication type in our * request, in the current session (if there is one), and with our * SingleSignOn valve, if there is one. Set the appropriate cookie * to be returned. * * @param request The servlet request we are processing * @param response The servlet response we are generating * @param principal The authenticated Principal to be registered * @param authType The authentication type to be registered * @param username Username used to authenticate (if any) * @param password Password used to authenticate (if any) */ public void register(Request request, HttpServletResponse response, Principal principal, String authType, String username, String password) { if (log.isDebugEnabled()) { String name = (principal == null) ? "none" : principal.getName(); log.debug("Authenticated '" + name + "' with type '" + authType + "'"); } // Cache the authentication information in our request request.setAuthType(authType); request.setUserPrincipal(principal); Session session = request.getSessionInternal(false); if (session != null) { if (changeSessionIdOnAuthentication) { Manager manager = request.getContext().getManager(); manager.changeSessionId(session); request.changeSessionId(session.getId()); } } else if (alwaysUseSession) { session = request.getSessionInternal(true); } // Cache the authentication information in our session, if any if (cache) { if (session != null) { session.setAuthType(authType); session.setPrincipal(principal); if (username != null) { session.setNote(Constants.SESS_USERNAME_NOTE, username); } else { session.removeNote(Constants.SESS_USERNAME_NOTE); } if (password != null) { session.setNote(Constants.SESS_PASSWORD_NOTE, password); } else { session.removeNote(Constants.SESS_PASSWORD_NOTE); } } } // Construct a cookie to be returned to the client if (sso == null) { return; } // Only create a new SSO entry if the SSO did not already set a note // for an existing entry (as it would do with subsequent requests // for DIGEST and SSL authenticated contexts) String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId == null) { // Construct a cookie to be returned to the client ssoId = sessionIdGenerator.generateSessionId(); Cookie cookie = new Cookie(Constants.SINGLE_SIGN_ON_COOKIE, ssoId); cookie.setMaxAge(-1); cookie.setPath("/"); // Bugzilla 41217 cookie.setSecure(request.isSecure()); // Bugzilla 34724 String ssoDomain = sso.getCookieDomain(); if(ssoDomain != null) { cookie.setDomain(ssoDomain); } // Configure httpOnly on SSO cookie using same rules as session cookies if (request.getServletContext().getSessionCookieConfig().isHttpOnly() || request.getContext().getUseHttpOnly()) { cookie.setHttpOnly(true); } response.addCookie(cookie); // Register this principal with our SSO valve sso.register(ssoId, principal, authType, username, password); request.setNote(Constants.REQ_SSOID_NOTE, ssoId); } else { if (principal == null) { // Registering a programmatic logout sso.deregister(ssoId); return; } else { // Update the SSO session with the latest authentication data sso.update(ssoId, principal, authType, username, password); } } // Fix for Bug 10040 // Always associate a session with a new SSO reqistration. // SSO entries are only removed from the SSO registry map when // associated sessions are destroyed; if a new SSO entry is created // above for this request and the user never revisits the context, the // SSO entry will never be cleared if we don't associate the session if (session == null) { session = request.getSessionInternal(true); } sso.associate(ssoId, session); } @Override public void login(String username, String password, Request request) throws ServletException { Principal principal = doLogin(request, username, password); register(request, request.getResponse(), principal, getAuthMethod(), username, password); } protected abstract String getAuthMethod(); /** * Process the login request. * * @param request Associated request * @param username The user * @param password The password * @return The authenticated Principal * @throws ServletException */ protected Principal doLogin(Request request, String username, String password) throws ServletException { Principal p = context.getRealm().authenticate(username, password); if (p == null) { throw new ServletException(sm.getString("authenticator.loginFail")); } return p; } @Override public void logout(Request request) throws ServletException { register(request, request.getResponse(), null, null, null, null); } /** * Start this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void startInternal() throws LifecycleException { // Look up the SingleSignOn implementation in our request processing // path, if there is one Container parent = context.getParent(); while ((sso == null) && (parent != null)) { Valve valves[] = parent.getPipeline().getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof SingleSignOn) { sso = (SingleSignOn) valves[i]; break; } } if (sso == null) { parent = parent.getParent(); } } if (log.isDebugEnabled()) { if (sso != null) { log.debug("Found SingleSignOn Valve at " + sso); } else { log.debug("No SingleSignOn Valve is present"); } } sessionIdGenerator = new SessionIdGenerator(); sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); super.startInternal(); } /** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { super.stopInternal(); sso = null; } }
55,035
Bug 55035 Deploy ROOT webapp with version through text manager using Ant
Currently Ant "deploy" task does not support separate parameter "version" and, thanks to URLEncoder, there is no workaround for that. But for apps with not empty context it's possible to define version using ##, like setting path to "/someContext#someVersion". For apps with empty context we receive error: Case #1: <deploy url="{tomcat.manager}/text" username="${username}", password="${password}" path="/ROOT##12345" war="${pathtowar}" /> Result: Failed to deploy application at context path /ROOT##12345 Case #1: <deploy url="{tomcat.manager}/text" username="${username}", password="${password}" path="/##12345" war="${pathtowar}" /> Result: Failed to deploy application at context path /##12345
resolved fixed
712a351
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-03T20:58:17Z
2013-05-31T19:53:20Z
java/org/apache/catalina/ant/DeployTask.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.ant; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; import org.apache.tools.ant.BuildException; /** * Ant task that implements the <code>/deploy</code> command, supported by * the Tomcat manager application. * * @author Craig R. McClanahan * @version $Id$ * @since 4.1 */ public class DeployTask extends AbstractCatalinaTask { // ------------------------------------------------------------- Properties /** * URL of the context configuration file for this application, if any. */ protected String config = null; public String getConfig() { return (this.config); } public void setConfig(String config) { this.config = config; } /** * URL of the server local web application archive (WAR) file * to be deployed. */ protected String localWar = null; public String getLocalWar() { return (this.localWar); } public void setLocalWar(String localWar) { this.localWar = localWar; } /** * The context path of the web application we are managing. */ protected String path = null; public String getPath() { return (this.path); } public void setPath(String path) { this.path = path; } /** * Tag to associate with this to be deployed webapp. */ protected String tag = null; public String getTag() { return (this.tag); } public void setTag(String tag) { this.tag = tag; } /** * Update existing webapps. */ protected boolean update = false; public boolean getUpdate() { return (this.update); } public void setUpdate(boolean update) { this.update = update; } /** * URL of the web application archive (WAR) file to be deployed. */ protected String war = null; public String getWar() { return (this.war); } public void setWar(String war) { this.war = war; } // --------------------------------------------------------- Public Methods /** * Execute the requested operation. * * @exception BuildException if an error occurs */ @Override public void execute() throws BuildException { super.execute(); if (path == null) { throw new BuildException ("Must specify 'path' attribute"); } if ((war == null) && (localWar == null) && (config == null) && (tag == null)) { throw new BuildException ("Must specify either 'war', 'localWar', 'config', or 'tag' attribute"); } // Building an input stream on the WAR to upload, if any BufferedInputStream stream = null; String contentType = null; int contentLength = -1; if (war != null) { if (war.startsWith("file:")) { try { URL url = new URL(war); URLConnection conn = url.openConnection(); contentLength = conn.getContentLength(); stream = new BufferedInputStream (conn.getInputStream(), 1024); } catch (IOException e) { throw new BuildException(e); } } else { try { FileInputStream fsInput = new FileInputStream(war); long size = fsInput.getChannel().size(); if (size > Integer.MAX_VALUE) throw new UnsupportedOperationException( "DeployTask does not support WAR files " + "greater than 2 Gb"); contentLength = (int) size; stream = new BufferedInputStream(fsInput, 1024); } catch (IOException e) { throw new BuildException(e); } } contentType = "application/octet-stream"; } // Building URL StringBuilder sb = new StringBuilder("/deploy?path="); try { sb.append(URLEncoder.encode(this.path, getCharset())); if ((war == null) && (config != null)) { sb.append("&config="); sb.append(URLEncoder.encode(config, getCharset())); } if ((war == null) && (localWar != null)) { sb.append("&war="); sb.append(URLEncoder.encode(localWar, getCharset())); } if (update) { sb.append("&update=true"); } if (tag != null) { sb.append("&tag="); sb.append(URLEncoder.encode(tag, getCharset())); } } catch (UnsupportedEncodingException e) { throw new BuildException("Invalid 'charset' attribute: " + getCharset()); } execute(sb.toString(), stream, contentType, contentLength); } }
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
java/org/apache/catalina/filters/CorsFilter.java
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
test/org/apache/catalina/filters/TestCorsFilter.java
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
test/org/apache/catalina/filters/TesterFilterChain.java
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
test/org/apache/catalina/filters/TesterFilterConfigs.java
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
test/org/apache/catalina/filters/TesterHttpServletRequest.java
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
test/org/apache/catalina/filters/TesterHttpServletResponse.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.filters; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.Collection; import java.util.Locale; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.catalina.connector.Request; /** * Mock HttpServletResponse */ public class TesterHttpServletResponse implements HttpServletResponse { public TesterHttpServletResponse() { // NOOP } public void setAppCommitted( @SuppressWarnings("unused") boolean appCommitted) {/* NOOP */} public boolean isAppCommitted() { return false; } public Connector getConnector() { return null; } public void setConnector(@SuppressWarnings("unused") Connector connector) { // NOOP } public int getContentCount() { return -1; } public Context getContext() { return null; } public void setContext(@SuppressWarnings("unused") Context context) { // NOOP } public boolean getIncluded() { return false; } public void setIncluded(@SuppressWarnings("unused") boolean included) { // NOOP } public Request getRequest() { return null; } public void setRequest(@SuppressWarnings("unused") Request request) { // NOOP } public ServletResponse getResponse() { return null; } public OutputStream getStream() { return null; } public void setStream(@SuppressWarnings("unused") OutputStream stream) { // NOOP } public void setSuspended(@SuppressWarnings("unused") boolean suspended) { // NOOP } public boolean isSuspended() { return false; } public void setError() {/* NOOP */} public boolean isError() { return false; } /** * @throws IOException */ public ServletOutputStream createOutputStream() throws IOException { return null; } /** * @throws IOException */ public void finishResponse() throws IOException {/* NOOP */} public int getContentLength() { return -1; } @Override public String getContentType() { return null; } public PrintWriter getReporter() { return null; } public void recycle() {/* NOOP */} /** * @param b * @throws IOException */ public void write(int b) throws IOException { // NOOP } /** * @param b * @throws IOException */ public void write(byte b[]) throws IOException { // NOOP } /** * @param b * @param off * @param len * @throws IOException */ public void write(byte b[], int off, int len) throws IOException { // NOOP } @Override public void flushBuffer() throws IOException {/* NOOP */} @Override public int getBufferSize() { return -1; } @Override public String getCharacterEncoding() { return null; } @Override public void setCharacterEncoding(String charEncoding) {/* NOOP */} @Override public ServletOutputStream getOutputStream() throws IOException { return null; } @Override public Locale getLocale() { return null; } @Override public PrintWriter getWriter() throws IOException { return null; } @Override public boolean isCommitted() { return false; } @Override public void reset() {/* NOOP */} @Override public void resetBuffer() {/* NOOP */} @Override public void setBufferSize(int size) {/* NOOP */} @Override public void setContentLength(int length) {/* NOOP */} @Override public void setContentType(String type) {/* NOOP */} @Override public void setLocale(Locale locale) {/* NOOP */} @Override public String getHeader(String name) { return null; } @Override public Collection<String> getHeaderNames() { return null; } @Override public Collection<String> getHeaders(String name) { return null; } public String getMessage() { return null; } @Override public int getStatus() { return -1; } public void reset(@SuppressWarnings("unused") int status, @SuppressWarnings("unused") String message) {/* NOOP */} @Override public void addCookie(Cookie cookie) {/* NOOP */} @Override public void addDateHeader(String name, long value) {/* NOOP */} @Override public void addHeader(String name, String value) {/* NOOP */} @Override public void addIntHeader(String name, int value) {/* NOOP */} @Override public boolean containsHeader(String name) { return false; } @Override public String encodeRedirectURL(String url) { return null; } /** @deprecated */ @Override @Deprecated public String encodeRedirectUrl(String url) { return null; } @Override public String encodeURL(String url) { return null; } /** @deprecated */ @Override @Deprecated public String encodeUrl(String url) { return null; } /** * * @throws IOException */ public void sendAcknowledgement() throws IOException {/* NOOP */} @Override public void sendError(int status) throws IOException {/* NOOP */} @Override public void sendError(int status, String message) throws IOException { // NOOP } @Override public void sendRedirect(String location) throws IOException {/* NOOP */} @Override public void setDateHeader(String name, long value) {/* NOOP */} @Override public void setHeader(String name, String value) {/* NOOP */} @Override public void setIntHeader(String name, int value) {/* NOOP */} @Override public void setStatus(int status) {/* NOOP */} /** @deprecated */ @Override @Deprecated public void setStatus(int status, String message) {/* NOOP */} @Override public void setContentLengthLong(long length) {/* NOOP */} }
55,046
Bug 55046 CORS Filter
null
resolved fixed
72edec7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T10:51:31Z
2013-06-02T05:13:20Z
test/org/apache/catalina/filters/TesterServletContext.java
55,052
Bug 55052 [JULI] Make ClassLoaderLogManager.getProperty() to try unprefixed property if prefixed one does not exist
null
resolved fixed
99562d3
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-04T12:19:29Z
2013-06-03T17:20:00Z
java/org/apache/juli/ClassLoaderLogManager.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.juli; import java.io.File; import java.io.FileInputStream; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.net.URLClassLoader; import java.security.AccessControlException; import java.security.AccessController; import java.security.Permission; import java.security.PrivilegedAction; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.StringTokenizer; import java.util.WeakHashMap; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogManager; import java.util.logging.Logger; /** * Per classloader LogManager implementation. */ public class ClassLoaderLogManager extends LogManager { private final class Cleaner extends Thread { @Override public void run() { if (useShutdownHook) { shutdown(); } } } // ------------------------------------------------------------Constructors public ClassLoaderLogManager() { super(); try { Runtime.getRuntime().addShutdownHook(new Cleaner()); } catch (IllegalStateException ise) { // We are probably already being shutdown. Ignore this error. } } // -------------------------------------------------------------- Variables /** * Map containing the classloader information, keyed per classloader. A * weak hashmap is used to ensure no classloader reference is leaked from * application redeployment. */ protected final Map<ClassLoader, ClassLoaderLogInfo> classLoaderLoggers = new WeakHashMap<>(); /** * This prefix is used to allow using prefixes for the properties names * of handlers and their subcomponents. */ protected final ThreadLocal<String> prefix = new ThreadLocal<>(); /** * Determines if the shutdown hook is used to perform any necessary * clean-up such as flushing buffered handlers on JVM shutdown. Defaults to * <code>true</code> but may be set to false if another component ensures * that {@link #shutdown()} is called. */ protected volatile boolean useShutdownHook = true; // ------------------------------------------------------------- Properties public boolean isUseShutdownHook() { return useShutdownHook; } public void setUseShutdownHook(boolean useShutdownHook) { this.useShutdownHook = useShutdownHook; } // --------------------------------------------------------- Public Methods /** * Add the specified logger to the classloader local configuration. * * @param logger The logger to be added */ @Override public synchronized boolean addLogger(final Logger logger) { final String loggerName = logger.getName(); ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); ClassLoaderLogInfo info = getClassLoaderInfo(classLoader); if (info.loggers.containsKey(loggerName)) { return false; } info.loggers.put(loggerName, logger); // Apply initial level for new logger final String levelString = getProperty(loggerName + ".level"); if (levelString != null) { try { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { logger.setLevel(Level.parse(levelString.trim())); return null; } }); } catch (IllegalArgumentException e) { // Leave level set to null } } // Always instantiate parent loggers so that // we can control log categories even during runtime int dotIndex = loggerName.lastIndexOf('.'); if (dotIndex >= 0) { final String parentName = loggerName.substring(0, dotIndex); Logger.getLogger(parentName); } // Find associated node LogNode node = info.rootNode.findNode(loggerName); node.logger = logger; // Set parent logger Logger parentLogger = node.findParentLogger(); if (parentLogger != null) { doSetParentLogger(logger, parentLogger); } // Tell children we are their new parent node.setParentLogger(logger); // Add associated handlers, if any are defined using the .handlers property. // In this case, handlers of the parent logger(s) will not be used String handlers = getProperty(loggerName + ".handlers"); if (handlers != null) { logger.setUseParentHandlers(false); StringTokenizer tok = new StringTokenizer(handlers, ","); while (tok.hasMoreTokens()) { String handlerName = (tok.nextToken().trim()); Handler handler = null; ClassLoader current = classLoader; while (current != null) { info = classLoaderLoggers.get(current); if (info != null) { handler = info.handlers.get(handlerName); if (handler != null) { break; } } current = current.getParent(); } if (handler != null) { logger.addHandler(handler); } } } // Parse useParentHandlers to set if the logger should delegate to its parent. // Unlike java.util.logging, the default is to not delegate if a list of handlers // has been specified for the logger. String useParentHandlersString = getProperty(loggerName + ".useParentHandlers"); if (Boolean.valueOf(useParentHandlersString).booleanValue()) { logger.setUseParentHandlers(true); } return true; } /** * Get the logger associated with the specified name inside * the classloader local configuration. If this returns null, * and the call originated for Logger.getLogger, a new * logger with the specified name will be instantiated and * added using addLogger. * * @param name The name of the logger to retrieve */ @Override public synchronized Logger getLogger(final String name) { ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); return getClassLoaderInfo(classLoader).loggers.get(name); } /** * Get an enumeration of the logger names currently defined in the * classloader local configuration. */ @Override public synchronized Enumeration<String> getLoggerNames() { ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); return Collections.enumeration(getClassLoaderInfo(classLoader).loggers.keySet()); } /** * Get the value of the specified property in the classloader local * configuration. * * @param name The property name */ @Override public String getProperty(String name) { ClassLoader classLoader = Thread.currentThread() .getContextClassLoader(); String prefix = this.prefix.get(); if (prefix != null) { name = prefix + name; } ClassLoaderLogInfo info = getClassLoaderInfo(classLoader); String result = info.props.getProperty(name); // If the property was not found, and the current classloader had no // configuration (property list is empty), look for the parent classloader // properties. if ((result == null) && (info.props.isEmpty())) { ClassLoader current = classLoader.getParent(); while (current != null) { info = classLoaderLoggers.get(current); if (info != null) { result = info.props.getProperty(name); if ((result != null) || (!info.props.isEmpty())) { break; } } current = current.getParent(); } if (result == null) { result = super.getProperty(name); } } // Simple property replacement (mostly for folder names) if (result != null) { result = replace(result); } return result; } @Override public void readConfiguration() throws IOException, SecurityException { checkAccess(); readConfiguration(Thread.currentThread().getContextClassLoader()); } @Override public void readConfiguration(InputStream is) throws IOException, SecurityException { checkAccess(); reset(); readConfiguration(is, Thread.currentThread().getContextClassLoader()); } @Override public void reset() throws SecurityException { Thread thread = Thread.currentThread(); if (thread.getClass().getName().startsWith( "java.util.logging.LogManager$")) { // Ignore the call from java.util.logging.LogManager.Cleaner, // because we have our own shutdown hook return; } ClassLoader classLoader = thread.getContextClassLoader(); ClassLoaderLogInfo clLogInfo = getClassLoaderInfo(classLoader); resetLoggers(clLogInfo); super.reset(); } /** * Shuts down the logging system. */ public void shutdown() { // The JVM is being shutdown. Make sure all loggers for all class // loaders are shutdown for (ClassLoaderLogInfo clLogInfo : classLoaderLoggers.values()) { resetLoggers(clLogInfo); } } // -------------------------------------------------------- Private Methods private void resetLoggers(ClassLoaderLogInfo clLogInfo) { // This differs from LogManager#resetLogger() in that we close not all // handlers of all loggers, but only those that are present in our // ClassLoaderLogInfo#handlers list. That is because our #addLogger(..) // method can use handlers from the parent class loaders, and closing // handlers that the current class loader does not own would be not // good. synchronized (clLogInfo) { for (Logger logger : clLogInfo.loggers.values()) { Handler[] handlers = logger.getHandlers(); for (Handler handler : handlers) { logger.removeHandler(handler); } } for (Handler handler : clLogInfo.handlers.values()) { try { handler.close(); } catch (Exception e) { // Ignore } } clLogInfo.handlers.clear(); } } // ------------------------------------------------------ Protected Methods /** * Retrieve the configuration associated with the specified classloader. If * it does not exist, it will be created. * * @param classLoader The classloader for which we will retrieve or build the * configuration */ protected ClassLoaderLogInfo getClassLoaderInfo(ClassLoader classLoader) { if (classLoader == null) { classLoader = ClassLoader.getSystemClassLoader(); } ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader); if (info == null) { final ClassLoader classLoaderParam = classLoader; AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { try { readConfiguration(classLoaderParam); } catch (IOException e) { // Ignore } return null; } }); info = classLoaderLoggers.get(classLoader); } return info; } /** * Read configuration for the specified classloader. * * @param classLoader * @throws IOException Error */ protected void readConfiguration(ClassLoader classLoader) throws IOException { InputStream is = null; // Special case for URL classloaders which are used in containers: // only look in the local repositories to avoid redefining loggers 20 times try { if ((classLoader instanceof URLClassLoader) && (((URLClassLoader) classLoader).findResource("logging.properties") != null)) { is = classLoader.getResourceAsStream("logging.properties"); } } catch (AccessControlException ace) { // No permission to configure logging in context // Log and carry on ClassLoaderLogInfo info = classLoaderLoggers.get(ClassLoader.getSystemClassLoader()); if (info != null) { Logger log = info.loggers.get(""); if (log != null) { Permission perm = ace.getPermission(); if (perm instanceof FilePermission && perm.getActions().equals("read")) { log.warning("Reading " + perm.getName() + " is not permitted. See \"per context logging\" in the default catalina.policy file."); } else { log.warning("Reading logging.properties is not permitted in some context. See \"per context logging\" in the default catalina.policy file."); log.warning("Original error was: " + ace.getMessage()); } } } } if ((is == null) && (classLoader == ClassLoader.getSystemClassLoader())) { String configFileStr = System.getProperty("java.util.logging.config.file"); if (configFileStr != null) { try { is = new FileInputStream(replace(configFileStr)); } catch (IOException e) { // Ignore } } // Try the default JVM configuration if (is == null) { File defaultFile = new File(new File(System.getProperty("java.home"), "lib"), "logging.properties"); try { is = new FileInputStream(defaultFile); } catch (IOException e) { // Critical problem, do something ... } } } Logger localRootLogger = new RootLogger(); if (is == null) { // Retrieve the root logger of the parent classloader instead ClassLoader current = classLoader.getParent(); ClassLoaderLogInfo info = null; while (current != null && info == null) { info = getClassLoaderInfo(current); current = current.getParent(); } if (info != null) { localRootLogger.setParent(info.rootNode.logger); } } ClassLoaderLogInfo info = new ClassLoaderLogInfo(new LogNode(null, localRootLogger)); classLoaderLoggers.put(classLoader, info); if (is != null) { readConfiguration(is, classLoader); } addLogger(localRootLogger); } /** * Load specified configuration. * * @param is InputStream to the properties file * @param classLoader for which the configuration will be loaded * @throws IOException If something wrong happens during loading */ protected void readConfiguration(InputStream is, ClassLoader classLoader) throws IOException { ClassLoaderLogInfo info = classLoaderLoggers.get(classLoader); try { info.props.load(is); } catch (IOException e) { // Report error System.err.println("Configuration error"); e.printStackTrace(); } finally { try { is.close(); } catch (IOException ioe) { // Ignore } } // Create handlers for the root logger of this classloader String rootHandlers = info.props.getProperty(".handlers"); String handlers = info.props.getProperty("handlers"); Logger localRootLogger = info.rootNode.logger; if (handlers != null) { StringTokenizer tok = new StringTokenizer(handlers, ","); while (tok.hasMoreTokens()) { String handlerName = (tok.nextToken().trim()); String handlerClassName = handlerName; String prefix = ""; if (handlerClassName.length() <= 0) { continue; } // Parse and remove a prefix (prefix start with a digit, such as // "10WebappFooHanlder.") if (Character.isDigit(handlerClassName.charAt(0))) { int pos = handlerClassName.indexOf('.'); if (pos >= 0) { prefix = handlerClassName.substring(0, pos + 1); handlerClassName = handlerClassName.substring(pos + 1); } } try { this.prefix.set(prefix); Handler handler = (Handler) classLoader.loadClass(handlerClassName).newInstance(); // The specification strongly implies all configuration should be done // during the creation of the handler object. // This includes setting level, filter, formatter and encoding. this.prefix.set(null); info.handlers.put(handlerName, handler); if (rootHandlers == null) { localRootLogger.addHandler(handler); } } catch (Exception e) { // Report error System.err.println("Handler error"); e.printStackTrace(); } } } } /** * Set parent child relationship between the two specified loggers. * * @param logger * @param parent */ protected static void doSetParentLogger(final Logger logger, final Logger parent) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { logger.setParent(parent); return null; } }); } /** * System property replacement in the given string. * * @param str The original string * @return the modified string */ protected String replace(String str) { String result = str; int pos_start = str.indexOf("${"); if (pos_start >= 0) { StringBuilder builder = new StringBuilder(); int pos_end = -1; while (pos_start >= 0) { builder.append(str, pos_end + 1, pos_start); pos_end = str.indexOf('}', pos_start + 2); if (pos_end < 0) { pos_end = pos_start - 1; break; } String propName = str.substring(pos_start + 2, pos_end); String replacement = propName.length() > 0 ? System .getProperty(propName) : null; if (replacement != null) { builder.append(replacement); } else { builder.append(str, pos_start, pos_end + 1); } pos_start = str.indexOf("${", pos_end + 1); } builder.append(str, pos_end + 1, str.length()); result = builder.toString(); } return result; } // ---------------------------------------------------- LogNode Inner Class protected static final class LogNode { Logger logger; protected final Map<String, LogNode> children = new HashMap<>(); protected final LogNode parent; LogNode(final LogNode parent, final Logger logger) { this.parent = parent; this.logger = logger; } LogNode(final LogNode parent) { this(parent, null); } LogNode findNode(String name) { LogNode currentNode = this; if (logger.getName().equals(name)) { return this; } while (name != null) { final int dotIndex = name.indexOf('.'); final String nextName; if (dotIndex < 0) { nextName = name; name = null; } else { nextName = name.substring(0, dotIndex); name = name.substring(dotIndex + 1); } LogNode childNode = currentNode.children.get(nextName); if (childNode == null) { childNode = new LogNode(currentNode); currentNode.children.put(nextName, childNode); } currentNode = childNode; } return currentNode; } Logger findParentLogger() { Logger logger = null; LogNode node = parent; while (node != null && logger == null) { logger = node.logger; node = node.parent; } return logger; } void setParentLogger(final Logger parent) { for (final Iterator<LogNode> iter = children.values().iterator(); iter.hasNext();) { final LogNode childNode = iter.next(); if (childNode.logger == null) { childNode.setParentLogger(parent); } else { doSetParentLogger(childNode.logger, parent); } } } } // -------------------------------------------- ClassLoaderInfo Inner Class protected static final class ClassLoaderLogInfo { final LogNode rootNode; final Map<String, Logger> loggers = new HashMap<>(); final Map<String, Handler> handlers = new HashMap<>(); final Properties props = new Properties(); ClassLoaderLogInfo(final LogNode rootNode) { this.rootNode = rootNode; } } // ------------------------------------------------- RootLogger Inner Class /** * This class is needed to instantiate the root of each per classloader * hierarchy. */ protected static class RootLogger extends Logger { public RootLogger() { super("", null); } } }
55,110
Bug 55110 Wasted work in "TestNonLoginAndBasicAuthenticator.doTestBasic"
null
resolved fixed
c48a2ed
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-18T07:18:09Z
2013-06-17T23:00:00Z
test/org/apache/catalina/authenticator/TestNonLoginAndBasicAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityCollection; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.session.ManagerBase; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.codec.binary.Base64; /** * Test BasicAuthenticator and NonLoginAuthenticator when a * SingleSignOn Valve is not active. * * <p> * In the absence of SSO support, these two authenticator classes * both have quite simple behaviour. By testing them together, we * can make sure they operate independently and confirm that no * SSO logic has been accidentally triggered. */ public class TestNonLoginAndBasicAuthenticator extends TomcatBaseTest { protected static final boolean USE_COOKIES = true; protected static final boolean NO_COOKIES = !USE_COOKIES; private static final String USER = "user"; private static final String PWD = "pwd"; private static final String ROLE = "role"; private static final String NICE_METHOD = "Basic"; private static final String HTTP_PREFIX = "http://localhost:"; private static final String CONTEXT_PATH_NOLOGIN = "/nologin"; private static final String CONTEXT_PATH_LOGIN = "/login"; private static final String URI_PROTECTED = "/protected"; private static final String URI_PUBLIC = "/anyoneCanAccess"; private static final int SHORT_SESSION_TIMEOUT_MINS = 1; private static final int LONG_SESSION_TIMEOUT_MINS = 2; private static final int MANAGER_SCAN_INTERVAL_SECS = 10; private static final int MANAGER_EXPIRE_SESSIONS_FAST = 1; private static final int EXTRA_DELAY_SECS = 5; private static final long TIMEOUT_DELAY_MSECS = (((SHORT_SESSION_TIMEOUT_MINS * 60) + (MANAGER_SCAN_INTERVAL_SECS * MANAGER_EXPIRE_SESSIONS_FAST) + EXTRA_DELAY_SECS) * 1000); private static final String CLIENT_AUTH_HEADER = "authorization"; private static final String SERVER_AUTH_HEADER = "WWW-Authenticate"; private static final String SERVER_COOKIE_HEADER = "Set-Cookie"; private static final String CLIENT_COOKIE_HEADER = "Cookie"; private static final BasicCredentials NO_CREDENTIALS = null; private static final BasicCredentials GOOD_CREDENTIALS = new BasicCredentials(NICE_METHOD, USER, PWD); private static final BasicCredentials STRANGE_CREDENTIALS = new BasicCredentials("bAsIc", USER, PWD); private static final BasicCredentials BAD_CREDENTIALS = new BasicCredentials(NICE_METHOD, USER, "wrong"); private static final BasicCredentials BAD_METHOD = new BasicCredentials("BadMethod", USER, PWD); private static final BasicCredentials SPACED_BASE64 = new BasicCredentials(NICE_METHOD + " ", USER, PWD); private static final BasicCredentials SPACED_USERNAME = new BasicCredentials(NICE_METHOD, " " + USER + " ", PWD); private static final BasicCredentials SPACED_PASSWORD = new BasicCredentials(NICE_METHOD, USER, " " + PWD + " "); private Tomcat tomcat; private Context basicContext; private Context nonloginContext; private List<String> cookies; /* * Try to access an unprotected resource in a webapp that * does not have a login method defined. * This should be permitted. */ @Test public void testAcceptPublicNonLogin() throws Exception { doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PUBLIC, NO_COOKIES, HttpServletResponse.SC_OK); } /* * Try to access a protected resource in a webapp that * does not have a login method defined. * This should be rejected with SC_FORBIDDEN 403 status. */ @Test public void testRejectProtectedNonLogin() throws Exception { doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, NO_COOKIES, HttpServletResponse.SC_FORBIDDEN); } /* * Try to access an unprotected resource in a webapp that * has a BASIC login method defined. * This should be permitted without a challenge. */ @Test public void testAcceptPublicBasic() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PUBLIC, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * Try to access a protected resource in a webapp that * has a BASIC login method defined. The access will be * challenged with 401 SC_UNAUTHORIZED, and then be permitted * once authenticated. */ @Test public void testAcceptProtectedBasic() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * This is the same as testAcceptProtectedBasic (above), except * using an invalid password. */ @Test public void testAuthMethodBadCredentials() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, BAD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * This is the same as testAcceptProtectedBasic (above), except * to verify the server follows RFC2617 by treating the auth-scheme * token as case-insensitive. */ @Test public void testAuthMethodCaseBasic() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, STRANGE_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * This is the same as testAcceptProtectedBasic (above), except * using an invalid authentication method. * * Note: the container ensures the Basic login method is called. * BasicAuthenticator does not find the expected authentication * header method, and so does not extract any credentials. * * The request is rejected with 401 SC_UNAUTHORIZED status. RFC2616 * says the response body should identify the auth-schemes that are * acceptable for the container. */ @Test public void testAuthMethodBadMethod() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, BAD_METHOD, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * This is the same as testAcceptProtectedBasic (above), except * using excess white space after the authentication method. * * The access will be challenged with 401 SC_UNAUTHORIZED, and then be * permitted once authenticated. * * RFC2617 does not define the separation syntax between the auth-scheme and * basic-credentials tokens. Tomcat tolerates any amount of white space * (within the limits of HTTP header sizes) and returns SC_OK. */ @Test public void testAuthMethodExtraSpace() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, SPACED_BASE64, NO_COOKIES, HttpServletResponse.SC_OK); } /* * This is the same as testAcceptProtectedBasic (above), except * using white space around the username credential. * * The request is rejected with 401 SC_UNAUTHORIZED status. * * TODO: RFC2617 does not define the separation syntax between the * auth-scheme and basic-credentials tokens. Tomcat should tolerate * any reasonable amount of white space and return SC_OK. */ @Test public void testUserExtraSpace() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, SPACED_USERNAME, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * This is the same as testAcceptProtectedBasic (above), except * using white space around the password credential. * * The request is rejected with 401 SC_UNAUTHORIZED status. * * TODO: RFC2617 does not define the separation syntax between the * auth-scheme and basic-credentials tokens. Tomcat should tolerate * any reasonable amount of white space and return SC_OK. */ @Test public void testPasswordExtraSpace() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, SPACED_PASSWORD, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * The default behaviour of BASIC authentication does NOT create * a session on the server. Verify that the client is required to * send a valid authenticate header with every request to access * protected resources. */ @Test public void testBasicLoginWithoutSession() throws Exception { // this section is identical to testAuthMethodCaseBasic doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // next, try to access the protected resource while not providing // credentials. This confirms the server has not retained any state // data which might allow it to authenticate the client. Expect // to be challenged with 401 SC_UNAUTHORIZED. doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); // finally, provide credentials to confirm the resource // can still be accessed with an authentication header. doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * Test the optional behaviour of BASIC authentication to create * a session on the server. The server will return a session cookie. * * 1. try to access a protected resource without credentials, so * get Unauthorized status. * 2. try to access a protected resource when providing credentials, * so get OK status and a server session cookie. * 3. access the protected resource once more using a session cookie. * 4. repeat using the session cookie. * * Note: The FormAuthenticator is a two-step process and is protected * from session fixation attacks by the default AuthenticatorBase * changeSessionIdOnAuthentication setting of true. However, * BasicAuthenticator is a one-step process and so the * AuthenticatorBase does not reissue the sessionId. */ @Test public void testBasicLoginSessionPersistence() throws Exception { setAlwaysUseSession(); // this section is identical to testAuthMethodCaseBasic doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // confirm the session is not recognised by the server alone doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); // now provide the harvested session cookie for authentication doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_OK); // finally, do it again with the cookie to be sure doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_OK); } /* * Verify the timeout mechanism works for BASIC sessions. This test * follows the flow of testBasicLoginSessionPersistence (above). */ @Test public void testBasicLoginSessionTimeout() throws Exception { setAlwaysUseSession(); setRapidSessionTimeout(); // this section is identical to testAuthMethodCaseBasic doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // now provide the harvested session cookie for authentication List<String> originalCookies = cookies; doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_OK); // allow the session to time out and lose authentication Thread.sleep(TIMEOUT_DELAY_MSECS); // provide the harvested session cookie for authentication // to confirm it has expired doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); // finally, do BASIC reauthentication and get another session doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // slightly paranoid verification boolean sameCookies = originalCookies.equals(cookies); assertTrue(!sameCookies); } /* * Logon to access a protected resource in a webapp that uses * BASIC authentication. Then try to access a protected resource * in a different webapp which does not have a login method. * This should be rejected with SC_FORBIDDEN 403 status, confirming * there has been no cross-authentication between the webapps. */ @Test public void testBasicLoginRejectProtected() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, NO_COOKIES, HttpServletResponse.SC_FORBIDDEN); } /* * Try to use the session cookie from the BASIC webapp to request * access to the webapp that does not have a login method. (This * is equivalent to Single Signon, but without the Valve.) * * Verify there is no cross-authentication when using similar logic * to testBasicLoginRejectProtected (above). * * This should be rejected with SC_FORBIDDEN 403 status. */ @Test public void testBasicLoginRejectProtectedWithSession() throws Exception { setAlwaysUseSession(); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // use the session cookie harvested with the other webapp doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, USE_COOKIES, HttpServletResponse.SC_FORBIDDEN); } private void doTestNonLogin(String uri, boolean useCookie, int expectedRC) throws Exception { Map<String,List<String>> reqHeaders = new HashMap<>(); Map<String,List<String>> respHeaders = new HashMap<>(); if (useCookie && (cookies != null)) { reqHeaders.put(CLIENT_COOKIE_HEADER + ":", cookies); } ByteChunk bc = new ByteChunk(); int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders, respHeaders); if (expectedRC != HttpServletResponse.SC_OK) { assertEquals(expectedRC, rc); assertTrue(bc.getLength() > 0); } else { assertEquals("OK", bc.toString()); } } private void doTestBasic(String uri, BasicCredentials credentials, boolean useCookie, int expectedRC) throws Exception { Map<String,List<String>> reqHeaders = new HashMap<>(); Map<String,List<String>> respHeaders = new HashMap<>(); if (useCookie && (cookies != null)) { reqHeaders.put(CLIENT_COOKIE_HEADER + ":", cookies); } else { if (credentials != null) { List<String> auth = new ArrayList<>(); auth.add(credentials.getCredentials()); reqHeaders.put(CLIENT_AUTH_HEADER, auth); } } ByteChunk bc = new ByteChunk(); int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders, respHeaders); if (expectedRC != HttpServletResponse.SC_OK) { assertEquals(expectedRC, rc); assertTrue(bc.getLength() > 0); if (expectedRC == HttpServletResponse.SC_UNAUTHORIZED) { // The server should identify the acceptable method(s) boolean methodFound = false; List<String> authHeaders = respHeaders.get(SERVER_AUTH_HEADER); for (String authHeader : authHeaders) { if (authHeader.indexOf(NICE_METHOD) > -1) { methodFound = true; } } assertTrue(methodFound); } } else { assertEquals("OK", bc.toString()); List<String> newCookies = respHeaders.get(SERVER_COOKIE_HEADER); if (newCookies != null) { // harvest cookies whenever the server sends some new ones cookies = newCookies; } } } /* * setup two webapps for every test * * note: the super class tearDown method will stop tomcat */ @Override public void setUp() throws Exception { super.setUp(); // create a tomcat server using the default in-memory Realm tomcat = getTomcatInstance(); // add the test user and role to the Realm tomcat.addUser(USER, PWD); tomcat.addRole(USER, ROLE); // setup both NonLogin and Login webapps setUpNonLogin(); setUpLogin(); tomcat.start(); } private void setUpNonLogin() throws Exception { // Must have a real docBase for webapps - just use temp nonloginContext = tomcat.addContext(CONTEXT_PATH_NOLOGIN, System.getProperty("java.io.tmpdir")); nonloginContext.setSessionTimeout(LONG_SESSION_TIMEOUT_MINS); // Add protected servlet to the context Tomcat.addServlet(nonloginContext, "TesterServlet1", new TesterServlet()); nonloginContext.addServletMapping(URI_PROTECTED, "TesterServlet1"); SecurityCollection collection1 = new SecurityCollection(); collection1.addPattern(URI_PROTECTED); SecurityConstraint sc1 = new SecurityConstraint(); sc1.addAuthRole(ROLE); sc1.addCollection(collection1); nonloginContext.addConstraint(sc1); // Add unprotected servlet to the context Tomcat.addServlet(nonloginContext, "TesterServlet2", new TesterServlet()); nonloginContext.addServletMapping(URI_PUBLIC, "TesterServlet2"); SecurityCollection collection2 = new SecurityCollection(); collection2.addPattern(URI_PUBLIC); SecurityConstraint sc2 = new SecurityConstraint(); // do not add a role - which signals access permitted without one sc2.addCollection(collection2); nonloginContext.addConstraint(sc2); // Configure the authenticator and inherit the Realm from Engine LoginConfig lc = new LoginConfig(); lc.setAuthMethod("NONE"); nonloginContext.setLoginConfig(lc); AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator(); nonloginContext.getPipeline().addValve(nonloginAuthenticator); } private void setUpLogin() throws Exception { // Must have a real docBase for webapps - just use temp basicContext = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir")); basicContext.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS); // Add protected servlet to the context Tomcat.addServlet(basicContext, "TesterServlet3", new TesterServlet()); basicContext.addServletMapping(URI_PROTECTED, "TesterServlet3"); SecurityCollection collection = new SecurityCollection(); collection.addPattern(URI_PROTECTED); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); basicContext.addConstraint(sc); // Add unprotected servlet to the context Tomcat.addServlet(basicContext, "TesterServlet4", new TesterServlet()); basicContext.addServletMapping(URI_PUBLIC, "TesterServlet4"); SecurityCollection collection2 = new SecurityCollection(); collection2.addPattern(URI_PUBLIC); SecurityConstraint sc2 = new SecurityConstraint(); // do not add a role - which signals access permitted without one sc2.addCollection(collection2); basicContext.addConstraint(sc2); // Configure the authenticator and inherit the Realm from Engine LoginConfig lc = new LoginConfig(); lc.setAuthMethod("BASIC"); basicContext.setLoginConfig(lc); AuthenticatorBase basicAuthenticator = new BasicAuthenticator(); basicContext.getPipeline().addValve(basicAuthenticator); } /* * Force non-default behaviour for both Authenticators */ private void setAlwaysUseSession() { ((AuthenticatorBase)basicContext.getAuthenticator()) .setAlwaysUseSession(true); ((AuthenticatorBase)nonloginContext.getAuthenticator()) .setAlwaysUseSession(true); } /* * Force rapid timeout scanning for the Basic Authentication webapp * The StandardManager default service cycle time is 10 seconds, * with a session expiry scan every 6 cycles. */ private void setRapidSessionTimeout() { ((ManagerBase) basicContext.getManager()) .setProcessExpiresFrequency(MANAGER_EXPIRE_SESSIONS_FAST); } /* * Encapsulate the logic to generate an HTTP header * for BASIC Authentication. * Note: only used internally, so no need to validate arguments. */ private static final class BasicCredentials { private final String method; private final String username; private final String password; private final String credentials; private BasicCredentials(String aMethod, String aUsername, String aPassword) { method = aMethod; username = aUsername; password = aPassword; String userCredentials = username + ":" + password; byte[] credentialsBytes = userCredentials.getBytes(B2CConverter.ISO_8859_1); String base64auth = Base64.encodeBase64String(credentialsBytes); credentials= method + " " + base64auth; } private String getCredentials() { return credentials; } } }
55,110
Bug 55110 Wasted work in "TestNonLoginAndBasicAuthenticator.doTestBasic"
null
resolved fixed
c48a2ed
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-18T07:18:09Z
2013-06-17T23:00:00Z
test/org/apache/tomcat/websocket/TestWsWebSocketContainer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.net.SocketTimeoutException; import java.net.URI; import java.nio.ByteBuffer; import java.util.List; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import javax.servlet.ServletContextEvent; import javax.websocket.ClientEndpointConfig; import javax.websocket.ContainerProvider; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.websocket.server.ServerContainer; import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.deploy.ApplicationListener; import org.apache.catalina.servlets.DefaultServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.coyote.http11.Http11Protocol; import org.apache.tomcat.util.net.TesterSupport; import org.apache.tomcat.websocket.TesterSingleMessageClient.BasicBinary; import org.apache.tomcat.websocket.TesterSingleMessageClient.BasicHandler; import org.apache.tomcat.websocket.TesterSingleMessageClient.BasicText; import org.apache.tomcat.websocket.TesterSingleMessageClient.TesterEndpoint; import org.apache.tomcat.websocket.TesterSingleMessageClient.TesterProgrammaticEndpoint; import org.apache.tomcat.websocket.server.Constants; import org.apache.tomcat.websocket.server.WsListener; public class TestWsWebSocketContainer extends TomcatBaseTest { private static final String MESSAGE_STRING_1 = "qwerty"; private static final String MESSAGE_TEXT_4K; private static final byte[] MESSAGE_BINARY_4K = new byte[4096]; private static final long TIMEOUT_MS = 5 * 1000; private static final long MARGIN = 500; static { StringBuilder sb = new StringBuilder(4096); for (int i = 0; i < 4096; i++) { sb.append('*'); } MESSAGE_TEXT_4K = sb.toString(); } @Test public void testConnectToServerEndpoint() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText(MESSAGE_STRING_1); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); List<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); Assert.assertEquals(MESSAGE_STRING_1, messages.get(0)); } @Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointInvalidScheme() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ftp://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); } @Test(expected=javax.websocket.DeploymentException.class) public void testConnectToServerEndpointNoHost() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://" + TesterEchoServer.Config.PATH_ASYNC)); } @Test public void testSmallTextBufferClientTextMessage() throws Exception { doBufferTest(true, false, true, false); } @Test public void testSmallTextBufferClientBinaryMessage() throws Exception { doBufferTest(true, false, false, true); } @Test public void testSmallTextBufferServerTextMessage() throws Exception { doBufferTest(true, true, true, false); } @Test public void testSmallTextBufferServerBinaryMessage() throws Exception { doBufferTest(true, true, false, true); } @Test public void testSmallBinaryBufferClientTextMessage() throws Exception { doBufferTest(false, false, true, true); } @Test public void testSmallBinaryBufferClientBinaryMessage() throws Exception { doBufferTest(false, false, false, false); } @Test public void testSmallBinaryBufferServerTextMessage() throws Exception { doBufferTest(false, true, true, true); } @Test public void testSmallBinaryBufferServerBinaryMessage() throws Exception { doBufferTest(false, true, false, false); } private void doBufferTest(boolean isTextBuffer, boolean isServerBuffer, boolean isTextMessage, boolean pass) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); if (isServerBuffer) { if (isTextBuffer) { ctx.addParameter( org.apache.tomcat.websocket.server.Constants. TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM, "1024"); } else { ctx.addParameter( org.apache.tomcat.websocket.server.Constants. BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM, "1024"); } } else { if (isTextBuffer) { wsContainer.setDefaultMaxTextMessageBufferSize(1024); } else { wsContainer.setDefaultMaxBinaryMessageBufferSize(1024); } } tomcat.start(); Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_BASIC)); BasicHandler<?> handler; CountDownLatch latch = new CountDownLatch(1); TesterEndpoint tep = (TesterEndpoint) wsSession.getUserProperties().get("endpoint"); tep.setLatch(latch); if (isTextMessage) { handler = new BasicText(latch); } else { handler = new BasicBinary(latch); } wsSession.addMessageHandler(handler); if (isTextMessage) { wsSession.getBasicRemote().sendText(MESSAGE_TEXT_4K); } else { wsSession.getBasicRemote().sendBinary( ByteBuffer.wrap(MESSAGE_BINARY_4K)); } boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); List<?> messages = handler.getMessages(); if (pass) { Assert.assertEquals(1, messages.size()); if (isTextMessage) { Assert.assertEquals(MESSAGE_TEXT_4K, messages.get(0)); } else { Assert.assertEquals(ByteBuffer.wrap(MESSAGE_BINARY_4K), messages.get(0)); } } else { // When the message exceeds the buffer size, the WebSocket is // closed. The endpoint ensures that the latch is cleared when the // WebSocket closes. However, the session isn't marked as closed // until after the onClose() method completes so there is a small // window where this test could fail. Therefore, wait briefly to // give the session a chance to complete the close process. for (int i = 0; i < 500; i++) { if (!wsSession.isOpen()) { break; } Thread.sleep(10); } Assert.assertFalse(wsSession.isOpen()); } } @Test public void testWriteTimeoutClientContainer() throws Exception { doTestWriteTimeoutClient(true); } @Test public void testWriteTimeoutClientEndpoint() throws Exception { doTestWriteTimeoutClient(false); } private void doTestWriteTimeoutClient(boolean setTimeoutOnContainer) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( BlockingConfig.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); // Set the async timeout if (setTimeoutOnContainer) { wsContainer.setAsyncSendTimeout(TIMEOUT_MS); } tomcat.start(); Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://localhost:" + getPort() + BlockingConfig.PATH)); if (!setTimeoutOnContainer) { wsSession.getAsyncRemote().setSendTimeout(TIMEOUT_MS); } long lastSend = 0; // Should send quickly until the network buffers fill up and then block // until the timeout kicks in Exception exception = null; try { while (true) { Future<Void> f = wsSession.getAsyncRemote().sendBinary( ByteBuffer.wrap(MESSAGE_BINARY_4K)); lastSend = System.currentTimeMillis(); f.get(); } } catch (Exception e) { exception = e; } long timeout = System.currentTimeMillis() - lastSend; String msg = "Time out was [" + timeout + "] ms"; // Check correct time passed Assert.assertTrue(msg, timeout >= TIMEOUT_MS - MARGIN ); // Check the timeout wasn't too long Assert.assertTrue(msg, timeout < TIMEOUT_MS * 2); Assert.assertNotNull(exception); } @Test public void testWriteTimeoutServerContainer() throws Exception { doTestWriteTimeoutServer(true); } @Test public void testWriteTimeoutServerEndpoint() throws Exception { doTestWriteTimeoutServer(false); } private static volatile boolean timoutOnContainer = false; private void doTestWriteTimeoutServer(boolean setTimeoutOnContainer) throws Exception { /* * Note: There are all sorts of horrible uses of statics in this test * because the API uses classes and the tests really need access * to the instances which simply isn't possible. */ timoutOnContainer = setTimeoutOnContainer; Tomcat tomcat = getTomcatInstance(); if (getProtocol().equals(Http11Protocol.class.getName())) { // This will never work for BIO return; } // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( ConstantTxConfig.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("ws://localhost:" + getPort() + ConstantTxConfig.PATH)); wsSession.addMessageHandler(new BlockingBinaryHandler()); int loops = 0; while (loops < 15) { Thread.sleep(1000); if (!ConstantTxEndpoint.getRunning()) { break; } loops++; } // Check the right exception was thrown Assert.assertNotNull(ConstantTxEndpoint.getException()); Assert.assertEquals(ExecutionException.class, ConstantTxEndpoint.getException().getClass()); Assert.assertNotNull(ConstantTxEndpoint.getException().getCause()); Assert.assertEquals(SocketTimeoutException.class, ConstantTxEndpoint.getException().getCause().getClass()); // Check correct time passed Assert.assertTrue(ConstantTxEndpoint.getTimeout() >= TIMEOUT_MS); // Check the timeout wasn't too long Assert.assertTrue(ConstantTxEndpoint.getTimeout() < TIMEOUT_MS*2); } public static class BlockingConfig extends WsListener { public static final String PATH = "/block"; @Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(BlockingPojo.class); } catch (DeploymentException e) { throw new IllegalStateException(e); } } } @ServerEndpoint("/block") public static class BlockingPojo { @SuppressWarnings("unused") @OnMessage public void echoTextMessage(Session session, String msg, boolean last) { try { Thread.sleep(60000); } catch (InterruptedException e) { // Ignore } } @SuppressWarnings("unused") @OnMessage public void echoBinaryMessage(Session session, ByteBuffer msg, boolean last) { try { Thread.sleep(TIMEOUT_MS * 10); } catch (InterruptedException e) { // Ignore } } } public static class BlockingBinaryHandler implements MessageHandler.Partial<ByteBuffer> { @Override public void onMessage(ByteBuffer messagePart, boolean last) { try { Thread.sleep(TIMEOUT_MS * 10); } catch (InterruptedException e) { // Ignore } } } public static class ConstantTxEndpoint extends Endpoint { // Have to be static to be able to retrieve results from test case private static volatile long timeout = -1; private static volatile Exception exception = null; private static volatile boolean running = true; @Override public void onOpen(Session session, EndpointConfig config) { // Reset everything timeout = -1; exception = null; running = true; if (!TestWsWebSocketContainer.timoutOnContainer) { session.getAsyncRemote().setSendTimeout(TIMEOUT_MS); } long lastSend = 0; // Should send quickly until the network buffers fill up and then // block until the timeout kicks in try { while (true) { lastSend = System.currentTimeMillis(); Future<Void> f = session.getAsyncRemote().sendBinary( ByteBuffer.wrap(MESSAGE_BINARY_4K)); f.get(); } } catch (ExecutionException | InterruptedException e) { exception = e; } timeout = System.currentTimeMillis() - lastSend; running = false; } public static long getTimeout() { return timeout; } public static Exception getException() { return exception; } public static boolean getRunning() { return running; } } public static class ConstantTxConfig extends WsListener { private static final String PATH = "/test"; @Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( Constants.SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(ServerEndpointConfig.Builder.create( ConstantTxEndpoint.class, PATH).build()); if (TestWsWebSocketContainer.timoutOnContainer) { sc.setAsyncSendTimeout(TIMEOUT_MS); } } catch (DeploymentException e) { throw new IllegalStateException(e); } } } @Test public void testGetOpenSessions() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session s1a = connectToEchoServerBasic(wsContainer, EndpointA.class); Session s2a = connectToEchoServerBasic(wsContainer, EndpointA.class); Session s3a = connectToEchoServerBasic(wsContainer, EndpointA.class); Session s1b = connectToEchoServerBasic(wsContainer, EndpointB.class); Session s2b = connectToEchoServerBasic(wsContainer, EndpointB.class); Set<Session> setA = s3a.getOpenSessions(); Assert.assertEquals(3, setA.size()); Assert.assertTrue(setA.remove(s1a)); Assert.assertTrue(setA.remove(s2a)); Assert.assertTrue(setA.remove(s3a)); s1a.close(); setA = s3a.getOpenSessions(); Assert.assertEquals(2, setA.size()); Assert.assertFalse(setA.remove(s1a)); Assert.assertTrue(setA.remove(s2a)); Assert.assertTrue(setA.remove(s3a)); Set<Session> setB = s1b.getOpenSessions(); Assert.assertEquals(2, setB.size()); Assert.assertTrue(setB.remove(s1b)); Assert.assertTrue(setB.remove(s2b)); } @Test public void testSessionExpiryContainer() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); // Need access to implementation methods for configuring unit tests WsWebSocketContainer wsContainer = (WsWebSocketContainer) ContainerProvider.getWebSocketContainer(); // 5 second timeout wsContainer.setDefaultMaxSessionIdleTimeout(5000); wsContainer.setProcessPeriod(1); connectToEchoServerBasic(wsContainer, EndpointA.class); connectToEchoServerBasic(wsContainer, EndpointA.class); Session s3a = connectToEchoServerBasic(wsContainer, EndpointA.class); // Check all three sessions are open Set<Session> setA = s3a.getOpenSessions(); Assert.assertEquals(3, setA.size()); int count = 0; boolean isOpen = true; while (isOpen && count < 8) { count ++; Thread.sleep(1000); isOpen = false; for (Session session : setA) { if (session.isOpen()) { isOpen = true; } } } if (isOpen) { for (Session session : setA) { if (session.isOpen()) { System.err.println("Session with ID [" + session.getId() + "] is open"); } } Assert.fail("There were open sessions"); } } @Test public void testSessionExpirySession() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); tomcat.start(); // Need access to implementation methods for configuring unit tests WsWebSocketContainer wsContainer = (WsWebSocketContainer) ContainerProvider.getWebSocketContainer(); // 5 second timeout wsContainer.setDefaultMaxSessionIdleTimeout(5000); wsContainer.setProcessPeriod(1); Session s1a = connectToEchoServerBasic(wsContainer, EndpointA.class); s1a.setMaxIdleTimeout(3000); Session s2a = connectToEchoServerBasic(wsContainer, EndpointA.class); s2a.setMaxIdleTimeout(6000); Session s3a = connectToEchoServerBasic(wsContainer, EndpointA.class); s3a.setMaxIdleTimeout(9000); // Check all three sessions are open Set<Session> setA = s3a.getOpenSessions(); int expected = 3; while (expected > 0) { Assert.assertEquals(expected, getOpenCount(setA)); int count = 0; while (getOpenCount(setA) == expected && count < 5) { count ++; Thread.sleep(1000); } expected--; } Assert.assertEquals(0, getOpenCount(setA)); } private int getOpenCount(Set<Session> sessions) { int result = 0; for (Session session : sessions) { if (session.isOpen()) { result++; } } return result; } private Session connectToEchoServerBasic(WebSocketContainer wsContainer, Class<? extends Endpoint> clazz) throws Exception { return wsContainer.connectToServer(clazz, ClientEndpointConfig.Builder.create().build(), new URI("ws://localhost:" + getPort() + TesterEchoServer.Config.PATH_BASIC)); } public static final class EndpointA extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) { // NO-OP } } public static final class EndpointB extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) { // NO-OP } } @Test public void testConnectToServerEndpointSSL() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( TesterEchoServer.Config.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); TesterSupport.initSsl(tomcat); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); ClientEndpointConfig clientEndpointConfig = ClientEndpointConfig.Builder.create().build(); clientEndpointConfig.getUserProperties().put( WsWebSocketContainer.SSL_TRUSTSTORE_PROPERTY, "test/org/apache/tomcat/util/net/ca.jks"); Session wsSession = wsContainer.connectToServer( TesterProgrammaticEndpoint.class, clientEndpointConfig, new URI("wss://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC)); CountDownLatch latch = new CountDownLatch(1); BasicText handler = new BasicText(latch); wsSession.addMessageHandler(handler); wsSession.getBasicRemote().sendText(MESSAGE_STRING_1); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); List<String> messages = handler.getMessages(); Assert.assertEquals(1, messages.size()); Assert.assertEquals(MESSAGE_STRING_1, messages.get(0)); } }
55,109
Bug 55109 Wasted work in "WebdavServlet.isLocked"
null
resolved fixed
82bccd2
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-18T07:27:26Z
2013-06-17T23:00:00Z
java/org/apache/catalina/servlets/WebdavServlet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.servlets; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.io.Writer; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Date; import java.util.Enumeration; import java.util.Hashtable; import java.util.Locale; import java.util.Stack; import java.util.TimeZone; import java.util.Vector; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.UnavailableException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.catalina.WebResource; import org.apache.catalina.util.ConcurrentDateFormat; import org.apache.catalina.util.DOMWriter; import org.apache.catalina.util.MD5Encoder; import org.apache.catalina.util.XMLWriter; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.RequestUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; /** * Servlet which adds support for WebDAV level 2. All the basic HTTP requests * are handled by the DefaultServlet. The WebDAVServlet must not be used as the * default servlet (ie mapped to '/') as it will not work in this configuration. * <p/> * Mapping a subpath (e.g. <code>/webdav/*</code> to this servlet has the effect * of re-mounting the entire web application under that sub-path, with WebDAV * access to all the resources. This <code>WEB-INF</code> and <code>META-INF</code> * directories are protected in this re-mounted resource tree. * <p/> * To enable WebDAV for a context add the following to web.xml: * <pre> * &lt;servlet&gt; * &lt;servlet-name&gt;webdav&lt;/servlet-name&gt; * &lt;servlet-class&gt;org.apache.catalina.servlets.WebdavServlet&lt;/servlet-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;debug&lt;/param-name&gt; * &lt;param-value&gt;0&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;listings&lt;/param-name&gt; * &lt;param-value&gt;false&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/servlet&gt; * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;webdav&lt;/servlet-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * This will enable read only access. To enable read-write access add: * <pre> * &lt;init-param&gt; * &lt;param-name&gt;readonly&lt;/param-name&gt; * &lt;param-value&gt;false&lt;/param-value&gt; * &lt;/init-param&gt; * </pre> * To make the content editable via a different URL, use the following * mapping: * <pre> * &lt;servlet-mapping&gt; * &lt;servlet-name&gt;webdav&lt;/servlet-name&gt; * &lt;url-pattern&gt;/webdavedit/*&lt;/url-pattern&gt; * &lt;/servlet-mapping&gt; * </pre> * By default access to /WEB-INF and META-INF are not available via WebDAV. To * enable access to these URLs, use add: * <pre> * &lt;init-param&gt; * &lt;param-name&gt;allowSpecialPaths&lt;/param-name&gt; * &lt;param-value&gt;true&lt;/param-value&gt; * &lt;/init-param&gt; * </pre> * Don't forget to secure access appropriately to the editing URLs, especially * if allowSpecialPaths is used. With the mapping configuration above, the * context will be accessible to normal users as before. Those users with the * necessary access will be able to edit content available via * http://host:port/context/content using * http://host:port/context/webdavedit/content * * @author Remy Maucherat * @version $Id$ */ public class WebdavServlet extends DefaultServlet { private static final long serialVersionUID = 1L; // -------------------------------------------------------------- Constants private static final String METHOD_PROPFIND = "PROPFIND"; private static final String METHOD_PROPPATCH = "PROPPATCH"; private static final String METHOD_MKCOL = "MKCOL"; private static final String METHOD_COPY = "COPY"; private static final String METHOD_MOVE = "MOVE"; private static final String METHOD_LOCK = "LOCK"; private static final String METHOD_UNLOCK = "UNLOCK"; /** * PROPFIND - Specify a property mask. */ private static final int FIND_BY_PROPERTY = 0; /** * PROPFIND - Display all properties. */ private static final int FIND_ALL_PROP = 1; /** * PROPFIND - Return property names. */ private static final int FIND_PROPERTY_NAMES = 2; /** * Create a new lock. */ private static final int LOCK_CREATION = 0; /** * Refresh lock. */ private static final int LOCK_REFRESH = 1; /** * Default lock timeout value. */ private static final int DEFAULT_TIMEOUT = 3600; /** * Maximum lock timeout. */ private static final int MAX_TIMEOUT = 604800; /** * Default namespace. */ protected static final String DEFAULT_NAMESPACE = "DAV:"; /** * Simple date format for the creation date ISO representation (partial). */ protected static final ConcurrentDateFormat creationDateFormat = new ConcurrentDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US, TimeZone.getTimeZone("GMT")); /** * MD5 message digest provider. */ protected static MessageDigest md5Helper; // ----------------------------------------------------- Instance Variables /** * Repository of the locks put on single resources. * <p> * Key : path <br> * Value : LockInfo */ private final Hashtable<String,LockInfo> resourceLocks = new Hashtable<>(); /** * Repository of the lock-null resources. * <p> * Key : path of the collection containing the lock-null resource<br> * Value : Vector of lock-null resource which are members of the * collection. Each element of the Vector is the path associated with * the lock-null resource. */ private final Hashtable<String,Vector<String>> lockNullResources = new Hashtable<>(); /** * Vector of the heritable locks. * <p> * Key : path <br> * Value : LockInfo */ private final Vector<LockInfo> collectionLocks = new Vector<>(); /** * Secret information used to generate reasonably secure lock ids. */ private String secret = "catalina"; /** * Default depth in spec is infinite. Limit depth to 3 by default as * infinite depth makes operations very expensive. */ private int maxDepth = 3; /** * Is access allowed via WebDAV to the special paths (/WEB-INF and * /META-INF)? */ private boolean allowSpecialPaths = false; // --------------------------------------------------------- Public Methods /** * Initialize this servlet. */ @Override public void init() throws ServletException { super.init(); if (getServletConfig().getInitParameter("secret") != null) secret = getServletConfig().getInitParameter("secret"); if (getServletConfig().getInitParameter("maxDepth") != null) maxDepth = Integer.parseInt( getServletConfig().getInitParameter("maxDepth")); if (getServletConfig().getInitParameter("allowSpecialPaths") != null) allowSpecialPaths = Boolean.parseBoolean( getServletConfig().getInitParameter("allowSpecialPaths")); // Load the MD5 helper used to calculate signatures. try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new UnavailableException("No MD5"); } } // ------------------------------------------------------ Protected Methods /** * Return JAXP document builder instance. */ protected DocumentBuilder getDocumentBuilder() throws ServletException { DocumentBuilder documentBuilder = null; DocumentBuilderFactory documentBuilderFactory = null; try { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setExpandEntityReferences(false); documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver( new WebdavResolver(this.getServletContext())); } catch(ParserConfigurationException e) { throw new ServletException (sm.getString("webdavservlet.jaxpfailed")); } return documentBuilder; } /** * Handles the special WebDAV methods. */ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final String path = getRelativePath(req); // Block access to special subdirectories. // DefaultServlet assumes it services resources from the root of the web app // and doesn't add any special path protection // WebdavServlet remounts the webapp under a new path, so this check is // necessary on all methods (including GET). if (isSpecialPath(path)) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return; } final String method = req.getMethod(); if (debug > 0) { log("[" + method + "] " + path); } if (method.equals(METHOD_PROPFIND)) { doPropfind(req, resp); } else if (method.equals(METHOD_PROPPATCH)) { doProppatch(req, resp); } else if (method.equals(METHOD_MKCOL)) { doMkcol(req, resp); } else if (method.equals(METHOD_COPY)) { doCopy(req, resp); } else if (method.equals(METHOD_MOVE)) { doMove(req, resp); } else if (method.equals(METHOD_LOCK)) { doLock(req, resp); } else if (method.equals(METHOD_UNLOCK)) { doUnlock(req, resp); } else { // DefaultServlet processing super.service(req, resp); } } /** * Checks whether a given path refers to a resource under * <code>WEB-INF</code> or <code>META-INF</code>. * @param path the full path of the resource being accessed * @return <code>true</code> if the resource specified is under a special path */ private final boolean isSpecialPath(final String path) { return !allowSpecialPaths && ( path.toUpperCase(Locale.ENGLISH).startsWith("/WEB-INF") || path.toUpperCase(Locale.ENGLISH).startsWith("/META-INF")); } @Override protected boolean checkIfHeaders(HttpServletRequest request, HttpServletResponse response, WebResource resource) throws IOException { if (!super.checkIfHeaders(request, response, resource)) return false; // TODO : Checking the WebDAV If header return true; } /** * Override the DefaultServlet implementation and only use the PathInfo. If * the ServletPath is non-null, it will be because the WebDAV servlet has * been mapped to a url other than /* to configure editing at different url * than normal viewing. * * @param request The servlet request we are processing */ @Override protected String getRelativePath(HttpServletRequest request) { // Are we being processed by a RequestDispatcher.include()? if (request.getAttribute( RequestDispatcher.INCLUDE_REQUEST_URI) != null) { String result = (String) request.getAttribute( RequestDispatcher.INCLUDE_PATH_INFO); if ((result == null) || (result.equals(""))) result = "/"; return (result); } // No, extract the desired path directly from the request String result = request.getPathInfo(); if ((result == null) || (result.equals(""))) { result = "/"; } return (result); } /** * Determines the prefix for standard directory GET listings. */ @Override protected String getPathPrefix(final HttpServletRequest request) { // Repeat the servlet path (e.g. /webdav/) in the listing path String contextPath = request.getContextPath(); if (request.getServletPath() != null) { contextPath = contextPath + request.getServletPath(); } return contextPath; } /** * OPTIONS Method. * * @param req The request * @param resp The response * @throws ServletException If an error occurs * @throws IOException If an IO error occurs */ @Override protected void doOptions(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.addHeader("DAV", "1,2"); StringBuilder methodsAllowed = determineMethodsAllowed(req); resp.addHeader("Allow", methodsAllowed.toString()); resp.addHeader("MS-Author-Via", "DAV"); } /** * PROPFIND Method. */ protected void doPropfind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (!listings) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } String path = getRelativePath(req); if (path.endsWith("/")) path = path.substring(0, path.length() - 1); // Properties which are to be displayed. Vector<String> properties = null; // Propfind depth int depth = maxDepth; // Propfind type int type = FIND_ALL_PROP; String depthStr = req.getHeader("Depth"); if (depthStr == null) { depth = maxDepth; } else { if (depthStr.equals("0")) { depth = 0; } else if (depthStr.equals("1")) { depth = 1; } else if (depthStr.equals("infinity")) { depth = maxDepth; } } Node propNode = null; if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse (new InputSource(req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); NodeList childList = rootElement.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: if (currentNode.getNodeName().endsWith("prop")) { type = FIND_BY_PROPERTY; propNode = currentNode; } if (currentNode.getNodeName().endsWith("propname")) { type = FIND_PROPERTY_NAMES; } if (currentNode.getNodeName().endsWith("allprop")) { type = FIND_ALL_PROP; } break; } } } catch (SAXException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } catch (IOException e) { // Something went wrong - bad request resp.sendError(WebdavStatus.SC_BAD_REQUEST); } } if (type == FIND_BY_PROPERTY) { properties = new Vector<>(); // propNode must be non-null if type == FIND_BY_PROPERTY @SuppressWarnings("null") NodeList childList = propNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); String propertyName = null; if (nodeName.indexOf(':') != -1) { propertyName = nodeName.substring (nodeName.indexOf(':') + 1); } else { propertyName = nodeName; } // href is a live property which is handled differently properties.addElement(propertyName); break; } } } WebResource resource = resources.getResource(path); if (!resource.exists()) { int slash = path.lastIndexOf('/'); if (slash != -1) { String parentPath = path.substring(0, slash); Vector<String> currentLockNullResources = lockNullResources.get(parentPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); if (lockNullPath.equals(path)) { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); return; } } } } } if (!resource.exists()) { resp.sendError(HttpServletResponse.SC_NOT_FOUND, path); return; } resp.setStatus(WebdavStatus.SC_MULTI_STATUS); resp.setContentType("text/xml; charset=UTF-8"); // Create multistatus object XMLWriter generatedXML = new XMLWriter(resp.getWriter()); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); if (depth == 0) { parseProperties(req, generatedXML, path, type, properties); } else { // The stack always contains the object of the current level Stack<String> stack = new Stack<>(); stack.push(path); // Stack of the objects one level below Stack<String> stackBelow = new Stack<>(); while ((!stack.isEmpty()) && (depth >= 0)) { String currentPath = stack.pop(); parseProperties(req, generatedXML, currentPath, type, properties); resource = resources.getResource(currentPath); if (resource.isDirectory() && (depth > 0)) { String[] entries = resources.list(currentPath); for (String entry : entries) { String newPath = currentPath; if (!(newPath.endsWith("/"))) newPath += "/"; newPath += entry; stackBelow.push(newPath); } // Displaying the lock-null resources present in that // collection String lockPath = currentPath; if (lockPath.endsWith("/")) lockPath = lockPath.substring(0, lockPath.length() - 1); Vector<String> currentLockNullResources = lockNullResources.get(lockPath); if (currentLockNullResources != null) { Enumeration<String> lockNullResourcesList = currentLockNullResources.elements(); while (lockNullResourcesList.hasMoreElements()) { String lockNullPath = lockNullResourcesList.nextElement(); parseLockNullProperties (req, generatedXML, lockNullPath, type, properties); } } } if (stack.isEmpty()) { depth--; stack = stackBelow; stackBelow = new Stack<>(); } generatedXML.sendData(); } } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); generatedXML.sendData(); } /** * PROPPATCH Method. */ protected void doProppatch(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } resp.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED); } /** * MKCOL Method. */ protected void doMkcol(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); WebResource resource = resources.getResource(path); // Can't create a collection if a resource already exists at the given // path if (resource.exists()) { // Get allowed methods StringBuilder methodsAllowed = determineMethodsAllowed(req); resp.addHeader("Allow", methodsAllowed.toString()); resp.sendError(WebdavStatus.SC_METHOD_NOT_ALLOWED); return; } if (req.getContentLength() > 0) { DocumentBuilder documentBuilder = getDocumentBuilder(); try { // Document document = documentBuilder.parse(new InputSource(req.getInputStream())); // TODO : Process this request body resp.sendError(WebdavStatus.SC_NOT_IMPLEMENTED); return; } catch(SAXException saxe) { // Parse error - assume invalid content resp.sendError(WebdavStatus.SC_UNSUPPORTED_MEDIA_TYPE); return; } } if (resources.mkdir(path)) { resp.setStatus(WebdavStatus.SC_CREATED); // Removing any lock-null resource which would be present lockNullResources.remove(path); } else { resp.sendError(WebdavStatus.SC_CONFLICT, WebdavStatus.getStatusText (WebdavStatus.SC_CONFLICT)); } } /** * DELETE Method. */ @Override protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } deleteResource(req, resp); } /** * Process a PUT request for the specified resource. * * @param req The servlet request we are processing * @param resp The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } super.doPut(req, resp); String path = getRelativePath(req); // Removing any lock-null resource which would be present lockNullResources.remove(path); } /** * COPY Method. */ protected void doCopy(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } copyResource(req, resp); } /** * MOVE Method. */ protected void doMove(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); if (copyResource(req, resp)) { deleteResource(path, req, resp, false); } } /** * LOCK Method. */ protected void doLock(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } LockInfo lock = new LockInfo(); // Parsing lock request // Parsing depth header String depthStr = req.getHeader("Depth"); if (depthStr == null) { lock.depth = maxDepth; } else { if (depthStr.equals("0")) { lock.depth = 0; } else { lock.depth = maxDepth; } } // Parsing timeout header int lockDuration = DEFAULT_TIMEOUT; String lockDurationStr = req.getHeader("Timeout"); if (lockDurationStr == null) { lockDuration = DEFAULT_TIMEOUT; } else { int commaPos = lockDurationStr.indexOf(","); // If multiple timeouts, just use the first if (commaPos != -1) { lockDurationStr = lockDurationStr.substring(0,commaPos); } if (lockDurationStr.startsWith("Second-")) { lockDuration = (new Integer(lockDurationStr.substring(7))).intValue(); } else { if (lockDurationStr.equalsIgnoreCase("infinity")) { lockDuration = MAX_TIMEOUT; } else { try { lockDuration = (new Integer(lockDurationStr)).intValue(); } catch (NumberFormatException e) { lockDuration = MAX_TIMEOUT; } } } if (lockDuration == 0) { lockDuration = DEFAULT_TIMEOUT; } if (lockDuration > MAX_TIMEOUT) { lockDuration = MAX_TIMEOUT; } } lock.expiresAt = System.currentTimeMillis() + (lockDuration * 1000); int lockRequestType = LOCK_CREATION; Node lockInfoNode = null; DocumentBuilder documentBuilder = getDocumentBuilder(); try { Document document = documentBuilder.parse(new InputSource (req.getInputStream())); // Get the root element of the document Element rootElement = document.getDocumentElement(); lockInfoNode = rootElement; } catch (IOException e) { lockRequestType = LOCK_REFRESH; } catch (SAXException e) { lockRequestType = LOCK_REFRESH; } if (lockInfoNode != null) { // Reading lock information NodeList childList = lockInfoNode.getChildNodes(); StringWriter strWriter = null; DOMWriter domWriter = null; Node lockScopeNode = null; Node lockTypeNode = null; Node lockOwnerNode = null; for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String nodeName = currentNode.getNodeName(); if (nodeName.endsWith("lockscope")) { lockScopeNode = currentNode; } if (nodeName.endsWith("locktype")) { lockTypeNode = currentNode; } if (nodeName.endsWith("owner")) { lockOwnerNode = currentNode; } break; } } if (lockScopeNode != null) { childList = lockScopeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempScope = currentNode.getNodeName(); if (tempScope.indexOf(':') != -1) { lock.scope = tempScope.substring (tempScope.indexOf(':') + 1); } else { lock.scope = tempScope; } break; } } if (lock.scope == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockTypeNode != null) { childList = lockTypeNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: break; case Node.ELEMENT_NODE: String tempType = currentNode.getNodeName(); if (tempType.indexOf(':') != -1) { lock.type = tempType.substring(tempType.indexOf(':') + 1); } else { lock.type = tempType; } break; } } if (lock.type == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } if (lockOwnerNode != null) { childList = lockOwnerNode.getChildNodes(); for (int i=0; i < childList.getLength(); i++) { Node currentNode = childList.item(i); switch (currentNode.getNodeType()) { case Node.TEXT_NODE: lock.owner += currentNode.getNodeValue(); break; case Node.ELEMENT_NODE: strWriter = new StringWriter(); domWriter = new DOMWriter(strWriter, true); domWriter.print(currentNode); lock.owner += strWriter.toString(); break; } } if (lock.owner == null) { // Bad request resp.setStatus(WebdavStatus.SC_BAD_REQUEST); } } else { lock.owner = ""; } } String path = getRelativePath(req); lock.path = path; WebResource resource = resources.getResource(path); Enumeration<LockInfo> locksList = null; if (lockRequestType == LOCK_CREATION) { // Generating lock id String lockTokenStr = req.getServletPath() + "-" + lock.type + "-" + lock.scope + "-" + req.getUserPrincipal() + "-" + lock.depth + "-" + lock.owner + "-" + lock.tokens + "-" + lock.expiresAt + "-" + System.currentTimeMillis() + "-" + secret; String lockToken = MD5Encoder.encode(md5Helper.digest( lockTokenStr.getBytes(B2CConverter.ISO_8859_1))); if (resource.isDirectory() && lock.depth == maxDepth) { // Locking a collection (and all its member resources) // Checking if a child resource of this collection is // already locked Vector<String> lockPaths = new Vector<>(); locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child collection of this collection is locked lockPaths.addElement(currentLock.path); } } locksList = resourceLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.hasExpired()) { resourceLocks.remove(currentLock.path); continue; } if ( (currentLock.path.startsWith(lock.path)) && ((currentLock.isExclusive()) || (lock.isExclusive())) ) { // A child resource of this collection is locked lockPaths.addElement(currentLock.path); } } if (!lockPaths.isEmpty()) { // One of the child paths was locked // We generate a multistatus error report Enumeration<String> lockPathsList = lockPaths.elements(); resp.setStatus(WebdavStatus.SC_CONFLICT); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); while (lockPathsList.hasMoreElements()) { generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); generatedXML.writeText(lockPathsList.nextElement()); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML .writeText("HTTP/1.1 " + WebdavStatus.SC_LOCKED + " " + WebdavStatus .getStatusText(WebdavStatus.SC_LOCKED)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); return; } boolean addLock = true; // Checking if there is already a shared lock on this path locksList = collectionLocks.elements(); while (locksList.hasMoreElements()) { LockInfo currentLock = locksList.nextElement(); if (currentLock.path.equals(lock.path)) { if (currentLock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } else { if (lock.isExclusive()) { resp.sendError(WebdavStatus.SC_LOCKED); return; } } currentLock.tokens.addElement(lockToken); lock = currentLock; addLock = false; } } if (addLock) { lock.tokens.addElement(lockToken); collectionLocks.addElement(lock); } } else { // Locking a single resource // Retrieving an already existing lock on that resource LockInfo presentLock = resourceLocks.get(lock.path); if (presentLock != null) { if ((presentLock.isExclusive()) || (lock.isExclusive())) { // If either lock is exclusive, the lock can't be // granted resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return; } else { presentLock.tokens.addElement(lockToken); lock = presentLock; } } else { lock.tokens.addElement(lockToken); resourceLocks.put(lock.path, lock); // Checking if a resource exists at this path if (!resource.exists()) { // "Creating" a lock-null resource int slash = lock.path.lastIndexOf('/'); String parentPath = lock.path.substring(0, slash); Vector<String> lockNulls = lockNullResources.get(parentPath); if (lockNulls == null) { lockNulls = new Vector<>(); lockNullResources.put(parentPath, lockNulls); } lockNulls.addElement(lock.path); } // Add the Lock-Token header as by RFC 2518 8.10.1 // - only do this for newly created locks resp.addHeader("Lock-Token", "<opaquelocktoken:" + lockToken + ">"); } } } if (lockRequestType == LOCK_REFRESH) { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; // Checking resource locks LockInfo toRenew = resourceLocks.get(path); Enumeration<String> tokenList = null; if (toRenew != null) { // At least one of the tokens of the locks must have been given tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { toRenew = collectionLocksList.nextElement(); if (path.equals(toRenew.path)) { tokenList = toRenew.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) { toRenew.expiresAt = lock.expiresAt; lock = toRenew; } } } } } // Set the status, then generate the XML response containing // the lock information XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); lock.toXML(generatedXML); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); resp.setStatus(WebdavStatus.SC_OK); resp.setContentType("text/xml; charset=UTF-8"); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); } /** * UNLOCK Method. */ protected void doUnlock(HttpServletRequest req, HttpServletResponse resp) throws IOException { if (readOnly) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return; } if (isLocked(req)) { resp.sendError(WebdavStatus.SC_LOCKED); return; } String path = getRelativePath(req); String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; // Checking resource locks LockInfo lock = resourceLocks.get(path); Enumeration<String> tokenList = null; if (lock != null) { // At least one of the tokens of the locks must have been given tokenList = lock.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (lockTokenHeader.indexOf(token) != -1) { lock.tokens.removeElement(token); } } if (lock.tokens.isEmpty()) { resourceLocks.remove(path); // Removing any lock-null resource which would be present lockNullResources.remove(path); } } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { lock = collectionLocksList.nextElement(); if (path.equals(lock.path)) { tokenList = lock.tokens.elements(); while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (lockTokenHeader.indexOf(token) != -1) { lock.tokens.removeElement(token); break; } } if (lock.tokens.isEmpty()) { collectionLocks.removeElement(lock); // Removing any lock-null resource which would be present lockNullResources.remove(path); } } } resp.setStatus(WebdavStatus.SC_NO_CONTENT); } // -------------------------------------------------------- Private Methods /** * Check to see if a resource is currently write locked. The method * will look at the "If" header to make sure the client * has give the appropriate lock tokens. * * @param req Servlet request * @return boolean true if the resource is locked (and no appropriate * lock token has been found for at least one of the non-shared locks which * are present on the resource). */ private boolean isLocked(HttpServletRequest req) { String path = getRelativePath(req); String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; return isLocked(path, ifHeader + lockTokenHeader); } /** * Check to see if a resource is currently write locked. * * @param path Path of the resource * @param ifHeader "If" HTTP header which was included in the request * @return boolean true if the resource is locked (and no appropriate * lock token has been found for at least one of the non-shared locks which * are present on the resource). */ private boolean isLocked(String path, String ifHeader) { // Checking resource locks LockInfo lock = resourceLocks.get(path); Enumeration<String> tokenList = null; if ((lock != null) && (lock.hasExpired())) { resourceLocks.remove(path); } else if (lock != null) { // At least one of the tokens of the locks must have been given tokenList = lock.tokens.elements(); boolean tokenMatch = false; while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) tokenMatch = true; } if (!tokenMatch) return true; } // Checking inheritable collection locks Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); while (collectionLocksList.hasMoreElements()) { lock = collectionLocksList.nextElement(); if (lock.hasExpired()) { collectionLocks.removeElement(lock); } else if (path.startsWith(lock.path)) { tokenList = lock.tokens.elements(); boolean tokenMatch = false; while (tokenList.hasMoreElements()) { String token = tokenList.nextElement(); if (ifHeader.indexOf(token) != -1) tokenMatch = true; } if (!tokenMatch) return true; } } return false; } /** * Copy a resource. * * @param req Servlet request * @param resp Servlet response * @return boolean true if the copy is successful */ private boolean copyResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { // Parsing destination header String destinationPath = req.getHeader("Destination"); if (destinationPath == null) { resp.sendError(WebdavStatus.SC_BAD_REQUEST); return false; } // Remove url encoding from destination destinationPath = org.apache.catalina.util.RequestUtil.URLDecode( destinationPath, "UTF8"); int protocolIndex = destinationPath.indexOf("://"); if (protocolIndex >= 0) { // if the Destination URL contains the protocol, we can safely // trim everything upto the first "/" character after "://" int firstSeparator = destinationPath.indexOf("/", protocolIndex + 4); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } else { String hostName = req.getServerName(); if ((hostName != null) && (destinationPath.startsWith(hostName))) { destinationPath = destinationPath.substring(hostName.length()); } int portIndex = destinationPath.indexOf(":"); if (portIndex >= 0) { destinationPath = destinationPath.substring(portIndex); } if (destinationPath.startsWith(":")) { int firstSeparator = destinationPath.indexOf("/"); if (firstSeparator < 0) { destinationPath = "/"; } else { destinationPath = destinationPath.substring(firstSeparator); } } } // Normalise destination path (remove '.' and '..') destinationPath = RequestUtil.normalize(destinationPath); String contextPath = req.getContextPath(); if ((contextPath != null) && (destinationPath.startsWith(contextPath))) { destinationPath = destinationPath.substring(contextPath.length()); } String pathInfo = req.getPathInfo(); if (pathInfo != null) { String servletPath = req.getServletPath(); if ((servletPath != null) && (destinationPath.startsWith(servletPath))) { destinationPath = destinationPath .substring(servletPath.length()); } } if (debug > 0) log("Dest path :" + destinationPath); // Check destination path to protect special subdirectories if (isSpecialPath(destinationPath)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } String path = getRelativePath(req); if (destinationPath.equals(path)) { resp.sendError(WebdavStatus.SC_FORBIDDEN); return false; } // Parsing overwrite header boolean overwrite = true; String overwriteHeader = req.getHeader("Overwrite"); if (overwriteHeader != null) { if (overwriteHeader.equalsIgnoreCase("T")) { overwrite = true; } else { overwrite = false; } } // Overwriting the destination WebResource destination = resources.getResource(destinationPath); if (overwrite) { // Delete destination resource, if it exists if (destination.exists()) { if (!deleteResource(destinationPath, req, resp, true)) { return false; } } else { resp.setStatus(WebdavStatus.SC_CREATED); } } else { // If the destination exists, then it's a conflict if (destination.exists()) { resp.sendError(WebdavStatus.SC_PRECONDITION_FAILED); return false; } } // Copying source to destination Hashtable<String,Integer> errorList = new Hashtable<>(); boolean result = copyResource(errorList, path, destinationPath); if ((!result) || (!errorList.isEmpty())) { if (errorList.size() == 1) { resp.sendError(errorList.elements().nextElement().intValue()); } else { sendReport(req, resp, errorList); } return false; } // Copy was successful if (destination.exists()) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } else { resp.setStatus(WebdavStatus.SC_CREATED); } // Removing any lock-null resource which would be present at // the destination path lockNullResources.remove(destinationPath); return true; } /** * Copy a collection. * * @param errorList Hashtable containing the list of errors which occurred * during the copy operation * @param source Path of the resource to be copied * @param dest Destination path */ private boolean copyResource(Hashtable<String,Integer> errorList, String source, String dest) { if (debug > 1) log("Copy: " + source + " To: " + dest); WebResource sourceResource = resources.getResource(source); if (sourceResource.isDirectory()) { if (!resources.mkdir(dest)) { WebResource destResource = resources.getResource(dest); if (!destResource.isDirectory()) { errorList.put(dest, new Integer(WebdavStatus.SC_CONFLICT)); return false; } } String[] entries = resources.list(source); for (String entry : entries) { String childDest = dest; if (!childDest.equals("/")) { childDest += "/"; } childDest += entry; String childSrc = source; if (!childSrc.equals("/")) { childSrc += "/"; } childSrc += entry; copyResource(errorList, childSrc, childDest); } } else if (sourceResource.isFile()) { if (!resources.write(dest, sourceResource.getInputStream(), false)) { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } } else { errorList.put(source, new Integer(WebdavStatus.SC_INTERNAL_SERVER_ERROR)); return false; } return true; } /** * Delete a resource. * * @param req Servlet request * @param resp Servlet response * @return boolean true if the copy is successful */ private boolean deleteResource(HttpServletRequest req, HttpServletResponse resp) throws IOException { String path = getRelativePath(req); return deleteResource(path, req, resp, true); } /** * Delete a resource. * * @param path Path of the resource which is to be deleted * @param req Servlet request * @param resp Servlet response * @param setStatus Should the response status be set on successful * completion */ private boolean deleteResource(String path, HttpServletRequest req, HttpServletResponse resp, boolean setStatus) throws IOException { String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; if (isLocked(path, ifHeader + lockTokenHeader)) { resp.sendError(WebdavStatus.SC_LOCKED); return false; } WebResource resource = resources.getResource(path); if (!resource.exists()) { resp.sendError(WebdavStatus.SC_NOT_FOUND); return false; } if (!resource.isDirectory()) { if (!resource.delete()) { resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR); return false; } } else { Hashtable<String,Integer> errorList = new Hashtable<>(); deleteCollection(req, path, errorList); if (!resource.delete()) { errorList.put(path, new Integer (WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } if (!errorList.isEmpty()) { sendReport(req, resp, errorList); return false; } } if (setStatus) { resp.setStatus(WebdavStatus.SC_NO_CONTENT); } return true; } /** * Deletes a collection. * * @param path Path to the collection to be deleted * @param errorList Contains the list of the errors which occurred */ private void deleteCollection(HttpServletRequest req, String path, Hashtable<String,Integer> errorList) { if (debug > 1) log("Delete:" + path); // Prevent deletion of special subdirectories if (isSpecialPath(path)) { errorList.put(path, new Integer(WebdavStatus.SC_FORBIDDEN)); return; } String ifHeader = req.getHeader("If"); if (ifHeader == null) ifHeader = ""; String lockTokenHeader = req.getHeader("Lock-Token"); if (lockTokenHeader == null) lockTokenHeader = ""; String[] entries = resources.list(path); for (String entry : entries) { String childName = path; if (!childName.equals("/")) childName += "/"; childName += entry; if (isLocked(childName, ifHeader + lockTokenHeader)) { errorList.put(childName, new Integer(WebdavStatus.SC_LOCKED)); } else { WebResource childResource = resources.getResource(childName); if (childResource.isDirectory()) { deleteCollection(req, childName, errorList); } if (!childResource.delete()) { if (!childResource.isDirectory()) { // If it's not a collection, then it's an unknown // error errorList.put(childName, new Integer( WebdavStatus.SC_INTERNAL_SERVER_ERROR)); } } } } } /** * Send a multistatus element containing a complete error report to the * client. * * @param req Servlet request * @param resp Servlet response * @param errorList List of error to be displayed */ private void sendReport(HttpServletRequest req, HttpServletResponse resp, Hashtable<String,Integer> errorList) throws IOException { resp.setStatus(WebdavStatus.SC_MULTI_STATUS); String absoluteUri = req.getRequestURI(); String relativePath = getRelativePath(req); XMLWriter generatedXML = new XMLWriter(); generatedXML.writeXMLHeader(); generatedXML.writeElement("D", DEFAULT_NAMESPACE, "multistatus", XMLWriter.OPENING); Enumeration<String> pathList = errorList.keys(); while (pathList.hasMoreElements()) { String errorPath = pathList.nextElement(); int errorCode = errorList.get(errorPath).intValue(); generatedXML.writeElement("D", "response", XMLWriter.OPENING); generatedXML.writeElement("D", "href", XMLWriter.OPENING); String toAppend = errorPath.substring(relativePath.length()); if (!toAppend.startsWith("/")) toAppend = "/" + toAppend; generatedXML.writeText(absoluteUri + toAppend); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText("HTTP/1.1 " + errorCode + " " + WebdavStatus.getStatusText(errorCode)); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } generatedXML.writeElement("D", "multistatus", XMLWriter.CLOSING); Writer writer = resp.getWriter(); writer.write(generatedXML.toString()); writer.close(); } /** * Propfind helper method. * * @param req The servlet request * @param resources Resources object associated with this context * @param generatedXML XML response to the Propfind request * @param path Path of the current resource * @param type Propfind type * @param propertiesVector If the propfind type is find properties by * name, then this Vector contains those properties */ private void parseProperties(HttpServletRequest req, XMLWriter generatedXML, String path, int type, Vector<String> propertiesVector) { // Exclude any resource in the /WEB-INF and /META-INF subdirectories if (isSpecialPath(path)) return; WebResource resource = resources.getResource(path); if (!resource.exists()) { // File is in directory listing but doesn't appear to exist // Broken symlink or odd permission settings? return; } generatedXML.writeElement("D", "response", XMLWriter.OPENING); String status = "HTTP/1.1 " + WebdavStatus.SC_OK + " " + WebdavStatus.getStatusText(WebdavStatus.SC_OK); // Generating href element generatedXML.writeElement("D", "href", XMLWriter.OPENING); String href = req.getContextPath() + req.getServletPath(); if ((href.endsWith("/")) && (path.startsWith("/"))) href += path.substring(1); else href += path; if (resource.isDirectory() && (!href.endsWith("/"))) href += "/"; generatedXML.writeText(rewriteUrl(href)); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); String resourceName = path; int lastSlash = path.lastIndexOf('/'); if (lastSlash != -1) resourceName = resourceName.substring(lastSlash + 1); switch (type) { case FIND_ALL_PROP : generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); generatedXML.writeProperty("D", "creationdate", getISOCreationDate(resource.getCreation())); generatedXML.writeElement("D", "displayname", XMLWriter.OPENING); generatedXML.writeData(resourceName); generatedXML.writeElement("D", "displayname", XMLWriter.CLOSING); if (resource.isFile()) { generatedXML.writeProperty ("D", "getlastmodified", FastHttpDateFormat.formatDate (resource.getLastModified(), null)); generatedXML.writeProperty ("D", "getcontentlength", String.valueOf(resource.getContentLength())); String contentType = getServletContext().getMimeType( resource.getName()); if (contentType != null) { generatedXML.writeProperty("D", "getcontenttype", contentType); } generatedXML.writeProperty("D", "getetag",resource.getETag()); generatedXML.writeElement("D", "resourcetype", XMLWriter.NO_CONTENT); } else { generatedXML.writeElement("D", "resourcetype", XMLWriter.OPENING); generatedXML.writeElement("D", "collection", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "resourcetype", XMLWriter.CLOSING); } generatedXML.writeProperty("D", "source", ""); String supportedLocks = "<D:lockentry>" + "<D:lockscope><D:exclusive/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>" + "<D:lockentry>" + "<D:lockscope><D:shared/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>"; generatedXML.writeElement("D", "supportedlock", XMLWriter.OPENING); generatedXML.writeText(supportedLocks); generatedXML.writeElement("D", "supportedlock", XMLWriter.CLOSING); generateLockDiscovery(path, generatedXML); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); break; case FIND_PROPERTY_NAMES : generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "creationdate", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "displayname", XMLWriter.NO_CONTENT); if (resource.isFile()) { generatedXML.writeElement("D", "getcontentlanguage", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getcontentlength", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getcontenttype", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getetag", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getlastmodified", XMLWriter.NO_CONTENT); } generatedXML.writeElement("D", "resourcetype", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "source", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); break; case FIND_BY_PROPERTY : Vector<String> propertiesNotFound = new Vector<>(); // Parse the list of properties generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); Enumeration<String> properties = propertiesVector.elements(); while (properties.hasMoreElements()) { String property = properties.nextElement(); if (property.equals("creationdate")) { generatedXML.writeProperty ("D", "creationdate", getISOCreationDate(resource.getCreation())); } else if (property.equals("displayname")) { generatedXML.writeElement ("D", "displayname", XMLWriter.OPENING); generatedXML.writeData(resourceName); generatedXML.writeElement ("D", "displayname", XMLWriter.CLOSING); } else if (property.equals("getcontentlanguage")) { if (resource.isDirectory()) { propertiesNotFound.addElement(property); } else { generatedXML.writeElement("D", "getcontentlanguage", XMLWriter.NO_CONTENT); } } else if (property.equals("getcontentlength")) { if (resource.isDirectory()) { propertiesNotFound.addElement(property); } else { generatedXML.writeProperty ("D", "getcontentlength", (String.valueOf(resource.getContentLength()))); } } else if (property.equals("getcontenttype")) { if (resource.isDirectory()) { propertiesNotFound.addElement(property); } else { generatedXML.writeProperty ("D", "getcontenttype", getServletContext().getMimeType (resource.getName())); } } else if (property.equals("getetag")) { if (resource.isDirectory()) { propertiesNotFound.addElement(property); } else { generatedXML.writeProperty ("D", "getetag", resource.getETag()); } } else if (property.equals("getlastmodified")) { if (resource.isDirectory()) { propertiesNotFound.addElement(property); } else { generatedXML.writeProperty ("D", "getlastmodified", FastHttpDateFormat.formatDate (resource.getLastModified(), null)); } } else if (property.equals("resourcetype")) { if (resource.isDirectory()) { generatedXML.writeElement("D", "resourcetype", XMLWriter.OPENING); generatedXML.writeElement("D", "collection", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "resourcetype", XMLWriter.CLOSING); } else { generatedXML.writeElement("D", "resourcetype", XMLWriter.NO_CONTENT); } } else if (property.equals("source")) { generatedXML.writeProperty("D", "source", ""); } else if (property.equals("supportedlock")) { supportedLocks = "<D:lockentry>" + "<D:lockscope><D:exclusive/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>" + "<D:lockentry>" + "<D:lockscope><D:shared/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>"; generatedXML.writeElement("D", "supportedlock", XMLWriter.OPENING); generatedXML.writeText(supportedLocks); generatedXML.writeElement("D", "supportedlock", XMLWriter.CLOSING); } else if (property.equals("lockdiscovery")) { if (!generateLockDiscovery(path, generatedXML)) propertiesNotFound.addElement(property); } else { propertiesNotFound.addElement(property); } } generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); Enumeration<String> propertiesNotFoundList = propertiesNotFound.elements(); if (propertiesNotFoundList.hasMoreElements()) { status = "HTTP/1.1 " + WebdavStatus.SC_NOT_FOUND + " " + WebdavStatus.getStatusText(WebdavStatus.SC_NOT_FOUND); generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); while (propertiesNotFoundList.hasMoreElements()) { generatedXML.writeElement ("D", propertiesNotFoundList.nextElement(), XMLWriter.NO_CONTENT); } generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); } break; } generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } /** * Propfind helper method. Displays the properties of a lock-null resource. * * @param resources Resources object associated with this context * @param generatedXML XML response to the Propfind request * @param path Path of the current resource * @param type Propfind type * @param propertiesVector If the propfind type is find properties by * name, then this Vector contains those properties */ private void parseLockNullProperties(HttpServletRequest req, XMLWriter generatedXML, String path, int type, Vector<String> propertiesVector) { // Exclude any resource in the /WEB-INF and /META-INF subdirectories if (isSpecialPath(path)) return; // Retrieving the lock associated with the lock-null resource LockInfo lock = resourceLocks.get(path); if (lock == null) return; generatedXML.writeElement("D", "response", XMLWriter.OPENING); String status = "HTTP/1.1 " + WebdavStatus.SC_OK + " " + WebdavStatus.getStatusText(WebdavStatus.SC_OK); // Generating href element generatedXML.writeElement("D", "href", XMLWriter.OPENING); String absoluteUri = req.getRequestURI(); String relativePath = getRelativePath(req); String toAppend = path.substring(relativePath.length()); if (!toAppend.startsWith("/")) toAppend = "/" + toAppend; generatedXML.writeText(rewriteUrl(RequestUtil.normalize( absoluteUri + toAppend))); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); String resourceName = path; int lastSlash = path.lastIndexOf('/'); if (lastSlash != -1) resourceName = resourceName.substring(lastSlash + 1); switch (type) { case FIND_ALL_PROP : generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); generatedXML.writeProperty("D", "creationdate", getISOCreationDate(lock.creationDate.getTime())); generatedXML.writeElement("D", "displayname", XMLWriter.OPENING); generatedXML.writeData(resourceName); generatedXML.writeElement("D", "displayname", XMLWriter.CLOSING); generatedXML.writeProperty("D", "getlastmodified", FastHttpDateFormat.formatDate (lock.creationDate.getTime(), null)); generatedXML.writeProperty("D", "getcontentlength", String.valueOf(0)); generatedXML.writeProperty("D", "getcontenttype", ""); generatedXML.writeProperty("D", "getetag", ""); generatedXML.writeElement("D", "resourcetype", XMLWriter.OPENING); generatedXML.writeElement("D", "lock-null", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "resourcetype", XMLWriter.CLOSING); generatedXML.writeProperty("D", "source", ""); String supportedLocks = "<D:lockentry>" + "<D:lockscope><D:exclusive/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>" + "<D:lockentry>" + "<D:lockscope><D:shared/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>"; generatedXML.writeElement("D", "supportedlock", XMLWriter.OPENING); generatedXML.writeText(supportedLocks); generatedXML.writeElement("D", "supportedlock", XMLWriter.CLOSING); generateLockDiscovery(path, generatedXML); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); break; case FIND_PROPERTY_NAMES : generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); generatedXML.writeElement("D", "creationdate", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "displayname", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getcontentlanguage", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getcontentlength", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getcontenttype", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getetag", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "getlastmodified", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "resourcetype", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "source", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "lockdiscovery", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); break; case FIND_BY_PROPERTY : Vector<String> propertiesNotFound = new Vector<>(); // Parse the list of properties generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); Enumeration<String> properties = propertiesVector.elements(); while (properties.hasMoreElements()) { String property = properties.nextElement(); if (property.equals("creationdate")) { generatedXML.writeProperty("D", "creationdate", getISOCreationDate(lock.creationDate.getTime())); } else if (property.equals("displayname")) { generatedXML.writeElement("D", "displayname", XMLWriter.OPENING); generatedXML.writeData(resourceName); generatedXML.writeElement("D", "displayname", XMLWriter.CLOSING); } else if (property.equals("getcontentlanguage")) { generatedXML.writeElement("D", "getcontentlanguage", XMLWriter.NO_CONTENT); } else if (property.equals("getcontentlength")) { generatedXML.writeProperty("D", "getcontentlength", (String.valueOf(0))); } else if (property.equals("getcontenttype")) { generatedXML.writeProperty("D", "getcontenttype", ""); } else if (property.equals("getetag")) { generatedXML.writeProperty("D", "getetag", ""); } else if (property.equals("getlastmodified")) { generatedXML.writeProperty ("D", "getlastmodified", FastHttpDateFormat.formatDate (lock.creationDate.getTime(), null)); } else if (property.equals("resourcetype")) { generatedXML.writeElement("D", "resourcetype", XMLWriter.OPENING); generatedXML.writeElement("D", "lock-null", XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "resourcetype", XMLWriter.CLOSING); } else if (property.equals("source")) { generatedXML.writeProperty("D", "source", ""); } else if (property.equals("supportedlock")) { supportedLocks = "<D:lockentry>" + "<D:lockscope><D:exclusive/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>" + "<D:lockentry>" + "<D:lockscope><D:shared/></D:lockscope>" + "<D:locktype><D:write/></D:locktype>" + "</D:lockentry>"; generatedXML.writeElement("D", "supportedlock", XMLWriter.OPENING); generatedXML.writeText(supportedLocks); generatedXML.writeElement("D", "supportedlock", XMLWriter.CLOSING); } else if (property.equals("lockdiscovery")) { if (!generateLockDiscovery(path, generatedXML)) propertiesNotFound.addElement(property); } else { propertiesNotFound.addElement(property); } } generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); Enumeration<String> propertiesNotFoundList = propertiesNotFound.elements(); if (propertiesNotFoundList.hasMoreElements()) { status = "HTTP/1.1 " + WebdavStatus.SC_NOT_FOUND + " " + WebdavStatus.getStatusText(WebdavStatus.SC_NOT_FOUND); generatedXML.writeElement("D", "propstat", XMLWriter.OPENING); generatedXML.writeElement("D", "prop", XMLWriter.OPENING); while (propertiesNotFoundList.hasMoreElements()) { generatedXML.writeElement ("D", propertiesNotFoundList.nextElement(), XMLWriter.NO_CONTENT); } generatedXML.writeElement("D", "prop", XMLWriter.CLOSING); generatedXML.writeElement("D", "status", XMLWriter.OPENING); generatedXML.writeText(status); generatedXML.writeElement("D", "status", XMLWriter.CLOSING); generatedXML.writeElement("D", "propstat", XMLWriter.CLOSING); } break; } generatedXML.writeElement("D", "response", XMLWriter.CLOSING); } /** * Print the lock discovery information associated with a path. * * @param path Path * @param generatedXML XML data to which the locks info will be appended * @return true if at least one lock was displayed */ private boolean generateLockDiscovery (String path, XMLWriter generatedXML) { LockInfo resourceLock = resourceLocks.get(path); Enumeration<LockInfo> collectionLocksList = collectionLocks.elements(); boolean wroteStart = false; if (resourceLock != null) { wroteStart = true; generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); resourceLock.toXML(generatedXML); } while (collectionLocksList.hasMoreElements()) { LockInfo currentLock = collectionLocksList.nextElement(); if (path.startsWith(currentLock.path)) { if (!wroteStart) { wroteStart = true; generatedXML.writeElement("D", "lockdiscovery", XMLWriter.OPENING); } currentLock.toXML(generatedXML); } } if (wroteStart) { generatedXML.writeElement("D", "lockdiscovery", XMLWriter.CLOSING); } else { return false; } return true; } /** * Get creation date in ISO format. */ private String getISOCreationDate(long creationDate) { return creationDateFormat.format(new Date(creationDate)); } /** * Determines the methods normally allowed for the resource. * */ private StringBuilder determineMethodsAllowed(HttpServletRequest req) { StringBuilder methodsAllowed = new StringBuilder(); WebResource resource = resources.getResource(getRelativePath(req)); if (!resource.exists()) { methodsAllowed.append("OPTIONS, MKCOL, PUT, LOCK"); return methodsAllowed; } methodsAllowed.append("OPTIONS, GET, HEAD, POST, DELETE, TRACE"); methodsAllowed.append(", PROPPATCH, COPY, MOVE, LOCK, UNLOCK"); if (listings) { methodsAllowed.append(", PROPFIND"); } if (resource.isFile()) { methodsAllowed.append(", PUT"); } return methodsAllowed; } // -------------------------------------------------- LockInfo Inner Class /** * Holds a lock information. */ private class LockInfo { // -------------------------------------------------------- Constructor /** * Constructor. */ public LockInfo() { // Ignore } // ------------------------------------------------- Instance Variables String path = "/"; String type = "write"; String scope = "exclusive"; int depth = 0; String owner = ""; Vector<String> tokens = new Vector<>(); long expiresAt = 0; Date creationDate = new Date(); // ----------------------------------------------------- Public Methods /** * Get a String representation of this lock token. */ @Override public String toString() { StringBuilder result = new StringBuilder("Type:"); result.append(type); result.append("\nScope:"); result.append(scope); result.append("\nDepth:"); result.append(depth); result.append("\nOwner:"); result.append(owner); result.append("\nExpiration:"); result.append(FastHttpDateFormat.formatDate(expiresAt, null)); Enumeration<String> tokensList = tokens.elements(); while (tokensList.hasMoreElements()) { result.append("\nToken:"); result.append(tokensList.nextElement()); } result.append("\n"); return result.toString(); } /** * Return true if the lock has expired. */ public boolean hasExpired() { return (System.currentTimeMillis() > expiresAt); } /** * Return true if the lock is exclusive. */ public boolean isExclusive() { return (scope.equals("exclusive")); } /** * Get an XML representation of this lock token. This method will * append an XML fragment to the given XML writer. */ public void toXML(XMLWriter generatedXML) { generatedXML.writeElement("D", "activelock", XMLWriter.OPENING); generatedXML.writeElement("D", "locktype", XMLWriter.OPENING); generatedXML.writeElement("D", type, XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "locktype", XMLWriter.CLOSING); generatedXML.writeElement("D", "lockscope", XMLWriter.OPENING); generatedXML.writeElement("D", scope, XMLWriter.NO_CONTENT); generatedXML.writeElement("D", "lockscope", XMLWriter.CLOSING); generatedXML.writeElement("D", "depth", XMLWriter.OPENING); if (depth == maxDepth) { generatedXML.writeText("Infinity"); } else { generatedXML.writeText("0"); } generatedXML.writeElement("D", "depth", XMLWriter.CLOSING); generatedXML.writeElement("D", "owner", XMLWriter.OPENING); generatedXML.writeText(owner); generatedXML.writeElement("D", "owner", XMLWriter.CLOSING); generatedXML.writeElement("D", "timeout", XMLWriter.OPENING); long timeout = (expiresAt - System.currentTimeMillis()) / 1000; generatedXML.writeText("Second-" + timeout); generatedXML.writeElement("D", "timeout", XMLWriter.CLOSING); generatedXML.writeElement("D", "locktoken", XMLWriter.OPENING); Enumeration<String> tokensList = tokens.elements(); while (tokensList.hasMoreElements()) { generatedXML.writeElement("D", "href", XMLWriter.OPENING); generatedXML.writeText("opaquelocktoken:" + tokensList.nextElement()); generatedXML.writeElement("D", "href", XMLWriter.CLOSING); } generatedXML.writeElement("D", "locktoken", XMLWriter.CLOSING); generatedXML.writeElement("D", "activelock", XMLWriter.CLOSING); } } // --------------------------------------------- WebdavResolver Inner Class /** * Work around for XML parsers that don't fully respect * {@link DocumentBuilderFactory#setExpandEntityReferences(boolean)} when * called with <code>false</code>. External references are filtered out for * security reasons. See CVE-2007-5461. */ private static class WebdavResolver implements EntityResolver { private ServletContext context; public WebdavResolver(ServletContext theContext) { context = theContext; } @Override public InputSource resolveEntity (String publicId, String systemId) { context.log(sm.getString("webdavservlet.enternalEntityIgnored", publicId, systemId)); return new InputSource( new StringReader("Ignored external entity")); } } } // -------------------------------------------------------- WebdavStatus Class /** * Wraps the HttpServletResponse class to abstract the * specific protocol used. To support other protocols * we would only need to modify this class and the * WebDavRetCode classes. * * @author Marc Eaddy * @version 1.0, 16 Nov 1997 */ class WebdavStatus { // ----------------------------------------------------- Instance Variables /** * This Hashtable contains the mapping of HTTP and WebDAV * status codes to descriptive text. This is a static * variable. */ private static final Hashtable<Integer,String> mapStatusCodes = new Hashtable<>(); // ------------------------------------------------------ HTTP Status Codes /** * Status code (200) indicating the request succeeded normally. */ public static final int SC_OK = HttpServletResponse.SC_OK; /** * Status code (201) indicating the request succeeded and created * a new resource on the server. */ public static final int SC_CREATED = HttpServletResponse.SC_CREATED; /** * Status code (202) indicating that a request was accepted for * processing, but was not completed. */ public static final int SC_ACCEPTED = HttpServletResponse.SC_ACCEPTED; /** * Status code (204) indicating that the request succeeded but that * there was no new information to return. */ public static final int SC_NO_CONTENT = HttpServletResponse.SC_NO_CONTENT; /** * Status code (301) indicating that the resource has permanently * moved to a new location, and that future references should use a * new URI with their requests. */ public static final int SC_MOVED_PERMANENTLY = HttpServletResponse.SC_MOVED_PERMANENTLY; /** * Status code (302) indicating that the resource has temporarily * moved to another location, but that future references should * still use the original URI to access the resource. */ public static final int SC_MOVED_TEMPORARILY = HttpServletResponse.SC_MOVED_TEMPORARILY; /** * Status code (304) indicating that a conditional GET operation * found that the resource was available and not modified. */ public static final int SC_NOT_MODIFIED = HttpServletResponse.SC_NOT_MODIFIED; /** * Status code (400) indicating the request sent by the client was * syntactically incorrect. */ public static final int SC_BAD_REQUEST = HttpServletResponse.SC_BAD_REQUEST; /** * Status code (401) indicating that the request requires HTTP * authentication. */ public static final int SC_UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED; /** * Status code (403) indicating the server understood the request * but refused to fulfill it. */ public static final int SC_FORBIDDEN = HttpServletResponse.SC_FORBIDDEN; /** * Status code (404) indicating that the requested resource is not * available. */ public static final int SC_NOT_FOUND = HttpServletResponse.SC_NOT_FOUND; /** * Status code (500) indicating an error inside the HTTP service * which prevented it from fulfilling the request. */ public static final int SC_INTERNAL_SERVER_ERROR = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; /** * Status code (501) indicating the HTTP service does not support * the functionality needed to fulfill the request. */ public static final int SC_NOT_IMPLEMENTED = HttpServletResponse.SC_NOT_IMPLEMENTED; /** * Status code (502) indicating that the HTTP server received an * invalid response from a server it consulted when acting as a * proxy or gateway. */ public static final int SC_BAD_GATEWAY = HttpServletResponse.SC_BAD_GATEWAY; /** * Status code (503) indicating that the HTTP service is * temporarily overloaded, and unable to handle the request. */ public static final int SC_SERVICE_UNAVAILABLE = HttpServletResponse.SC_SERVICE_UNAVAILABLE; /** * Status code (100) indicating the client may continue with * its request. This interim response is used to inform the * client that the initial part of the request has been * received and has not yet been rejected by the server. */ public static final int SC_CONTINUE = 100; /** * Status code (405) indicating the method specified is not * allowed for the resource. */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** * Status code (409) indicating that the request could not be * completed due to a conflict with the current state of the * resource. */ public static final int SC_CONFLICT = 409; /** * Status code (412) indicating the precondition given in one * or more of the request-header fields evaluated to false * when it was tested on the server. */ public static final int SC_PRECONDITION_FAILED = 412; /** * Status code (413) indicating the server is refusing to * process a request because the request entity is larger * than the server is willing or able to process. */ public static final int SC_REQUEST_TOO_LONG = 413; /** * Status code (415) indicating the server is refusing to service * the request because the entity of the request is in a format * not supported by the requested resource for the requested * method. */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; // -------------------------------------------- Extended WebDav status code /** * Status code (207) indicating that the response requires * providing status for multiple independent operations. */ public static final int SC_MULTI_STATUS = 207; // This one collides with HTTP 1.1 // "207 Partial Update OK" /** * Status code (418) indicating the entity body submitted with * the PATCH method was not understood by the resource. */ public static final int SC_UNPROCESSABLE_ENTITY = 418; // This one collides with HTTP 1.1 // "418 Reauthentication Required" /** * Status code (419) indicating that the resource does not have * sufficient space to record the state of the resource after the * execution of this method. */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; // This one collides with HTTP 1.1 // "419 Proxy Reauthentication Required" /** * Status code (420) indicating the method was not executed on * a particular resource within its scope because some part of * the method's execution failed causing the entire method to be * aborted. */ public static final int SC_METHOD_FAILURE = 420; /** * Status code (423) indicating the destination resource of a * method is locked, and either the request did not contain a * valid Lock-Info header, or the Lock-Info header identifies * a lock held by another principal. */ public static final int SC_LOCKED = 423; // ------------------------------------------------------------ Initializer static { // HTTP 1.0 status Code addStatusCodeMap(SC_OK, "OK"); addStatusCodeMap(SC_CREATED, "Created"); addStatusCodeMap(SC_ACCEPTED, "Accepted"); addStatusCodeMap(SC_NO_CONTENT, "No Content"); addStatusCodeMap(SC_MOVED_PERMANENTLY, "Moved Permanently"); addStatusCodeMap(SC_MOVED_TEMPORARILY, "Moved Temporarily"); addStatusCodeMap(SC_NOT_MODIFIED, "Not Modified"); addStatusCodeMap(SC_BAD_REQUEST, "Bad Request"); addStatusCodeMap(SC_UNAUTHORIZED, "Unauthorized"); addStatusCodeMap(SC_FORBIDDEN, "Forbidden"); addStatusCodeMap(SC_NOT_FOUND, "Not Found"); addStatusCodeMap(SC_INTERNAL_SERVER_ERROR, "Internal Server Error"); addStatusCodeMap(SC_NOT_IMPLEMENTED, "Not Implemented"); addStatusCodeMap(SC_BAD_GATEWAY, "Bad Gateway"); addStatusCodeMap(SC_SERVICE_UNAVAILABLE, "Service Unavailable"); addStatusCodeMap(SC_CONTINUE, "Continue"); addStatusCodeMap(SC_METHOD_NOT_ALLOWED, "Method Not Allowed"); addStatusCodeMap(SC_CONFLICT, "Conflict"); addStatusCodeMap(SC_PRECONDITION_FAILED, "Precondition Failed"); addStatusCodeMap(SC_REQUEST_TOO_LONG, "Request Too Long"); addStatusCodeMap(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); // WebDav Status Codes addStatusCodeMap(SC_MULTI_STATUS, "Multi-Status"); addStatusCodeMap(SC_UNPROCESSABLE_ENTITY, "Unprocessable Entity"); addStatusCodeMap(SC_INSUFFICIENT_SPACE_ON_RESOURCE, "Insufficient Space On Resource"); addStatusCodeMap(SC_METHOD_FAILURE, "Method Failure"); addStatusCodeMap(SC_LOCKED, "Locked"); } // --------------------------------------------------------- Public Methods /** * Returns the HTTP status text for the HTTP or WebDav status code * specified by looking it up in the static mapping. This is a * static function. * * @param nHttpStatusCode [IN] HTTP or WebDAV status code * @return A string with a short descriptive phrase for the * HTTP status code (e.g., "OK"). */ public static String getStatusText(int nHttpStatusCode) { Integer intKey = Integer.valueOf(nHttpStatusCode); if (!mapStatusCodes.containsKey(intKey)) { return ""; } else { return mapStatusCodes.get(intKey); } } // -------------------------------------------------------- Private Methods /** * Adds a new status code -> status text mapping. This is a static * method because the mapping is a static variable. * * @param nKey [IN] HTTP or WebDAV status code * @param strVal [IN] HTTP status text */ private static void addStatusCodeMap(int nKey, String strVal) { mapStatusCodes.put(Integer.valueOf(nKey), strVal); } }
55,108
Bug 55108 Wasted work in "AbstractReplicatedMap.excludeFromSet"
null
resolved fixed
4979721
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-18T07:32:42Z
2013-06-17T23:00:00Z
java/org/apache/catalina/tribes/tipis/AbstractReplicatedMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.tribes.tipis; import java.io.IOException; import java.io.Serializable; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.apache.catalina.tribes.Channel; import org.apache.catalina.tribes.ChannelException; import org.apache.catalina.tribes.ChannelException.FaultyMember; import org.apache.catalina.tribes.ChannelListener; import org.apache.catalina.tribes.Heartbeat; import org.apache.catalina.tribes.Member; import org.apache.catalina.tribes.MembershipListener; import org.apache.catalina.tribes.group.Response; import org.apache.catalina.tribes.group.RpcCallback; import org.apache.catalina.tribes.group.RpcChannel; import org.apache.catalina.tribes.io.XByteBuffer; import org.apache.catalina.tribes.util.Arrays; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * * @author Filip Hanik * @version 1.0 */ public abstract class AbstractReplicatedMap<K,V> implements Map<K,V>, Serializable, RpcCallback, ChannelListener, MembershipListener, Heartbeat { private static final long serialVersionUID = 1L; private static final Log log = LogFactory.getLog(AbstractReplicatedMap.class); /** * The default initial capacity - MUST be a power of two. */ public static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The load factor used when none specified in constructor. **/ public static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * Used to identify the map */ private static final Charset CHARSET_ISO_8859_1 = Charset.forName("ISO-8859-1"); //------------------------------------------------------------------------------ // INSTANCE VARIABLES //------------------------------------------------------------------------------ private final ConcurrentHashMap<K, MapEntry<K,V>> innerMap; protected abstract int getStateMessageType(); /** * Timeout for RPC messages, how long we will wait for a reply */ protected transient long rpcTimeout = 5000; /** * Reference to the channel for sending messages */ protected transient Channel channel; /** * The RpcChannel to send RPC messages through */ protected transient RpcChannel rpcChannel; /** * The Map context name makes this map unique, this * allows us to have more than one map shared * through one channel */ protected transient byte[] mapContextName; /** * Has the state been transferred */ protected transient boolean stateTransferred = false; /** * Simple lock object for transfers */ protected final transient Object stateMutex = new Object(); /** * A list of members in our map */ protected final transient HashMap<Member, Long> mapMembers = new HashMap<>(); /** * Our default send options */ protected transient int channelSendOptions = Channel.SEND_OPTIONS_DEFAULT; /** * The owner of this map, ala a SessionManager for example */ protected transient MapOwner mapOwner; /** * External class loaders if serialization and deserialization is to be performed successfully. */ protected transient ClassLoader[] externalLoaders; /** * The node we are currently backing up data to, this index will rotate * on a round robin basis */ protected transient int currentNode = 0; /** * Since the map keeps internal membership * this is the timeout for a ping message to be responded to * If a remote map doesn't respond within this timeframe, * its considered dead. */ protected transient long accessTimeout = 5000; /** * Readable string of the mapContextName value */ protected transient String mapname = ""; //------------------------------------------------------------------------------ // map owner interface //------------------------------------------------------------------------------ public static interface MapOwner { public void objectMadePrimary(Object key, Object value); } //------------------------------------------------------------------------------ // CONSTRUCTORS //------------------------------------------------------------------------------ /** * Creates a new map * @param channel The channel to use for communication * @param timeout long - timeout for RPC messags * @param mapContextName String - unique name for this map, to allow multiple maps per channel * @param initialCapacity int - the size of this map, see HashMap * @param loadFactor float - load factor, see HashMap * @param cls - a list of classloaders to be used for deserialization of objects. */ public AbstractReplicatedMap(MapOwner owner, Channel channel, long timeout, String mapContextName, int initialCapacity, float loadFactor, int channelSendOptions, ClassLoader[] cls) { innerMap = new ConcurrentHashMap<>(initialCapacity, loadFactor, 15); init(owner, channel, mapContextName, timeout, channelSendOptions, cls); } /** * Helper methods, wraps a single member in an array * @param m Member * @return Member[] */ protected Member[] wrap(Member m) { if ( m == null ) return new Member[0]; else return new Member[] {m}; } /** * Initializes the map by creating the RPC channel, registering itself as a channel listener * This method is also responsible for initiating the state transfer * @param owner Object * @param channel Channel * @param mapContextName String * @param timeout long * @param channelSendOptions int * @param cls ClassLoader[] */ protected void init(MapOwner owner, Channel channel, String mapContextName, long timeout, int channelSendOptions,ClassLoader[] cls) { log.info("Initializing AbstractReplicatedMap with context name:"+mapContextName); this.mapOwner = owner; this.externalLoaders = cls; this.channelSendOptions = channelSendOptions; this.channel = channel; this.rpcTimeout = timeout; this.mapname = mapContextName; //unique context is more efficient if it is stored as bytes this.mapContextName = mapContextName.getBytes(CHARSET_ISO_8859_1); if ( log.isTraceEnabled() ) log.trace("Created Lazy Map with name:"+mapContextName+", bytes:"+Arrays.toString(this.mapContextName)); //create an rpc channel and add the map as a listener this.rpcChannel = new RpcChannel(this.mapContextName, channel, this); //add this map as a message listener this.channel.addChannelListener(this); //listen for membership notifications this.channel.addMembershipListener(this); try { //broadcast our map, this just notifies other members of our existence broadcast(MapMessage.MSG_INIT, true); //transfer state from another map transferState(); //state is transferred, we are ready for messaging broadcast(MapMessage.MSG_START, true); } catch (ChannelException x) { log.warn("Unable to send map start message."); // remove listener from channel this.rpcChannel.breakdown(); this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); throw new RuntimeException("Unable to start replicated map.",x); } } /** * Sends a ping out to all the members in the cluster, not just map members * that this map is alive. * @param timeout long * @throws ChannelException */ protected void ping(long timeout) throws ChannelException { //send out a map membership message, only wait for the first reply MapMessage msg = new MapMessage(this.mapContextName, MapMessage.MSG_INIT, false, null, null, null, channel.getLocalMember(false), null); if ( channel.getMembers().length > 0 ) { try { //send a ping, wait for all nodes to reply Response[] resp = rpcChannel.send(channel.getMembers(), msg, RpcChannel.ALL_REPLY, (channelSendOptions), (int) accessTimeout); for (int i = 0; i < resp.length; i++) { memberAlive(resp[i].getSource()); } } catch (ChannelException ce) { // Handle known failed members FaultyMember[] faultyMembers = ce.getFaultyMembers(); for (FaultyMember faultyMember : faultyMembers) { memberDisappeared(faultyMember.getMember()); } } } //update our map of members, expire some if we didn't receive a ping back synchronized (mapMembers) { Iterator<Map.Entry<Member, Long>> it = mapMembers.entrySet().iterator(); long now = System.currentTimeMillis(); while ( it.hasNext() ) { Map.Entry<Member,Long> entry = it.next(); long access = entry.getValue().longValue(); if ( (now - access) > timeout ) { it.remove(); memberDisappeared(entry.getKey()); } } }//synch } /** * We have received a member alive notification * @param member Member */ protected void memberAlive(Member member) { synchronized (mapMembers) { if (!mapMembers.containsKey(member)) { mapMemberAdded(member); } //end if mapMembers.put(member, new Long(System.currentTimeMillis())); } } /** * Helper method to broadcast a message to all members in a channel * @param msgtype int * @param rpc boolean * @throws ChannelException */ protected void broadcast(int msgtype, boolean rpc) throws ChannelException { Member[] members = channel.getMembers(); // No destination. if (members.length == 0 ) return; //send out a map membership message, only wait for the first reply MapMessage msg = new MapMessage(this.mapContextName, msgtype, false, null, null, null, channel.getLocalMember(false), null); if ( rpc) { Response[] resp = rpcChannel.send(members, msg, RpcChannel.FIRST_REPLY, (channelSendOptions), rpcTimeout); if (resp.length > 0) { for (int i = 0; i < resp.length; i++) { mapMemberAdded(resp[i].getSource()); messageReceived(resp[i].getMessage(), resp[i].getSource()); } } else { log.warn("broadcast received 0 replies, probably a timeout."); } } else { channel.send(channel.getMembers(),msg,channelSendOptions); } } public void breakdown() { finalize(); } @Override public void finalize() { try {broadcast(MapMessage.MSG_STOP,false); }catch ( Exception ignore){} //cleanup if (this.rpcChannel != null) { this.rpcChannel.breakdown(); } if (this.channel != null) { this.channel.removeChannelListener(this); this.channel.removeMembershipListener(this); } this.rpcChannel = null; this.channel = null; this.mapMembers.clear(); innerMap.clear(); this.stateTransferred = false; this.externalLoaders = null; } @Override public int hashCode() { return Arrays.hashCode(this.mapContextName); } @Override public boolean equals(Object o) { if ( !(o instanceof AbstractReplicatedMap)) return false; if ( !(o.getClass().equals(this.getClass())) ) return false; @SuppressWarnings("unchecked") AbstractReplicatedMap<K,V> other = (AbstractReplicatedMap<K,V>)o; return Arrays.equals(mapContextName,other.mapContextName); } //------------------------------------------------------------------------------ // GROUP COM INTERFACES //------------------------------------------------------------------------------ public Member[] getMapMembers(HashMap<Member, Long> members) { synchronized (members) { Member[] result = new Member[members.size()]; members.keySet().toArray(result); return result; } } public Member[] getMapMembers() { return getMapMembers(this.mapMembers); } public Member[] getMapMembersExcl(Member[] exclude) { synchronized (mapMembers) { HashMap<Member, Long> list = (HashMap<Member, Long>)mapMembers.clone(); for (int i=0; i<exclude.length;i++) list.remove(exclude[i]); return getMapMembers(list); } } /** * Replicates any changes to the object since the last time * The object has to be primary, ie, if the object is a proxy or a backup, it will not be replicated<br> * @param complete - if set to true, the object is replicated to its backup * if set to false, only objects that implement ReplicatedMapEntry and the isDirty() returns true will * be replicated */ public void replicate(Object key, boolean complete) { if ( log.isTraceEnabled() ) log.trace("Replicate invoked on key:"+key); MapEntry<K,V> entry = innerMap.get(key); if ( entry == null ) return; if ( !entry.isSerializable() ) return; if (entry.isPrimary() && entry.getBackupNodes()!= null && entry.getBackupNodes().length > 0) { //check to see if we need to replicate this object isDirty()||complete || isAccessReplicate() ReplicatedMapEntry rentry = null; if (entry.getValue() instanceof ReplicatedMapEntry) rentry = (ReplicatedMapEntry)entry.getValue(); boolean isDirty = rentry != null && rentry.isDirty(); boolean isAccess = rentry != null && rentry.isAccessReplicate(); boolean repl = complete || isDirty || isAccess; if (!repl) { if ( log.isTraceEnabled() ) log.trace("Not replicating:"+key+", no change made"); return; } //check to see if the message is diffable MapMessage msg = null; if (rentry != null && rentry.isDiffable() && (isDirty || complete)) { try { rentry.lock(); //construct a diff message msg = new MapMessage(mapContextName, MapMessage.MSG_BACKUP, true, (Serializable) entry.getKey(), null, rentry.getDiff(), entry.getPrimary(), entry.getBackupNodes()); rentry.resetDiff(); } catch (IOException x) { log.error("Unable to diff object. Will replicate the entire object instead.", x); } finally { rentry.unlock(); } } if (msg == null && complete) { //construct a complete msg = new MapMessage(mapContextName, MapMessage.MSG_BACKUP, false, (Serializable) entry.getKey(), (Serializable) entry.getValue(), null, entry.getPrimary(),entry.getBackupNodes()); } if (msg == null) { //construct a access message msg = new MapMessage(mapContextName, MapMessage.MSG_ACCESS, false, (Serializable) entry.getKey(), null, null, entry.getPrimary(), entry.getBackupNodes()); } try { if ( channel!=null && entry.getBackupNodes()!= null && entry.getBackupNodes().length > 0 ) { if (rentry != null) rentry.setLastTimeReplicated(System.currentTimeMillis()); channel.send(entry.getBackupNodes(), msg, channelSendOptions); } } catch (ChannelException x) { log.error("Unable to replicate data.", x); } } //end if } /** * This can be invoked by a periodic thread to replicate out any changes. * For maps that don't store objects that implement ReplicatedMapEntry, this * method should be used infrequently to avoid large amounts of data transfer * @param complete boolean */ public void replicate(boolean complete) { Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<?,?> e = i.next(); replicate(e.getKey(), complete); } //while } public void transferState() { try { Member[] members = getMapMembers(); Member backup = members.length > 0 ? (Member) members[0] : null; if (backup != null) { MapMessage msg = new MapMessage(mapContextName, getStateMessageType(), false, null, null, null, null, null); Response[] resp = rpcChannel.send(new Member[] {backup}, msg, RpcChannel.FIRST_REPLY, channelSendOptions, rpcTimeout); if (resp.length > 0) { synchronized (stateMutex) { msg = (MapMessage) resp[0].getMessage(); msg.deserialize(getExternalLoaders()); ArrayList<?> list = (ArrayList<?>) msg.getValue(); for (int i = 0; i < list.size(); i++) { messageReceived( (Serializable) list.get(i), resp[0].getSource()); } //for } } else { log.warn("Transfer state, 0 replies, probably a timeout."); } } } catch (ChannelException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); } catch (IOException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); } catch (ClassNotFoundException x) { log.error("Unable to transfer LazyReplicatedMap state.", x); } stateTransferred = true; } /** * TODO implement state transfer * @param msg Serializable * @return Serializable - null if no reply should be sent */ @Override public Serializable replyRequest(Serializable msg, final Member sender) { if (! (msg instanceof MapMessage))return null; MapMessage mapmsg = (MapMessage) msg; //map init request if (mapmsg.getMsgType() == MapMessage.MSG_INIT) { mapmsg.setPrimary(channel.getLocalMember(false)); return mapmsg; } //map start request if (mapmsg.getMsgType() == MapMessage.MSG_START) { mapmsg.setPrimary(channel.getLocalMember(false)); mapMemberAdded(sender); return mapmsg; } //backup request if (mapmsg.getMsgType() == MapMessage.MSG_RETRIEVE_BACKUP) { MapEntry<K,V> entry = innerMap.get(mapmsg.getKey()); if (entry == null || (!entry.isSerializable()) )return null; mapmsg.setValue( (Serializable) entry.getValue()); return mapmsg; } //state transfer request if (mapmsg.getMsgType() == MapMessage.MSG_STATE || mapmsg.getMsgType() == MapMessage.MSG_STATE_COPY) { synchronized (stateMutex) { //make sure we dont do two things at the same time ArrayList<MapMessage> list = new ArrayList<>(); Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<?,?> e = i.next(); MapEntry<K,V> entry = innerMap.get(e.getKey()); if ( entry != null && entry.isSerializable() ) { boolean copy = (mapmsg.getMsgType() == MapMessage.MSG_STATE_COPY); MapMessage me = new MapMessage(mapContextName, copy?MapMessage.MSG_COPY:MapMessage.MSG_PROXY, false, (Serializable) entry.getKey(), copy?(Serializable) entry.getValue():null, null, entry.getPrimary(),entry.getBackupNodes()); list.add(me); } } mapmsg.setValue(list); return mapmsg; } //synchronized } return null; } /** * If the reply has already been sent to the requesting thread, * the rpc callback can handle any data that comes in after the fact. * @param msg Serializable * @param sender Member */ @Override public void leftOver(Serializable msg, Member sender) { //left over membership messages if (! (msg instanceof MapMessage))return; MapMessage mapmsg = (MapMessage) msg; try { mapmsg.deserialize(getExternalLoaders()); if (mapmsg.getMsgType() == MapMessage.MSG_START) { mapMemberAdded(mapmsg.getPrimary()); } else if (mapmsg.getMsgType() == MapMessage.MSG_INIT) { memberAlive(mapmsg.getPrimary()); } } catch (IOException x ) { log.error("Unable to deserialize MapMessage.",x); } catch (ClassNotFoundException x ) { log.error("Unable to deserialize MapMessage.",x); } } @SuppressWarnings("unchecked") @Override public void messageReceived(Serializable msg, Member sender) { if (! (msg instanceof MapMessage)) return; MapMessage mapmsg = (MapMessage) msg; if ( log.isTraceEnabled() ) { log.trace("Map["+mapname+"] received message:"+mapmsg); } try { mapmsg.deserialize(getExternalLoaders()); } catch (IOException x) { log.error("Unable to deserialize MapMessage.", x); return; } catch (ClassNotFoundException x) { log.error("Unable to deserialize MapMessage.", x); return; } if ( log.isTraceEnabled() ) log.trace("Map message received from:"+sender.getName()+" msg:"+mapmsg); if (mapmsg.getMsgType() == MapMessage.MSG_START) { mapMemberAdded(mapmsg.getPrimary()); } if (mapmsg.getMsgType() == MapMessage.MSG_STOP) { memberDisappeared(mapmsg.getPrimary()); } if (mapmsg.getMsgType() == MapMessage.MSG_PROXY) { MapEntry<K,V> entry = innerMap.get(mapmsg.getKey()); if ( entry==null ) { entry = new MapEntry<>((K) mapmsg.getKey(), (V) mapmsg.getValue()); MapEntry<K,V> old = innerMap.putIfAbsent(entry.getKey(), entry); if (old != null) { entry = old; } } entry.setProxy(true); entry.setBackup(false); entry.setBackupNodes(mapmsg.getBackupNodes()); entry.setPrimary(mapmsg.getPrimary()); } if (mapmsg.getMsgType() == MapMessage.MSG_REMOVE) { innerMap.remove(mapmsg.getKey()); } if (mapmsg.getMsgType() == MapMessage.MSG_BACKUP || mapmsg.getMsgType() == MapMessage.MSG_COPY) { MapEntry<K,V> entry = innerMap.get(mapmsg.getKey()); if (entry == null) { entry = new MapEntry<>((K) mapmsg.getKey(), (V) mapmsg.getValue()); entry.setBackup(mapmsg.getMsgType() == MapMessage.MSG_BACKUP); entry.setProxy(false); entry.setBackupNodes(mapmsg.getBackupNodes()); entry.setPrimary(mapmsg.getPrimary()); if (mapmsg.getValue()!=null && mapmsg.getValue() instanceof ReplicatedMapEntry ) { ((ReplicatedMapEntry)mapmsg.getValue()).setOwner(getMapOwner()); } } else { entry.setBackup(mapmsg.getMsgType() == MapMessage.MSG_BACKUP); entry.setProxy(false); entry.setBackupNodes(mapmsg.getBackupNodes()); entry.setPrimary(mapmsg.getPrimary()); if (entry.getValue() instanceof ReplicatedMapEntry) { ReplicatedMapEntry diff = (ReplicatedMapEntry) entry.getValue(); if (mapmsg.isDiff()) { try { diff.lock(); diff.applyDiff(mapmsg.getDiffValue(), 0, mapmsg.getDiffValue().length); } catch (Exception x) { log.error("Unable to apply diff to key:" + entry.getKey(), x); } finally { diff.unlock(); } } else { if ( mapmsg.getValue()!=null ) entry.setValue((V) mapmsg.getValue()); ((ReplicatedMapEntry)entry.getValue()).setOwner(getMapOwner()); } //end if } else if (mapmsg.getValue() instanceof ReplicatedMapEntry) { ReplicatedMapEntry re = (ReplicatedMapEntry)mapmsg.getValue(); re.setOwner(getMapOwner()); entry.setValue((V) re); } else { if ( mapmsg.getValue()!=null ) entry.setValue((V) mapmsg.getValue()); } //end if } //end if innerMap.put(entry.getKey(), entry); } //end if if (mapmsg.getMsgType() == MapMessage.MSG_ACCESS) { MapEntry<K, V> entry = innerMap.get(mapmsg.getKey()); if (entry != null) { entry.setBackupNodes(mapmsg.getBackupNodes()); entry.setPrimary(mapmsg.getPrimary()); if (entry.getValue() instanceof ReplicatedMapEntry) { ((ReplicatedMapEntry) entry.getValue()).accessEntry(); } } } } @Override public boolean accept(Serializable msg, Member sender) { boolean result = false; if (msg instanceof MapMessage) { if ( log.isTraceEnabled() ) log.trace("Map["+mapname+"] accepting...."+msg); result = Arrays.equals(mapContextName, ( (MapMessage) msg).getMapId()); if ( log.isTraceEnabled() ) log.trace("Msg["+mapname+"] accepted["+result+"]...."+msg); } return result; } public void mapMemberAdded(Member member) { if ( member.equals(getChannel().getLocalMember(false)) ) return; boolean memberAdded = false; //select a backup node if we don't have one synchronized (mapMembers) { if (!mapMembers.containsKey(member) ) { mapMembers.put(member, new Long(System.currentTimeMillis())); memberAdded = true; } } if ( memberAdded ) { synchronized (stateMutex) { Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<K,MapEntry<K,V>> e = i.next(); MapEntry<K,V> entry = innerMap.get(e.getKey()); if ( entry == null ) continue; if (entry.isPrimary() && (entry.getBackupNodes() == null || entry.getBackupNodes().length == 0)) { try { Member[] backup = publishEntryInfo(entry.getKey(), entry.getValue()); entry.setBackupNodes(backup); entry.setPrimary(channel.getLocalMember(false)); } catch (ChannelException x) { log.error("Unable to select backup node.", x); } //catch } //end if } //while } //synchronized }//end if } public boolean inSet(Member m, Member[] set) { if ( set == null ) return false; boolean result = false; for (int i=0; i<set.length && (!result); i++ ) if ( m.equals(set[i]) ) result = true; return result; } public Member[] excludeFromSet(Member[] mbrs, Member[] set) { ArrayList<Member> result = new ArrayList<>(); for (int i=0; i<set.length; i++ ) { boolean include = true; for (int j=0; j<mbrs.length; j++ ) if ( mbrs[j].equals(set[i]) ) include = false; if ( include ) result.add(set[i]); } return result.toArray(new Member[result.size()]); } @Override public void memberAdded(Member member) { //do nothing } @Override public void memberDisappeared(Member member) { boolean removed = false; synchronized (mapMembers) { removed = (mapMembers.remove(member) != null ); if (!removed) { if (log.isDebugEnabled()) log.debug("Member["+member+"] disappeared, but was not present in the map."); return; //the member was not part of our map. } } Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<K,MapEntry<K,V>> e = i.next(); MapEntry<K,V> entry = innerMap.get(e.getKey()); if (entry==null) continue; if (entry.isPrimary() && inSet(member,entry.getBackupNodes())) { if (log.isDebugEnabled()) log.debug("[1] Primary choosing a new backup"); try { Member[] backup = publishEntryInfo(entry.getKey(), entry.getValue()); entry.setBackupNodes(backup); entry.setPrimary(channel.getLocalMember(false)); } catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); } } else if (member.equals(entry.getPrimary())) { if (log.isDebugEnabled()) log.debug("[2] Primary disappeared"); entry.setPrimary(null); } //end if if ( entry.isProxy() && entry.getPrimary() == null && entry.getBackupNodes()!=null && entry.getBackupNodes().length == 1 && entry.getBackupNodes()[0].equals(member) ) { //remove proxies that have no backup nor primaries if (log.isDebugEnabled()) log.debug("[3] Removing orphaned proxy"); i.remove(); } else if ( entry.getPrimary() == null && entry.isBackup() && entry.getBackupNodes()!=null && entry.getBackupNodes().length == 1 && entry.getBackupNodes()[0].equals(channel.getLocalMember(false)) ) { try { if (log.isDebugEnabled()) log.debug("[4] Backup becoming primary"); entry.setPrimary(channel.getLocalMember(false)); entry.setBackup(false); entry.setProxy(false); Member[] backup = publishEntryInfo(entry.getKey(), entry.getValue()); entry.setBackupNodes(backup); if ( mapOwner!=null ) mapOwner.objectMadePrimary(entry.getKey(),entry.getValue()); } catch (ChannelException x) { log.error("Unable to relocate[" + entry.getKey() + "] to a new backup node", x); } } } //while } public int getNextBackupIndex() { int size = mapMembers.size(); if (mapMembers.size() == 0)return -1; int node = currentNode++; if (node >= size) { node = 0; currentNode = 0; } return node; } public Member getNextBackupNode() { Member[] members = getMapMembers(); int node = getNextBackupIndex(); if ( members.length == 0 || node==-1) return null; if ( node >= members.length ) node = 0; return members[node]; } protected abstract Member[] publishEntryInfo(Object key, Object value) throws ChannelException; @Override public void heartbeat() { try { ping(accessTimeout); }catch ( Exception x ) { log.error("Unable to send AbstractReplicatedMap.ping message",x); } } //------------------------------------------------------------------------------ // METHODS TO OVERRIDE //------------------------------------------------------------------------------ /** * Removes an object from this map, it will also remove it from * * @param key Object * @return Object */ @Override public V remove(Object key) { return remove(key,true); } public V remove(Object key, boolean notify) { MapEntry<K,V> entry = innerMap.remove(key); try { if (getMapMembers().length > 0 && notify) { MapMessage msg = new MapMessage(getMapContextName(), MapMessage.MSG_REMOVE, false, (Serializable) key, null, null, null,null); getChannel().send(getMapMembers(), msg, getChannelSendOptions()); } } catch ( ChannelException x ) { log.error("Unable to replicate out data for a LazyReplicatedMap.remove operation",x); } return entry!=null?entry.getValue():null; } public MapEntry<K,V> getInternal(Object key) { return innerMap.get(key); } @SuppressWarnings("unchecked") @Override public V get(Object key) { MapEntry<K,V> entry = innerMap.get(key); if (log.isTraceEnabled()) log.trace("Requesting id:"+key+" entry:"+entry); if ( entry == null ) return null; if ( !entry.isPrimary() ) { //if the message is not primary, we need to retrieve the latest value try { Member[] backup = null; MapMessage msg = null; if ( !entry.isBackup() ) { //make sure we don't retrieve from ourselves msg = new MapMessage(getMapContextName(), MapMessage.MSG_RETRIEVE_BACKUP, false, (Serializable) key, null, null, null,null); Response[] resp = getRpcChannel().send(entry.getBackupNodes(),msg, RpcChannel.FIRST_REPLY, Channel.SEND_OPTIONS_DEFAULT, getRpcTimeout()); if (resp == null || resp.length == 0) { //no responses log.warn("Unable to retrieve remote object for key:" + key); return null; } msg = (MapMessage) resp[0].getMessage(); msg.deserialize(getExternalLoaders()); backup = entry.getBackupNodes(); if ( entry.getValue() instanceof ReplicatedMapEntry ) { ReplicatedMapEntry val = (ReplicatedMapEntry)entry.getValue(); val.setOwner(getMapOwner()); } if ( msg.getValue()!=null ) entry.setValue((V) msg.getValue()); } if (entry.isBackup()) { //select a new backup node backup = publishEntryInfo(key, entry.getValue()); } else if ( entry.isProxy() ) { //invalidate the previous primary msg = new MapMessage(getMapContextName(),MapMessage.MSG_PROXY,false,(Serializable)key,null,null,channel.getLocalMember(false),backup); Member[] dest = getMapMembersExcl(backup); if ( dest!=null && dest.length >0) { getChannel().send(dest, msg, getChannelSendOptions()); } if ( entry.getValue() != null && entry.getValue() instanceof ReplicatedMapEntry ) { ReplicatedMapEntry val = (ReplicatedMapEntry)entry.getValue(); val.setOwner(getMapOwner()); } } entry.setPrimary(channel.getLocalMember(false)); entry.setBackupNodes(backup); entry.setBackup(false); entry.setProxy(false); if ( getMapOwner()!=null ) getMapOwner().objectMadePrimary(key, entry.getValue()); } catch (Exception x) { log.error("Unable to replicate out data for a LazyReplicatedMap.get operation", x); return null; } } if (log.isTraceEnabled()) log.trace("Requesting id:"+key+" result:"+entry.getValue()); return entry.getValue(); } protected void printMap(String header) { try { System.out.println("\nDEBUG MAP:"+header); System.out.println("Map[" + new String(mapContextName, CHARSET_ISO_8859_1) + ", Map Size:" + innerMap.size()); Member[] mbrs = getMapMembers(); for ( int i=0; i<mbrs.length;i++ ) { System.out.println("Mbr["+(i+1)+"="+mbrs[i].getName()); } Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); int cnt = 0; while (i.hasNext()) { Map.Entry<?,?> e = i.next(); System.out.println( (++cnt) + ". " + innerMap.get(e.getKey())); } System.out.println("EndMap]\n\n"); }catch ( Exception ignore) { ignore.printStackTrace(); } } /** * Returns true if the key has an entry in the map. * The entry can be a proxy or a backup entry, invoking <code>get(key)</code> * will make this entry primary for the group * @param key Object * @return boolean */ @Override public boolean containsKey(Object key) { return innerMap.containsKey(key); } @Override public V put(K key, V value) { return put(key, value, true); } public V put(K key, V value, boolean notify) { MapEntry<K,V> entry = new MapEntry<>(key, value); entry.setBackup(false); entry.setProxy(false); entry.setPrimary(channel.getLocalMember(false)); V old = null; //make sure that any old values get removed if ( containsKey(key) ) old = remove(key); try { if ( notify ) { Member[] backup = publishEntryInfo(key, value); entry.setBackupNodes(backup); } } catch (ChannelException x) { log.error("Unable to replicate out data for a LazyReplicatedMap.put operation", x); } innerMap.put(key,entry); return old; } /** * Copies all values from one map to this instance * @param m Map */ @Override public void putAll(Map<? extends K, ? extends V> m) { Iterator<?> i = m.entrySet().iterator(); while ( i.hasNext() ) { Map.Entry<K,V> entry = (Map.Entry<K,V>) i.next(); put(entry.getKey(),entry.getValue()); } } @Override public void clear() { clear(true); } public void clear(boolean notify) { if ( notify ) { //only delete active keys Iterator<K> keys = keySet().iterator(); while (keys.hasNext()) remove(keys.next()); } else { innerMap.clear(); } } @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while (i.hasNext()) { Map.Entry<K,MapEntry<K,V>> e = i.next(); MapEntry<K,V> entry = innerMap.get(e.getKey()); if (entry!=null && entry.isActive() && value.equals(entry.getValue())) return true; } return false; } @Override public Object clone() { throw new UnsupportedOperationException("This operation is not valid on a replicated map"); } /** * Returns the entire contents of the map * Map.Entry.getValue() will return a LazyReplicatedMap.MapEntry object containing all the information * about the object. * @return Set */ public Set<Map.Entry<K,MapEntry<K,V>>> entrySetFull() { return innerMap.entrySet(); } public Set<K> keySetFull() { return innerMap.keySet(); } public int sizeFull() { return innerMap.size(); } @Override public Set<Map.Entry<K,V>> entrySet() { LinkedHashSet<Map.Entry<K,V>> set = new LinkedHashSet<>(innerMap.size()); Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while ( i.hasNext() ) { Map.Entry<?,?> e = i.next(); Object key = e.getKey(); MapEntry<K,V> entry = innerMap.get(key); if ( entry != null && entry.isActive() ) { set.add(entry); } } return Collections.unmodifiableSet(set); } @Override public Set<K> keySet() { //todo implement //should only return keys where this is active. LinkedHashSet<K> set = new LinkedHashSet<>(innerMap.size()); Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while ( i.hasNext() ) { Map.Entry<K,MapEntry<K,V>> e = i.next(); K key = e.getKey(); MapEntry<K,V> entry = innerMap.get(key); if ( entry!=null && entry.isActive() ) set.add(key); } return Collections.unmodifiableSet(set); } @Override public int size() { //todo, implement a counter variable instead //only count active members in this node int counter = 0; Iterator<Map.Entry<K,MapEntry<K,V>>> it = innerMap.entrySet().iterator(); while (it!=null && it.hasNext() ) { Map.Entry<?,?> e = it.next(); if ( e != null ) { MapEntry<K,V> entry = innerMap.get(e.getKey()); if (entry!=null && entry.isActive() && entry.getValue() != null) counter++; } } return counter; } @Override public boolean isEmpty() { return size()==0; } @Override public Collection<V> values() { ArrayList<V> values = new ArrayList<>(); Iterator<Map.Entry<K,MapEntry<K,V>>> i = innerMap.entrySet().iterator(); while ( i.hasNext() ) { Map.Entry<K,MapEntry<K,V>> e = i.next(); MapEntry<K,V> entry = innerMap.get(e.getKey()); if (entry!=null && entry.isActive() && entry.getValue()!=null) values.add(entry.getValue()); } return Collections.unmodifiableCollection(values); } //------------------------------------------------------------------------------ // Map Entry class //------------------------------------------------------------------------------ public static class MapEntry<K,V> implements Map.Entry<K,V> { private boolean backup; private boolean proxy; private Member[] backupNodes; private Member primary; private K key; private V value; public MapEntry(K key, V value) { setKey(key); setValue(value); } public boolean isKeySerializable() { return (key == null) || (key instanceof Serializable); } public boolean isValueSerializable() { return (value==null) || (value instanceof Serializable); } public boolean isSerializable() { return isKeySerializable() && isValueSerializable(); } public boolean isBackup() { return backup; } public void setBackup(boolean backup) { this.backup = backup; } public boolean isProxy() { return proxy; } public boolean isPrimary() { return (!proxy && !backup); } public boolean isActive() { return !proxy; } public void setProxy(boolean proxy) { this.proxy = proxy; } public boolean isDiffable() { return (value instanceof ReplicatedMapEntry) && ((ReplicatedMapEntry)value).isDiffable(); } public void setBackupNodes(Member[] nodes) { this.backupNodes = nodes; } public Member[] getBackupNodes() { return backupNodes; } public void setPrimary(Member m) { primary = m; } public Member getPrimary() { return primary; } @Override public V getValue() { return value; } @Override public V setValue(V value) { V old = this.value; this.value = value; return old; } @Override public K getKey() { return key; } public K setKey(K key) { K old = this.key; this.key = key; return old; } @Override public int hashCode() { return key.hashCode(); } @Override public boolean equals(Object o) { return key.equals(o); } /** * apply a diff, or an entire object * @param data byte[] * @param offset int * @param length int * @param diff boolean * @throws IOException * @throws ClassNotFoundException */ public void apply(byte[] data, int offset, int length, boolean diff) throws IOException, ClassNotFoundException { if (isDiffable() && diff) { ReplicatedMapEntry rentry = (ReplicatedMapEntry) value; try { rentry.lock(); rentry.applyDiff(data, offset, length); } finally { rentry.unlock(); } } else if (length == 0) { value = null; proxy = true; } else { value = (V) XByteBuffer.deserialize(data, offset, length); } } @Override public String toString() { StringBuilder buf = new StringBuilder("MapEntry[key:"); buf.append(getKey()).append("; "); buf.append("value:").append(getValue()).append("; "); buf.append("primary:").append(isPrimary()).append("; "); buf.append("backup:").append(isBackup()).append("; "); buf.append("proxy:").append(isProxy()).append(";]"); return buf.toString(); } } //------------------------------------------------------------------------------ // map message to send to and from other maps //------------------------------------------------------------------------------ public static class MapMessage implements Serializable { private static final long serialVersionUID = 1L; public static final int MSG_BACKUP = 1; public static final int MSG_RETRIEVE_BACKUP = 2; public static final int MSG_PROXY = 3; public static final int MSG_REMOVE = 4; public static final int MSG_STATE = 5; public static final int MSG_START = 6; public static final int MSG_STOP = 7; public static final int MSG_INIT = 8; public static final int MSG_COPY = 9; public static final int MSG_STATE_COPY = 10; public static final int MSG_ACCESS = 11; private final byte[] mapId; private final int msgtype; private final boolean diff; private transient Serializable key; private transient Serializable value; private byte[] valuedata; private byte[] keydata; private final byte[] diffvalue; private final Member[] nodes; private Member primary; @Override public String toString() { StringBuilder buf = new StringBuilder("MapMessage[context="); buf.append(new String(mapId)); buf.append("; type="); buf.append(getTypeDesc()); buf.append("; key="); buf.append(key); buf.append("; value="); buf.append(value); return buf.toString(); } public String getTypeDesc() { switch (msgtype) { case MSG_BACKUP: return "MSG_BACKUP"; case MSG_RETRIEVE_BACKUP: return "MSG_RETRIEVE_BACKUP"; case MSG_PROXY: return "MSG_PROXY"; case MSG_REMOVE: return "MSG_REMOVE"; case MSG_STATE: return "MSG_STATE"; case MSG_START: return "MSG_START"; case MSG_STOP: return "MSG_STOP"; case MSG_INIT: return "MSG_INIT"; case MSG_STATE_COPY: return "MSG_STATE_COPY"; case MSG_COPY: return "MSG_COPY"; case MSG_ACCESS: return "MSG_ACCESS"; default : return "UNKNOWN"; } } public MapMessage(byte[] mapId,int msgtype, boolean diff, Serializable key, Serializable value, byte[] diffvalue, Member primary, Member[] nodes) { this.mapId = mapId; this.msgtype = msgtype; this.diff = diff; this.key = key; this.value = value; this.diffvalue = diffvalue; this.nodes = nodes; this.primary = primary; setValue(value); setKey(key); } public void deserialize(ClassLoader[] cls) throws IOException, ClassNotFoundException { key(cls); value(cls); } public int getMsgType() { return msgtype; } public boolean isDiff() { return diff; } public Serializable getKey() { try { return key(null); } catch ( Exception x ) { log.error("Deserialization error of the MapMessage.key",x); return null; } } public Serializable key(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( key!=null ) return key; if ( keydata == null || keydata.length == 0 ) return null; key = XByteBuffer.deserialize(keydata,0,keydata.length,cls); keydata = null; return key; } public byte[] getKeyData() { return keydata; } public Serializable getValue() { try { return value(null); } catch ( Exception x ) { log.error("Deserialization error of the MapMessage.value",x); return null; } } public Serializable value(ClassLoader[] cls) throws IOException, ClassNotFoundException { if ( value!=null ) return value; if ( valuedata == null || valuedata.length == 0 ) return null; value = XByteBuffer.deserialize(valuedata,0,valuedata.length,cls); valuedata = null; return value; } public byte[] getValueData() { return valuedata; } public byte[] getDiffValue() { return diffvalue; } public Member[] getBackupNodes() { return nodes; } public Member getPrimary() { return primary; } private void setPrimary(Member m) { primary = m; } public byte[] getMapId() { return mapId; } public void setValue(Serializable value) { try { if ( value != null ) valuedata = XByteBuffer.serialize(value); this.value = value; }catch ( IOException x ) { throw new RuntimeException(x); } } public void setKey(Serializable key) { try { if (key != null) keydata = XByteBuffer.serialize(key); this.key = key; } catch (IOException x) { throw new RuntimeException(x); } } /** * shallow clone * @return Object */ @Override public Object clone() { MapMessage msg = new MapMessage(this.mapId, this.msgtype, this.diff, this.key, this.value, this.diffvalue, this.primary, this.nodes); msg.keydata = this.keydata; msg.valuedata = this.valuedata; return msg; } } //MapMessage public Channel getChannel() { return channel; } public byte[] getMapContextName() { return mapContextName; } public RpcChannel getRpcChannel() { return rpcChannel; } public long getRpcTimeout() { return rpcTimeout; } public Object getStateMutex() { return stateMutex; } public boolean isStateTransferred() { return stateTransferred; } public MapOwner getMapOwner() { return mapOwner; } public ClassLoader[] getExternalLoaders() { return externalLoaders; } public int getChannelSendOptions() { return channelSendOptions; } public long getAccessTimeout() { return accessTimeout; } public void setMapOwner(MapOwner mapOwner) { this.mapOwner = mapOwner; } public void setExternalLoaders(ClassLoader[] externalLoaders) { this.externalLoaders = externalLoaders; } public void setChannelSendOptions(int channelSendOptions) { this.channelSendOptions = channelSendOptions; } public void setAccessTimeout(long accessTimeout) { this.accessTimeout = accessTimeout; } }
55,073
Bug 55073 wasted work in ValidateVisitor.isExpression()
null
resolved fixed
3e2ceee
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-18T07:57:32Z
2013-06-07T18:33:20Z
java/org/apache/jasper/compiler/Validator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.FunctionMapper; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.tagext.FunctionInfo; import javax.servlet.jsp.tagext.PageData; import javax.servlet.jsp.tagext.TagAttributeInfo; import javax.servlet.jsp.tagext.TagData; import javax.servlet.jsp.tagext.TagExtraInfo; import javax.servlet.jsp.tagext.TagInfo; import javax.servlet.jsp.tagext.TagLibraryInfo; import javax.servlet.jsp.tagext.ValidationMessage; import org.apache.jasper.JasperException; import org.apache.jasper.el.ELContextImpl; import org.xml.sax.Attributes; /** * Performs validation on the page elements. Attributes are checked for * mandatory presence, entry value validity, and consistency. As a side effect, * some page global value (such as those from page directives) are stored, for * later use. * * @author Kin-man Chung * @author Jan Luehe * @author Shawn Bayern * @author Mark Roth */ class Validator { /** * A visitor to validate and extract page directive info */ private static class DirectiveVisitor extends Node.Visitor { private final PageInfo pageInfo; private final ErrorDispatcher err; private static final JspUtil.ValidAttribute[] pageDirectiveAttrs = { new JspUtil.ValidAttribute("language"), new JspUtil.ValidAttribute("extends"), new JspUtil.ValidAttribute("import"), new JspUtil.ValidAttribute("session"), new JspUtil.ValidAttribute("buffer"), new JspUtil.ValidAttribute("autoFlush"), new JspUtil.ValidAttribute("isThreadSafe"), new JspUtil.ValidAttribute("info"), new JspUtil.ValidAttribute("errorPage"), new JspUtil.ValidAttribute("isErrorPage"), new JspUtil.ValidAttribute("contentType"), new JspUtil.ValidAttribute("pageEncoding"), new JspUtil.ValidAttribute("isELIgnored"), new JspUtil.ValidAttribute("deferredSyntaxAllowedAsLiteral"), new JspUtil.ValidAttribute("trimDirectiveWhitespaces") }; private boolean pageEncodingSeen = false; /* * Constructor */ DirectiveVisitor(Compiler compiler) { this.pageInfo = compiler.getPageInfo(); this.err = compiler.getErrorDispatcher(); } @Override public void visit(Node.IncludeDirective n) throws JasperException { // Since pageDirectiveSeen flag only applies to the Current page // save it here and restore it after the file is included. boolean pageEncodingSeenSave = pageEncodingSeen; pageEncodingSeen = false; visitBody(n); pageEncodingSeen = pageEncodingSeenSave; } @Override public void visit(Node.PageDirective n) throws JasperException { JspUtil.checkAttributes("Page directive", n, pageDirectiveAttrs, err); // JSP.2.10.1 Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, true); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.language", pageInfo.getLanguage(false), value); } } else if ("extends".equals(attr)) { if (pageInfo.getExtends(false) == null) { pageInfo.setExtends(value, n); } else if (!pageInfo.getExtends(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.extends", pageInfo.getExtends(false), value); } } else if ("contentType".equals(attr)) { if (pageInfo.getContentType() == null) { pageInfo.setContentType(value); } else if (!pageInfo.getContentType().equals(value)) { err.jspError(n, "jsp.error.page.conflict.contenttype", pageInfo.getContentType(), value); } } else if ("session".equals(attr)) { if (pageInfo.getSession() == null) { pageInfo.setSession(value, n, err); } else if (!pageInfo.getSession().equals(value)) { err.jspError(n, "jsp.error.page.conflict.session", pageInfo.getSession(), value); } } else if ("buffer".equals(attr)) { if (pageInfo.getBufferValue() == null) { pageInfo.setBufferValue(value, n, err); } else if (!pageInfo.getBufferValue().equals(value)) { err.jspError(n, "jsp.error.page.conflict.buffer", pageInfo.getBufferValue(), value); } } else if ("autoFlush".equals(attr)) { if (pageInfo.getAutoFlush() == null) { pageInfo.setAutoFlush(value, n, err); } else if (!pageInfo.getAutoFlush().equals(value)) { err.jspError(n, "jsp.error.page.conflict.autoflush", pageInfo.getAutoFlush(), value); } } else if ("isThreadSafe".equals(attr)) { if (pageInfo.getIsThreadSafe() == null) { pageInfo.setIsThreadSafe(value, n, err); } else if (!pageInfo.getIsThreadSafe().equals(value)) { err.jspError(n, "jsp.error.page.conflict.isthreadsafe", pageInfo.getIsThreadSafe(), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, true); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("isErrorPage".equals(attr)) { if (pageInfo.getIsErrorPage() == null) { pageInfo.setIsErrorPage(value, n, err); } else if (!pageInfo.getIsErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iserrorpage", pageInfo.getIsErrorPage(), value); } } else if ("errorPage".equals(attr)) { if (pageInfo.getErrorPage() == null) { pageInfo.setErrorPage(value); } else if (!pageInfo.getErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.errorpage", pageInfo.getErrorPage(), value); } } else if ("info".equals(attr)) { if (pageInfo.getInfo() == null) { pageInfo.setInfo(value); } else if (!pageInfo.getInfo().equals(value)) { err.jspError(n, "jsp.error.page.conflict.info", pageInfo.getInfo(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.page.multi.pageencoding"); // 'pageEncoding' can occur at most once per file pageEncodingSeen = true; String actual = comparePageEncodings(value, n); n.getRoot().setPageEncoding(actual); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, true); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.page.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, true); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.page.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Check for bad combinations if (pageInfo.getBuffer() == 0 && !pageInfo.isAutoFlush()) err.jspError(n, "jsp.error.page.badCombo"); // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); } @Override public void visit(Node.TagDirective n) throws JasperException { // Note: Most of the validation is done in TagFileProcessor // when it created a TagInfo object from the // tag file in which the directive appeared. // This method does additional processing to collect page info Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, false); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.tag.conflict.language", pageInfo.getLanguage(false), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, false); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.tag.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.tag.multi.pageencoding"); pageEncodingSeen = true; compareTagEncodings(value, n); n.getRoot().setPageEncoding(value); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, false); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.tag.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, false); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.tag.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); } @Override public void visit(Node.AttributeDirective n) throws JasperException { // Do nothing, since this attribute directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared } @Override public void visit(Node.VariableDirective n) throws JasperException { // Do nothing, since this variable directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared } /* * Compares page encodings specified in various places, and throws * exception in case of page encoding mismatch. * * @param pageDirEnc The value of the pageEncoding attribute of the page * directive @param pageDir The page directive node * * @throws JasperException in case of page encoding mismatch */ private String comparePageEncodings(String thePageDirEnc, Node.PageDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String configEnc = root.getJspConfigPageEncoding(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the JSP config element whose URL * pattern matches this page. Treat "UTF-16", "UTF-16BE", and * "UTF-16LE" as identical. */ if (configEnc != null) { configEnc = configEnc.toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(configEnc) && (!pageDirEnc.startsWith("UTF-16") || !configEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.config_pagedir_encoding_mismatch", configEnc, pageDirEnc); } else { return configEnc; } } /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } else { return pageEnc; } } return pageDirEnc; } /* * Compares page encodings specified in various places, and throws * exception in case of page encoding mismatch. * * @param thePageDirEnc The value of the pageEncoding attribute of the page * directive @param pageDir The page directive node * * @throws JasperException in case of page encoding mismatch */ private void compareTagEncodings(String thePageDirEnc, Node.TagDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } } } } /** * A visitor for validating nodes other than page directives */ private static class ValidateVisitor extends Node.Visitor { private final PageInfo pageInfo; private final ErrorDispatcher err; private final ClassLoader loader; private final StringBuilder buf = new StringBuilder(32); private static final JspUtil.ValidAttribute[] jspRootAttrs = { new JspUtil.ValidAttribute("xsi:schemaLocation"), new JspUtil.ValidAttribute("version", true) }; private static final JspUtil.ValidAttribute[] includeDirectiveAttrs = { new JspUtil.ValidAttribute( "file", true) }; private static final JspUtil.ValidAttribute[] taglibDirectiveAttrs = { new JspUtil.ValidAttribute("uri"), new JspUtil.ValidAttribute("tagdir"), new JspUtil.ValidAttribute("prefix", true) }; private static final JspUtil.ValidAttribute[] includeActionAttrs = { new JspUtil.ValidAttribute("page", true), new JspUtil.ValidAttribute("flush") }; private static final JspUtil.ValidAttribute[] paramActionAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("value", true) }; private static final JspUtil.ValidAttribute[] forwardActionAttrs = { new JspUtil.ValidAttribute("page", true) }; private static final JspUtil.ValidAttribute[] getPropertyAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("property", true) }; private static final JspUtil.ValidAttribute[] setPropertyAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("property", true), new JspUtil.ValidAttribute("value", false), new JspUtil.ValidAttribute("param") }; private static final JspUtil.ValidAttribute[] useBeanAttrs = { new JspUtil.ValidAttribute("id", true), new JspUtil.ValidAttribute("scope"), new JspUtil.ValidAttribute("class"), new JspUtil.ValidAttribute("type"), new JspUtil.ValidAttribute("beanName", false) }; private static final JspUtil.ValidAttribute[] plugInAttrs = { new JspUtil.ValidAttribute("type", true), new JspUtil.ValidAttribute("code", true), new JspUtil.ValidAttribute("codebase"), new JspUtil.ValidAttribute("align"), new JspUtil.ValidAttribute("archive"), new JspUtil.ValidAttribute("height", false), new JspUtil.ValidAttribute("hspace"), new JspUtil.ValidAttribute("jreversion"), new JspUtil.ValidAttribute("name"), new JspUtil.ValidAttribute("vspace"), new JspUtil.ValidAttribute("width", false), new JspUtil.ValidAttribute("nspluginurl"), new JspUtil.ValidAttribute("iepluginurl") }; private static final JspUtil.ValidAttribute[] attributeAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("trim"), new JspUtil.ValidAttribute("omit")}; private static final JspUtil.ValidAttribute[] invokeAttrs = { new JspUtil.ValidAttribute("fragment", true), new JspUtil.ValidAttribute("var"), new JspUtil.ValidAttribute("varReader"), new JspUtil.ValidAttribute("scope") }; private static final JspUtil.ValidAttribute[] doBodyAttrs = { new JspUtil.ValidAttribute("var"), new JspUtil.ValidAttribute("varReader"), new JspUtil.ValidAttribute("scope") }; private static final JspUtil.ValidAttribute[] jspOutputAttrs = { new JspUtil.ValidAttribute("omit-xml-declaration"), new JspUtil.ValidAttribute("doctype-root-element"), new JspUtil.ValidAttribute("doctype-public"), new JspUtil.ValidAttribute("doctype-system") }; private final ExpressionFactory expressionFactory; /* * Constructor */ ValidateVisitor(Compiler compiler) { this.pageInfo = compiler.getPageInfo(); this.err = compiler.getErrorDispatcher(); this.loader = compiler.getCompilationContext().getClassLoader(); // Get the cached EL expression factory for this context expressionFactory = JspFactory.getDefaultFactory().getJspApplicationContext( compiler.getCompilationContext().getServletContext()). getExpressionFactory(); } @Override public void visit(Node.JspRoot n) throws JasperException { JspUtil.checkAttributes("Jsp:root", n, jspRootAttrs, err); String version = n.getTextAttribute("version"); if (!version.equals("1.2") && !version.equals("2.0") && !version.equals("2.1") && !version.equals("2.2") && !version.equals("2.3")) { err.jspError(n, "jsp.error.jsproot.version.invalid", version); } visitBody(n); } @Override public void visit(Node.IncludeDirective n) throws JasperException { JspUtil.checkAttributes("Include directive", n, includeDirectiveAttrs, err); visitBody(n); } @Override public void visit(Node.TaglibDirective n) throws JasperException { JspUtil.checkAttributes("Taglib directive", n, taglibDirectiveAttrs, err); // Either 'uri' or 'tagdir' attribute must be specified String uri = n.getAttributeValue("uri"); String tagdir = n.getAttributeValue("tagdir"); if (uri == null && tagdir == null) { err.jspError(n, "jsp.error.taglibDirective.missing.location"); } if (uri != null && tagdir != null) { err .jspError(n, "jsp.error.taglibDirective.both_uri_and_tagdir"); } } @Override public void visit(Node.ParamAction n) throws JasperException { JspUtil.checkAttributes("Param action", n, paramActionAttrs, err); // make sure the value of the 'name' attribute is not a // request-time expression throwErrorIfExpression(n, "name", "jsp:param"); n.setValue(getJspAttribute(null, "value", null, null, n .getAttributeValue("value"), n, false)); visitBody(n); } @Override public void visit(Node.ParamsAction n) throws JasperException { // Make sure we've got at least one nested jsp:param Node.Nodes subElems = n.getBody(); if (subElems == null) { err.jspError(n, "jsp.error.params.emptyBody"); } visitBody(n); } @Override public void visit(Node.IncludeAction n) throws JasperException { JspUtil.checkAttributes("Include action", n, includeActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); } @Override public void visit(Node.ForwardAction n) throws JasperException { JspUtil.checkAttributes("Forward", n, forwardActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); } @Override public void visit(Node.GetProperty n) throws JasperException { JspUtil.checkAttributes("GetProperty", n, getPropertyAttrs, err); } @Override public void visit(Node.SetProperty n) throws JasperException { JspUtil.checkAttributes("SetProperty", n, setPropertyAttrs, err); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); String value = n.getAttributeValue("value"); n.setValue(getJspAttribute(null, "value", null, null, value, n, false)); boolean valueSpecified = n.getValue() != null; if ("*".equals(property)) { if (param != null || valueSpecified) err.jspError(n, "jsp.error.setProperty.invalid"); } else if (param != null && valueSpecified) { err.jspError(n, "jsp.error.setProperty.invalid"); } visitBody(n); } @Override public void visit(Node.UseBean n) throws JasperException { JspUtil.checkAttributes("UseBean", n, useBeanAttrs, err); String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String className = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); BeanRepository beanInfo = pageInfo.getBeanRepository(); if (className == null && type == null) err.jspError(n, "jsp.error.usebean.missingType"); if (beanInfo.checkVariable(name)) err.jspError(n, "jsp.error.usebean.duplicate"); if ("session".equals(scope) && !pageInfo.isSession()) err.jspError(n, "jsp.error.usebean.noSession"); Node.JspAttribute jattr = getJspAttribute(null, "beanName", null, null, n.getAttributeValue("beanName"), n, false); n.setBeanName(jattr); if (className != null && jattr != null) err.jspError(n, "jsp.error.usebean.notBoth"); if (className == null) className = type; beanInfo.addBean(n, name, className, scope); visitBody(n); } @SuppressWarnings("null") // type can't be null after initial test @Override public void visit(Node.PlugIn n) throws JasperException { JspUtil.checkAttributes("Plugin", n, plugInAttrs, err); throwErrorIfExpression(n, "type", "jsp:plugin"); throwErrorIfExpression(n, "code", "jsp:plugin"); throwErrorIfExpression(n, "codebase", "jsp:plugin"); throwErrorIfExpression(n, "align", "jsp:plugin"); throwErrorIfExpression(n, "archive", "jsp:plugin"); throwErrorIfExpression(n, "hspace", "jsp:plugin"); throwErrorIfExpression(n, "jreversion", "jsp:plugin"); throwErrorIfExpression(n, "name", "jsp:plugin"); throwErrorIfExpression(n, "vspace", "jsp:plugin"); throwErrorIfExpression(n, "nspluginurl", "jsp:plugin"); throwErrorIfExpression(n, "iepluginurl", "jsp:plugin"); String type = n.getTextAttribute("type"); if (type == null) err.jspError(n, "jsp.error.plugin.notype"); if (!type.equals("bean") && !type.equals("applet")) err.jspError(n, "jsp.error.plugin.badtype"); if (n.getTextAttribute("code") == null) err.jspError(n, "jsp.error.plugin.nocode"); Node.JspAttribute width = getJspAttribute(null, "width", null, null, n.getAttributeValue("width"), n, false); n.setWidth(width); Node.JspAttribute height = getJspAttribute(null, "height", null, null, n.getAttributeValue("height"), n, false); n.setHeight(height); visitBody(n); } @Override public void visit(Node.NamedAttribute n) throws JasperException { JspUtil.checkAttributes("Attribute", n, attributeAttrs, err); n.setOmit(getJspAttribute(null, "omit", null, null, n .getAttributeValue("omit"), n, true)); visitBody(n); } @Override public void visit(Node.JspBody n) throws JasperException { visitBody(n); } @Override public void visit(Node.Declaration n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } } @Override public void visit(Node.Expression n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } } @Override public void visit(Node.Scriptlet n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } } @Override public void visit(Node.ELExpression n) throws JasperException { // exit if we are ignoring EL all together if (pageInfo.isELIgnored()) return; // JSP.2.2 - '#{' not allowed in template text if (n.getType() == '#') { if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { err.jspError(n, "jsp.error.el.template.deferred"); } else { return; } } // build expression StringBuilder expr = this.getBuffer(); expr.append(n.getType()).append('{').append(n.getText()) .append('}'); ELNode.Nodes el = ELParser.parse(expr.toString(), pageInfo .isDeferredSyntaxAllowedAsLiteral()); // validate/prepare expression prepareExpression(el, n, expr.toString()); // store it n.setEL(el); } @Override public void visit(Node.UninterpretedTag n) throws JasperException { if (n.getNamedAttributeNodes().size() != 0) { err.jspError(n, "jsp.error.namedAttribute.invalidUse"); } Attributes attrs = n.getAttributes(); if (attrs != null) { int attrSize = attrs.getLength(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[attrSize]; for (int i = 0; i < attrSize; i++) { // JSP.2.2 - '#{' not allowed in template text String value = attrs.getValue(i); if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { if (containsDeferredSyntax(value)) { err.jspError(n, "jsp.error.el.template.deferred"); } } jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), value, n, false); } n.setJspAttributes(jspAttrs); } visitBody(n); } /* * Look for a #{ sequence that isn't preceded by \. */ private boolean containsDeferredSyntax(String value) { if (value == null) { return false; } int i = 0; int len = value.length(); boolean prevCharIsEscape = false; while (i < value.length()) { char c = value.charAt(i); if (c == '#' && (i+1) < len && value.charAt(i+1) == '{' && !prevCharIsEscape) { return true; } else if (c == '\\') { prevCharIsEscape = true; } else { prevCharIsEscape = false; } i++; } return false; } @SuppressWarnings("null") // tagInfo can't be null after initial test @Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } /* * The bodycontent of a SimpleTag cannot be JSP. */ if (n.implementsSimpleTag() && tagInfo.getBodyContent().equalsIgnoreCase( TagInfo.BODY_CONTENT_JSP)) { err.jspError(n, "jsp.error.simpletag.badbodycontent", tagInfo .getTagClassName()); } /* * If the tag handler declares in the TLD that it supports dynamic * attributes, it also must implement the DynamicAttributes * interface. */ if (tagInfo.hasDynamicAttributes() && !n.implementsDynamicAttributes()) { err.jspError(n, "jsp.error.dynamic.attributes.not.implemented", n.getQName()); } /* * Make sure all required attributes are present, either as * attributes or named attributes (<jsp:attribute>). Also make sure * that the same attribute is not specified in both attributes or * named attributes. */ TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); String customActionUri = n.getURI(); Attributes attrs = n.getAttributes(); int attrsSize = (attrs == null) ? 0 : attrs.getLength(); for (int i = 0; i < tldAttrs.length; i++) { String attr = null; if (attrs != null) { attr = attrs.getValue(tldAttrs[i].getName()); if (attr == null) { attr = attrs.getValue(customActionUri, tldAttrs[i] .getName()); } } Node.NamedAttribute na = n.getNamedAttributeNode(tldAttrs[i] .getName()); if (tldAttrs[i].isRequired() && attr == null && na == null) { err.jspError(n, "jsp.error.missing_attribute", tldAttrs[i] .getName(), n.getLocalName()); } if (attr != null && na != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", tldAttrs[i].getName()); } } Node.Nodes naNodes = n.getNamedAttributeNodes(); int jspAttrsSize = naNodes.size() + attrsSize; Node.JspAttribute[] jspAttrs = null; if (jspAttrsSize > 0) { jspAttrs = new Node.JspAttribute[jspAttrsSize]; } Hashtable<String, Object> tagDataAttrs = new Hashtable<>(attrsSize); checkXmlAttributes(n, jspAttrs, tagDataAttrs); checkNamedAttributes(n, jspAttrs, attrsSize, tagDataAttrs); TagData tagData = new TagData(tagDataAttrs); // JSP.C1: It is a (translation time) error for an action that // has one or more variable subelements to have a TagExtraInfo // class that returns a non-null object. TagExtraInfo tei = tagInfo.getTagExtraInfo(); if (tei != null && tei.getVariableInfo(tagData) != null && tei.getVariableInfo(tagData).length > 0 && tagInfo.getTagVariableInfos().length > 0) { err.jspError("jsp.error.non_null_tei_and_var_subelems", n .getQName()); } n.setTagData(tagData); n.setJspAttributes(jspAttrs); visitBody(n); } @Override public void visit(Node.JspElement n) throws JasperException { Attributes attrs = n.getAttributes(); if (attrs == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } @SuppressWarnings("null") // Exception will have been thrown above int xmlAttrLen = attrs.getLength(); Node.Nodes namedAttrs = n.getNamedAttributeNodes(); // XML-style 'name' attribute, which is mandatory, must not be // included in JspAttribute array int jspAttrSize = xmlAttrLen - 1 + namedAttrs.size(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize]; int jspAttrIndex = 0; // Process XML-style attributes for (int i = 0; i < xmlAttrLen; i++) { if ("name".equals(attrs.getLocalName(i))) { n.setNameAttribute(getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false)); } else { if (jspAttrIndex < jspAttrSize) { jspAttrs[jspAttrIndex++] = getJspAttribute(null, attrs .getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), n, false); } } } if (n.getNameAttribute() == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } // Process named attributes for (int i = 0; i < namedAttrs.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) namedAttrs .getNode(i); jspAttrs[jspAttrIndex++] = new Node.JspAttribute(na, null, false); } n.setJspAttributes(jspAttrs); visitBody(n); } @Override public void visit(Node.JspOutput n) throws JasperException { JspUtil.checkAttributes("jsp:output", n, jspOutputAttrs, err); if (n.getBody() != null) { err.jspError(n, "jsp.error.jspoutput.nonemptybody"); } String omitXmlDecl = n.getAttributeValue("omit-xml-declaration"); String doctypeName = n.getAttributeValue("doctype-root-element"); String doctypePublic = n.getAttributeValue("doctype-public"); String doctypeSystem = n.getAttributeValue("doctype-system"); String omitXmlDeclOld = pageInfo.getOmitXmlDecl(); String doctypeNameOld = pageInfo.getDoctypeName(); String doctypePublicOld = pageInfo.getDoctypePublic(); String doctypeSystemOld = pageInfo.getDoctypeSystem(); if (omitXmlDecl != null && omitXmlDeclOld != null && !omitXmlDecl.equals(omitXmlDeclOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "omit-xml-declaration", omitXmlDeclOld, omitXmlDecl); } if (doctypeName != null && doctypeNameOld != null && !doctypeName.equals(doctypeNameOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-root-element", doctypeNameOld, doctypeName); } if (doctypePublic != null && doctypePublicOld != null && !doctypePublic.equals(doctypePublicOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-public", doctypePublicOld, doctypePublic); } if (doctypeSystem != null && doctypeSystemOld != null && !doctypeSystem.equals(doctypeSystemOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-system", doctypeSystemOld, doctypeSystem); } if (doctypeName == null && doctypeSystem != null || doctypeName != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypenamesystem"); } if (doctypePublic != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypepulicsystem"); } if (omitXmlDecl != null) { pageInfo.setOmitXmlDecl(omitXmlDecl); } if (doctypeName != null) { pageInfo.setDoctypeName(doctypeName); } if (doctypeSystem != null) { pageInfo.setDoctypeSystem(doctypeSystem); } if (doctypePublic != null) { pageInfo.setDoctypePublic(doctypePublic); } } @Override public void visit(Node.InvokeAction n) throws JasperException { JspUtil.checkAttributes("Invoke", n, invokeAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } } @Override public void visit(Node.DoBodyAction n) throws JasperException { JspUtil.checkAttributes("DoBody", n, doBodyAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } } /* * Make sure the given custom action does not have any invalid * attributes. * * A custom action and its declared attributes always belong to the same * namespace, which is identified by the prefix name of the custom tag * invocation. For example, in this invocation: * * <my:test a="1" b="2" c="3"/>, the action * * "test" and its attributes "a", "b", and "c" all belong to the * namespace identified by the prefix "my". The above invocation would * be equivalent to: * * <my:test my:a="1" my:b="2" my:c="3"/> * * An action attribute may have a prefix different from that of the * action invocation only if the underlying tag handler supports dynamic * attributes, in which case the attribute with the different prefix is * considered a dynamic attribute. */ private void checkXmlAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { boolean found = false; boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("%=")) || (!n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("<%="))); boolean elExpression = false; boolean deferred = false; double libraryVersion = Double.parseDouble( tagInfo.getTagLibrary().getRequiredVersion()); boolean deferredSyntaxAllowedAsLiteral = pageInfo.isDeferredSyntaxAllowedAsLiteral() || libraryVersion < 2.1; ELNode.Nodes el = null; if (!runtimeExpression && !pageInfo.isELIgnored()) { el = ELParser.parse(attrs.getValue(i), deferredSyntaxAllowedAsLiteral); Iterator<ELNode> nodes = el.iterator(); while (nodes.hasNext()) { ELNode node = nodes.next(); if (node instanceof ELNode.Root) { if (((ELNode.Root) node).getType() == '$') { if (elExpression && deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; } else if (((ELNode.Root) node).getType() == '#') { if (elExpression && !deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; deferred = true; } } } } boolean expression = runtimeExpression || elExpression; for (int j = 0; tldAttrs != null && j < tldAttrs.length; j++) { if (attrs.getLocalName(i).equals(tldAttrs[j].getName()) && (attrs.getURI(i) == null || attrs.getURI(i).length() == 0 || attrs .getURI(i).equals(n.getURI()))) { TagAttributeInfo tldAttr = tldAttrs[j]; if (tldAttr.canBeRequestTime() || tldAttr.isDeferredMethod() || tldAttr.isDeferredValue()) { // JSP 2.1 if (!expression) { String expectedType = null; if (tldAttr.isDeferredMethod()) { // The String literal must be castable to what is declared as type // for the attribute String m = tldAttr.getMethodSignature(); if (m != null) { m = m.trim(); int rti = m.indexOf(' '); if (rti > 0) { expectedType = m.substring(0, rti).trim(); } } else { expectedType = "java.lang.Object"; } if ("void".equals(expectedType)) { // Can't specify a literal for a // deferred method with an expected type // of void - JSP.2.3.4 err.jspError(n, "jsp.error.literal_with_void", tldAttr.getName()); } } if (tldAttr.isDeferredValue()) { // The String literal must be castable to what is declared as type // for the attribute expectedType = tldAttr.getExpectedTypeName(); } if (expectedType != null) { Class<?> expectedClass = String.class; try { expectedClass = JspUtil.toClass(expectedType, loader); } catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); } // Check casting - not possible for all types if (String.class.equals(expectedClass) || expectedClass == Long.TYPE || expectedClass == Double.TYPE || expectedClass == Byte.TYPE || expectedClass == Short.TYPE || expectedClass == Integer.TYPE || expectedClass == Float.TYPE || Number.class.isAssignableFrom(expectedClass) || Character.class.equals(expectedClass) || Character.TYPE == expectedClass || Boolean.class.equals(expectedClass) || Boolean.TYPE == expectedClass || expectedClass.isEnum()) { try { expressionFactory.coerceToType(attrs.getValue(i), expectedClass); } catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); } } } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } else { if (deferred && !tldAttr.isDeferredMethod() && !tldAttr.isDeferredValue()) { // No deferred expressions allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (!deferred && !tldAttr.canBeRequestTime()) { // Only deferred expressions are allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (elExpression) { // El expression validateFunctions(el, n); jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs.getValue(i), false, el, false); ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(getFunctionMapper(el)); try { jspAttrs[i].validateEL(this.pageInfo.getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); } } else { // Runtime expression jspAttrs[i] = getJspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false); } } } else { // Attribute does not accept any expressions. // Make sure its value does not contain any. if (expression) { err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } if (expression) { tagDataAttrs.put(attrs.getQName(i), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(attrs.getQName(i), attrs .getValue(i)); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, true); } else { err.jspError(n, "jsp.error.bad_attribute", attrs .getQName(i), n.getLocalName()); } } } } /* * Make sure the given custom action does not have any invalid named * attributes */ private void checkNamedAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, int start, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Node.Nodes naNodes = n.getNamedAttributeNodes(); for (int i = 0; i < naNodes.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) naNodes .getNode(i); boolean found = false; for (int j = 0; j < tldAttrs.length; j++) { /* * See above comment about namespace matches. For named * attributes, we use the prefix instead of URI as the match * criterion, because in the case of a JSP document, we'd * have to keep track of which namespaces are in scope when * parsing a named attribute, in order to determine the URI * that the prefix of the named attribute's name matches to. */ String attrPrefix = na.getPrefix(); if (na.getLocalName().equals(tldAttrs[j].getName()) && (attrPrefix == null || attrPrefix.length() == 0 || attrPrefix .equals(n.getPrefix()))) { jspAttrs[start + i] = new Node.JspAttribute(na, tldAttrs[j], false); NamedAttributeVisitor nav = null; if (na.getBody() != null) { nav = new NamedAttributeVisitor(); na.getBody().visit(nav); } if (nav != null && nav.hasDynamicContent()) { tagDataAttrs.put(na.getName(), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(na.getName(), na.getText()); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[start + i] = new Node.JspAttribute(na, null, true); } else { err.jspError(n, "jsp.error.bad_attribute", na.getName(), n.getLocalName()); } } } } /** * Preprocess attributes that can be expressions. Expression delimiters * are stripped. * <p> * If value is null, checks if there are any NamedAttribute subelements * in the tree node, and if so, constructs a JspAttribute out of a child * NamedAttribute node. */ private Node.JspAttribute getJspAttribute(TagAttributeInfo tai, String qName, String uri, String localName, String value, Node n, boolean dynamic) throws JasperException { Node.JspAttribute result = null; // XXX Is it an error to see "%=foo%" in non-Xml page? // (We won't see "<%=foo%> in xml page because '<' is not a // valid attribute value in xml). if (value != null) { if (n.getRoot().isXmlSyntax() && value.startsWith("%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(2, value.length() - 1), true, null, dynamic); } else if (!n.getRoot().isXmlSyntax() && value.startsWith("<%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(3, value.length() - 2), true, null, dynamic); } else if (pageInfo.isELIgnored()) { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } else { // The attribute can contain expressions but is not a // scriptlet expression; thus, we want to run it through // the expression interpreter // validate expression syntax if string contains // expression(s) ELNode.Nodes el = ELParser.parse(value, pageInfo .isDeferredSyntaxAllowedAsLiteral()); if (el.containsEL()) { validateFunctions(el, n); result = new Node.JspAttribute(tai, qName, uri, localName, value, false, el, dynamic); ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(getFunctionMapper(el)); try { result.validateEL(this.pageInfo .getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); } } else { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } } } else { // Value is null. Check for any NamedAttribute subnodes // that might contain the value for this attribute. // Otherwise, the attribute wasn't found so we return null. Node.NamedAttribute namedAttributeNode = n .getNamedAttributeNode(qName); if (namedAttributeNode != null) { result = new Node.JspAttribute(namedAttributeNode, tai, dynamic); } } return result; } /* * Return an empty StringBuilder [not thread-safe] */ private StringBuilder getBuffer() { this.buf.setLength(0); return this.buf; } /* * Checks to see if the given attribute value represents a runtime or EL * expression. */ private boolean isExpression(Node n, String value, boolean checkDeferred) { boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && value.startsWith("%=")) || (!n.getRoot().isXmlSyntax() && value.startsWith("<%="))); boolean elExpression = false; if (!runtimeExpression && !pageInfo.isELIgnored()) { Iterator<ELNode> nodes = ELParser.parse(value, pageInfo.isDeferredSyntaxAllowedAsLiteral()).iterator(); while (nodes.hasNext()) { ELNode node = nodes.next(); if (node instanceof ELNode.Root) { if (((ELNode.Root) node).getType() == '$') { elExpression = true; } else if (checkDeferred && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && ((ELNode.Root) node).getType() == '#') { elExpression = true; } } } } return runtimeExpression || elExpression; } /* * Throws exception if the value of the attribute with the given name in * the given node is given as an RT or EL expression, but the spec * requires a static value. */ private void throwErrorIfExpression(Node n, String attrName, String actionName) throws JasperException { if (n.getAttributes() != null && n.getAttributes().getValue(attrName) != null && isExpression(n, n.getAttributes().getValue(attrName), true)) { err.jspError(n, "jsp.error.attribute.standard.non_rt_with_expr", attrName, actionName); } } private static class NamedAttributeVisitor extends Node.Visitor { private boolean hasDynamicContent; @Override public void doVisit(Node n) throws JasperException { if (!(n instanceof Node.JspText) && !(n instanceof Node.TemplateText)) { hasDynamicContent = true; } visitBody(n); } public boolean hasDynamicContent() { return hasDynamicContent; } } private String findUri(String prefix, Node n) { for (Node p = n; p != null; p = p.getParent()) { Attributes attrs = p.getTaglibAttributes(); if (attrs == null) { continue; } for (int i = 0; i < attrs.getLength(); i++) { String name = attrs.getQName(i); int k = name.indexOf(':'); if (prefix == null && k < 0) { // prefix not specified and a default ns found return attrs.getValue(i); } if (prefix != null && k >= 0 && prefix.equals(name.substring(k + 1))) { return attrs.getValue(i); } } } return null; } /** * Validate functions in EL expressions */ private void validateFunctions(ELNode.Nodes el, Node n) throws JasperException { class FVVisitor extends ELNode.Visitor { private Node n; FVVisitor(Node n) { this.n = n; } @Override public void visit(ELNode.Function func) throws JasperException { String prefix = func.getPrefix(); String function = func.getName(); String uri = null; if (n.getRoot().isXmlSyntax()) { uri = findUri(prefix, n); } else if (prefix != null) { uri = pageInfo.getURI(prefix); } if (uri == null) { if (prefix == null) { err.jspError(n, "jsp.error.noFunctionPrefix", function); } else { err.jspError(n, "jsp.error.attribute.invalidPrefix", prefix); } } TagLibraryInfo taglib = pageInfo.getTaglib(uri); FunctionInfo funcInfo = null; if (taglib != null) { funcInfo = taglib.getFunction(function); } if (funcInfo == null) { err.jspError(n, "jsp.error.noFunction", function); } // Skip TLD function uniqueness check. Done by Schema ? func.setUri(uri); func.setFunctionInfo(funcInfo); processSignature(func); } } el.visit(new FVVisitor(n)); } private void prepareExpression(ELNode.Nodes el, Node n, String expr) throws JasperException { validateFunctions(el, n); // test it out ELContextImpl ctx = new ELContextImpl(); ctx.setFunctionMapper(this.getFunctionMapper(el)); ExpressionFactory ef = this.pageInfo.getExpressionFactory(); try { ef.createValueExpression(ctx, expr, Object.class); } catch (ELException e) { } } private void processSignature(ELNode.Function func) throws JasperException { func.setMethodName(getMethod(func)); func.setParameters(getParameters(func)); } /** * Get the method name from the signature. */ private String getMethod(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); int start = signature.indexOf(' '); if (start < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } int end = signature.indexOf('('); if (end < 0) { err.jspError( "jsp.error.tld.fn.invalid.signature.parenexpected", func.getPrefix(), func.getName()); } return signature.substring(start + 1, end).trim(); } /** * Get the parameters types from the function signature. * * @return An array of parameter class names */ private String[] getParameters(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); ArrayList<String> params = new ArrayList<>(); // Signature is of the form // <return-type> S <method-name S? '(' // < <arg-type> ( ',' <arg-type> )* )? ')' int start = signature.indexOf('(') + 1; boolean lastArg = false; while (true) { int p = signature.indexOf(',', start); if (p < 0) { p = signature.indexOf(')', start); if (p < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } lastArg = true; } String arg = signature.substring(start, p).trim(); if (!"".equals(arg)) { params.add(arg); } if (lastArg) { break; } start = p + 1; } return params.toArray(new String[params.size()]); } private FunctionMapper getFunctionMapper(ELNode.Nodes el) throws JasperException { class ValidateFunctionMapper extends FunctionMapper { private HashMap<String, Method> fnmap = new HashMap<>(); public void mapFunction(String fnQName, Method method) { fnmap.put(fnQName, method); } @Override public Method resolveFunction(String prefix, String localName) { return this.fnmap.get(prefix + ":" + localName); } } class MapperELVisitor extends ELNode.Visitor { private ValidateFunctionMapper fmapper; MapperELVisitor(ValidateFunctionMapper fmapper) { this.fmapper = fmapper; } @SuppressWarnings("null") // c can't be null after catch block @Override public void visit(ELNode.Function n) throws JasperException { Class<?> c = null; Method method = null; try { c = loader.loadClass(n.getFunctionInfo() .getFunctionClass()); } catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); } String paramTypes[] = n.getParameters(); int size = paramTypes.length; Class<?> params[] = new Class[size]; int i = 0; try { for (i = 0; i < size; i++) { params[i] = JspUtil.toClass(paramTypes[i], loader); } method = c.getDeclaredMethod(n.getMethodName(), params); } catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); } catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); } fmapper.mapFunction(n.getPrefix() + ':' + n.getName(), method); } } ValidateFunctionMapper fmapper = new ValidateFunctionMapper(); el.visit(new MapperELVisitor(fmapper)); return fmapper; } } // End of ValidateVisitor /** * A visitor for validating TagExtraInfo classes of all tags */ private static class TagExtraInfoVisitor extends Node.Visitor { private final ErrorDispatcher err; /* * Constructor */ TagExtraInfoVisitor(Compiler compiler) { this.err = compiler.getErrorDispatcher(); } @Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } @SuppressWarnings("null") // tagInfo can't be null here ValidationMessage[] errors = tagInfo.validate(n.getTagData()); if (errors != null && errors.length != 0) { StringBuilder errMsg = new StringBuilder(); errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tei.invalid.attributes", n.getQName())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { errMsg.append("<p>"); if (errors[i].getId() != null) { errMsg.append(errors[i].getId()); errMsg.append(": "); } errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } err.jspError(n, errMsg.toString()); } visitBody(n); } } public static void validateDirectives(Compiler compiler, Node.Nodes page) throws JasperException { page.visit(new DirectiveVisitor(compiler)); } public static void validateExDirectives(Compiler compiler, Node.Nodes page) throws JasperException { // Determine the default output content type PageInfo pageInfo = compiler.getPageInfo(); String contentType = pageInfo.getContentType(); if (contentType == null || contentType.indexOf("charset=") < 0) { boolean isXml = page.getRoot().isXmlSyntax(); String defaultType; if (contentType == null) { defaultType = isXml ? "text/xml" : "text/html"; } else { defaultType = contentType; } String charset = null; if (isXml) { charset = "UTF-8"; } else { if (!page.getRoot().isDefaultPageEncoding()) { charset = page.getRoot().getPageEncoding(); } } if (charset != null) { pageInfo.setContentType(defaultType + ";charset=" + charset); } else { pageInfo.setContentType(defaultType); } } /* * Validate all other nodes. This validation step includes checking a * custom tag's mandatory and optional attributes against information in * the TLD (first validation step for custom tags according to * JSP.10.5). */ page.visit(new ValidateVisitor(compiler)); /* * Invoke TagLibraryValidator classes of all imported tags (second * validation step for custom tags according to JSP.10.5). */ validateXmlView(new PageDataImpl(page, compiler), compiler); /* * Invoke TagExtraInfo method isValid() for all imported tags (third * validation step for custom tags according to JSP.10.5). */ page.visit(new TagExtraInfoVisitor(compiler)); } // ********************************************************************* // Private (utility) methods /** * Validate XML view against the TagLibraryValidator classes of all imported * tag libraries. */ private static void validateXmlView(PageData xmlView, Compiler compiler) throws JasperException { StringBuilder errMsg = null; ErrorDispatcher errDisp = compiler.getErrorDispatcher(); for (Iterator<TagLibraryInfo> iter = compiler.getPageInfo().getTaglibs().iterator(); iter.hasNext();) { Object o = iter.next(); if (!(o instanceof TagLibraryInfoImpl)) continue; TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o; ValidationMessage[] errors = tli.validate(xmlView); if ((errors != null) && (errors.length != 0)) { if (errMsg == null) { errMsg = new StringBuilder(); } errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tlv.invalid.page", tli.getShortName(), compiler.getPageInfo().getJspFile())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { if (errors[i] != null) { errMsg.append("<p>"); errMsg.append(errors[i].getId()); errMsg.append(": "); errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } } } } if (errMsg != null) { errDisp.jspError(errMsg.toString()); } } }
53,987
Bug 53987 Log uncovered HTTP methods in combined security constraints
It is usually an error (and a security hole) if security constraints are defined for some but not all HTTP methods for a given URL. If such a situation is detected on web application start, log it.
resolved fixed
f78c1a4
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-19T21:43:26Z
2012-10-09T22:00:00Z
java/org/apache/catalina/core/StandardContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.ServletSecurityElement; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; import org.apache.catalina.Authenticator; import org.apache.catalina.Cluster; import org.apache.catalina.Container; import org.apache.catalina.ContainerListener; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.InstanceListener; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.catalina.Loader; import org.apache.catalina.Manager; import org.apache.catalina.Pipeline; import org.apache.catalina.Realm; import org.apache.catalina.Valve; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.catalina.deploy.ApplicationListener; import org.apache.catalina.deploy.ApplicationParameter; import org.apache.catalina.deploy.ErrorPage; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.deploy.FilterMap; import org.apache.catalina.deploy.Injectable; import org.apache.catalina.deploy.InjectionTarget; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.MessageDestination; import org.apache.catalina.deploy.MessageDestinationRef; import org.apache.catalina.deploy.NamingResources; import org.apache.catalina.deploy.SecurityCollection; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.loader.WebappLoader; import org.apache.catalina.session.StandardManager; import org.apache.catalina.startup.TldConfig; import org.apache.catalina.util.CharsetMapper; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.ExtensionValidator; import org.apache.catalina.util.RequestUtil; import org.apache.catalina.util.URLEncoder; import org.apache.catalina.webresources.StandardRoot; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.naming.ContextBindings; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.JarScanner; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.scan.StandardJarScanner; /** * Standard implementation of the <b>Context</b> interface. Each * child container must be a Wrapper implementation to process the * requests directed to a particular servlet. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class StandardContext extends ContainerBase implements Context, NotificationEmitter { private static final Log log = LogFactory.getLog(StandardContext.class); // ----------------------------------------------------------- Constructors /** * Create a new StandardContext component with the default basic Valve. */ public StandardContext() { super(); pipeline.setBasic(new StandardContextValve()); broadcaster = new NotificationBroadcasterSupport(); // Set defaults if (!Globals.STRICT_SERVLET_COMPLIANCE) { // Strict servlet compliance requires all extension mapped servlets // to be checked against welcome files resourceOnlyServlets.add("jsp"); } } // ----------------------------------------------------- Class Variables /** * Array containing the safe characters set. */ protected static URLEncoder urlEncoder; /** * GMT timezone - all HTTP dates are on GMT */ static { urlEncoder = new URLEncoder(); urlEncoder.addSafeCharacter('~'); urlEncoder.addSafeCharacter('-'); urlEncoder.addSafeCharacter('_'); urlEncoder.addSafeCharacter('.'); urlEncoder.addSafeCharacter('*'); urlEncoder.addSafeCharacter('/'); } // ----------------------------------------------------- Instance Variables /** * Allow multipart/form-data requests to be parsed even when the * target servlet doesn't specify @MultipartConfig or have a * &lt;multipart-config&gt; element. */ protected boolean allowCasualMultipartParsing = false; /** * Control whether remaining request data will be read * (swallowed) even if the request violates a data size constraint. */ private boolean swallowAbortedUploads = true; /** * The alternate deployment descriptor name. */ private String altDDName = null; /** * Lifecycle provider. */ private InstanceManager instanceManager = null; /** * The antiJARLocking flag for this Context. */ private boolean antiJARLocking = false; /** * The antiResourceLocking flag for this Context. */ private boolean antiResourceLocking = false; /** * The set of application listener class names configured for this * application, in the order they were encountered in the resulting merged * web.xml file. */ private ApplicationListener applicationListeners[] = new ApplicationListener[0]; private final Object applicationListenersLock = new Object(); /** * The set of instantiated application event listener objects. Note that * SCIs and other code may use the pluggability APIs to add listener * instances directly to this list before the application starts. */ private Object applicationEventListenersObjects[] = new Object[0]; /** * The set of instantiated application lifecycle listener objects. Note that * SCIs and other code may use the pluggability APIs to add listener * instances directly to this list before the application starts. */ private Object applicationLifecycleListenersObjects[] = new Object[0]; /** * The ordered set of ServletContainerInitializers for this web application. */ private Map<ServletContainerInitializer,Set<Class<?>>> initializers = new LinkedHashMap<>(); /** * The set of application parameters defined for this application. */ private ApplicationParameter applicationParameters[] = new ApplicationParameter[0]; private final Object applicationParametersLock = new Object(); /** * The broadcaster that sends j2ee notifications. */ private NotificationBroadcasterSupport broadcaster = null; /** * The Locale to character set mapper for this application. */ private CharsetMapper charsetMapper = null; /** * The Java class name of the CharsetMapper class to be created. */ private String charsetMapperClass = "org.apache.catalina.util.CharsetMapper"; /** * The URL of the XML descriptor for this context. */ private URL configFile = null; /** * The "correctly configured" flag for this Context. */ private boolean configured = false; /** * The security constraints for this web application. */ private volatile SecurityConstraint constraints[] = new SecurityConstraint[0]; private final Object constraintsLock = new Object(); /** * The ServletContext implementation associated with this Context. */ protected ApplicationContext context = null; /** * Should we attempt to use cookies for session id communication? */ private boolean cookies = true; /** * Should we allow the <code>ServletContext.getContext()</code> method * to access the context of other web applications in this server? */ private boolean crossContext = false; /** * Encoded path. */ private String encodedPath = null; /** * Unencoded path for this web application. */ private String path = null; /** * The "follow standard delegation model" flag that will be used to * configure our ClassLoader. */ private boolean delegate = false; /** * The display name of this web application. */ private String displayName = null; /** * Override the default context xml location. */ private String defaultContextXml; /** * Override the default web xml location. */ private String defaultWebXml; /** * The distributable flag for this web application. */ private boolean distributable = false; /** * The document root for this web application. */ private String docBase = null; /** * The exception pages for this web application, keyed by fully qualified * class name of the Java exception. */ private HashMap<String, ErrorPage> exceptionPages = new HashMap<>(); /** * The set of filter configurations (and associated filter instances) we * have initialized, keyed by filter name. */ private HashMap<String, ApplicationFilterConfig> filterConfigs = new HashMap<>(); /** * The set of filter definitions for this application, keyed by * filter name. */ private HashMap<String, FilterDef> filterDefs = new HashMap<>(); /** * The set of filter mappings for this application, in the order * they were defined in the deployment descriptor with additional mappings * added via the {@link ServletContext} possibly both before and after those * defined in the deployment descriptor. */ private final ContextFilterMaps filterMaps = new ContextFilterMaps(); /** * Ignore annotations. */ private boolean ignoreAnnotations = false; /** * The set of classnames of InstanceListeners that will be added * to each newly created Wrapper by <code>createWrapper()</code>. */ private String instanceListeners[] = new String[0]; private final Object instanceListenersLock = new Object(); /** * The Loader implementation with which this Container is associated. */ private Loader loader = null; private final ReadWriteLock loaderLock = new ReentrantReadWriteLock(); /** * The login configuration descriptor for this web application. */ private LoginConfig loginConfig = null; /** * The Manager implementation with which this Container is associated. */ protected Manager manager = null; private final ReadWriteLock managerLock = new ReentrantReadWriteLock(); /** * The naming context listener for this web application. */ private NamingContextListener namingContextListener = null; /** * The naming resources for this web application. */ private NamingResources namingResources = null; /** * The message destinations for this web application. */ private HashMap<String, MessageDestination> messageDestinations = new HashMap<>(); /** * The MIME mappings for this web application, keyed by extension. */ private HashMap<String, String> mimeMappings = new HashMap<>(); /** * The context initialization parameters for this web application, * keyed by name. */ private HashMap<String, String> parameters = new HashMap<>(); /** * The request processing pause flag (while reloading occurs) */ private boolean paused = false; /** * The public identifier of the DTD for the web application deployment * descriptor version we are currently parsing. This is used to support * relaxed validation rules when processing version 2.2 web.xml files. */ private String publicId = null; /** * The reloadable flag for this web application. */ private boolean reloadable = false; /** * Unpack WAR property. */ private boolean unpackWAR = true; /** * Context level override for default {@link StandardHost#isCopyXML()}. */ private boolean copyXML = false; /** * The default context override flag for this web application. */ private boolean override = false; /** * The original document root for this web application. */ private String originalDocBase = null; /** * The privileged flag for this web application. */ private boolean privileged = false; /** * Should the next call to <code>addWelcomeFile()</code> cause replacement * of any existing welcome files? This will be set before processing the * web application's deployment descriptor, so that application specified * choices <strong>replace</strong>, rather than append to, those defined * in the global descriptor. */ private boolean replaceWelcomeFiles = false; /** * The security role mappings for this application, keyed by role * name (as used within the application). */ private HashMap<String, String> roleMappings = new HashMap<>(); /** * The security roles for this application, keyed by role name. */ private String securityRoles[] = new String[0]; private final Object securityRolesLock = new Object(); /** * The servlet mappings for this web application, keyed by * matching pattern. */ private HashMap<String, String> servletMappings = new HashMap<>(); private final Object servletMappingsLock = new Object(); /** * The session timeout (in minutes) for this web application. */ private int sessionTimeout = 30; /** * The notification sequence number. */ private AtomicLong sequenceNumber = new AtomicLong(0); /** * The status code error pages for this web application, keyed by * HTTP status code (as an Integer). Note status code zero is used for the * default error page. */ private HashMap<Integer, ErrorPage> statusPages = new HashMap<>(); /** * Set flag to true to cause the system.out and system.err to be redirected * to the logger when executing a servlet. */ private boolean swallowOutput = false; /** * Amount of ms that the container will wait for servlets to unload. */ private long unloadDelay = 2000; /** * The watched resources for this application. */ private String watchedResources[] = new String[0]; private final Object watchedResourcesLock = new Object(); /** * The welcome files for this application. */ private String welcomeFiles[] = new String[0]; private final Object welcomeFilesLock = new Object(); /** * The set of classnames of LifecycleListeners that will be added * to each newly created Wrapper by <code>createWrapper()</code>. */ private String wrapperLifecycles[] = new String[0]; private final Object wrapperLifecyclesLock = new Object(); /** * The set of classnames of ContainerListeners that will be added * to each newly created Wrapper by <code>createWrapper()</code>. */ private String wrapperListeners[] = new String[0]; private final Object wrapperListenersLock = new Object(); /** * The pathname to the work directory for this context (relative to * the server's home if not absolute). */ private String workDir = null; /** * Java class name of the Wrapper class implementation we use. */ private String wrapperClassName = StandardWrapper.class.getName(); private Class<?> wrapperClass = null; /** * JNDI use flag. */ private boolean useNaming = true; /** * Name of the associated naming context. */ private String namingContextName = null; /** * Caching allowed flag. */ private boolean cachingAllowed = true; /** * Allow linking. */ protected boolean allowLinking = false; /** * Cache max size in KB. */ protected int cacheMaxSize = 10240; // 10 MB /** * Cache object max size in KB. */ protected int cacheObjectMaxSize = 512; // 512K /** * Cache TTL in ms. */ protected int cacheTTL = 5000; private WebResourceRoot resources; private final ReadWriteLock resourcesLock = new ReentrantReadWriteLock(); private long startupTime; private long startTime; private long tldScanTime; /** * Name of the engine. If null, the domain is used. */ private String j2EEApplication="none"; private String j2EEServer="none"; /** * Attribute value used to turn on/off XML validation */ private boolean webXmlValidation = Globals.STRICT_SERVLET_COMPLIANCE; /** * Attribute value used to turn on/off XML namespace validation */ private boolean webXmlNamespaceAware = Globals.STRICT_SERVLET_COMPLIANCE; /** * Attribute value used to turn on/off TLD processing */ private boolean processTlds = true; /** * Attribute value used to turn on/off XML validation */ private boolean tldValidation = Globals.STRICT_SERVLET_COMPLIANCE; /** * Attribute value used to turn on/off TLD XML namespace validation */ private boolean tldNamespaceAware = Globals.STRICT_SERVLET_COMPLIANCE; /** * The name to use for session cookies. <code>null</code> indicates that * the name is controlled by the application. */ private String sessionCookieName; /** * The flag that indicates that session cookies should use HttpOnly */ private boolean useHttpOnly = true; /** * The domain to use for session cookies. <code>null</code> indicates that * the domain is controlled by the application. */ private String sessionCookieDomain; /** * The path to use for session cookies. <code>null</code> indicates that * the path is controlled by the application. */ private String sessionCookiePath; /** * Is a / added to the end of the session cookie path to ensure browsers, * particularly IE, don't send a session cookie for context /foo with * requests intended for context /foobar. */ private boolean sessionCookiePathUsesTrailingSlash = true; /** * The Jar scanner to use to search for Jars that might contain * configuration information such as TLDs or web-fragment.xml files. */ private JarScanner jarScanner = null; /** * Should Tomcat attempt to null out any static or final fields from loaded * classes when a web application is stopped as a work around for apparent * garbage collection bugs and application coding errors? There have been * some issues reported with log4j when this option is true. Applications * without memory leaks using recent JVMs should operate correctly with this * option set to <code>false</code>. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStatic = false; /** * Should Tomcat attempt to terminate threads that have been started by the * web application? Stopping threads is performed via the deprecated (for * good reason) <code>Thread.stop()</code> method and is likely to result in * instability. As such, enabling this should be viewed as an option of last * resort in a development environment and is not recommended in a * production environment. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStopThreads = false; /** * Should Tomcat attempt to terminate any {@link java.util.TimerThread}s * that have been started by the web application? If not specified, the * default value of <code>false</code> will be used. */ private boolean clearReferencesStopTimerThreads = false; /** * If an HttpClient keep-alive timer thread has been started by this web * application and is still running, should Tomcat change the context class * loader from the current {@link WebappClassLoader} to * {@link WebappClassLoader#parent} to prevent a memory leak? Note that the * keep-alive timer thread will stop on its own once the keep-alives all * expire however, on a busy system that might not happen for some time. */ private boolean clearReferencesHttpClientKeepAliveThread = true; /** * Should Tomcat renew the threads of the thread pool when the application * is stopped to avoid memory leaks because of uncleaned ThreadLocal * variables. This also requires that the threadRenewalDelay property of the * StandardThreadExecutor of ThreadPoolExecutor be set to a positive value. */ private boolean renewThreadsWhenStoppingContext = true; /** * Should the effective web.xml be logged when the context starts? */ private boolean logEffectiveWebXml = false; private int effectiveMajorVersion = 3; private int effectiveMinorVersion = 0; private JspConfigDescriptor jspConfigDescriptor = new ApplicationJspConfigDescriptor(); private Set<String> resourceOnlyServlets = new HashSet<>(); private String webappVersion = ""; private boolean addWebinfClassesResources = false; private boolean fireRequestListenersOnForwards = false; /** * Servlets created via {@link ApplicationContext#createServlet(Class)} for * tracking purposes. */ private Set<Servlet> createdServlets = new HashSet<>(); private boolean preemptiveAuthentication = false; private boolean sendRedirectBody = false; private boolean jndiExceptionOnFailedWrite = true; private Map<String, String> postConstructMethods = new HashMap<>(); private Map<String, String> preDestroyMethods = new HashMap<>(); // ----------------------------------------------------- Context Properties @Override public boolean getSendRedirectBody() { return sendRedirectBody; } @Override public void setSendRedirectBody(boolean sendRedirectBody) { this.sendRedirectBody = sendRedirectBody; } @Override public boolean getPreemptiveAuthentication() { return preemptiveAuthentication; } @Override public void setPreemptiveAuthentication(boolean preemptiveAuthentication) { this.preemptiveAuthentication = preemptiveAuthentication; } @Override public void setFireRequestListenersOnForwards(boolean enable) { fireRequestListenersOnForwards = enable; } @Override public boolean getFireRequestListenersOnForwards() { return fireRequestListenersOnForwards; } @Override public void setAddWebinfClassesResources( boolean addWebinfClassesResources) { this.addWebinfClassesResources = addWebinfClassesResources; } @Override public boolean getAddWebinfClassesResources() { return addWebinfClassesResources; } @Override public void setWebappVersion(String webappVersion) { if (null == webappVersion) { this.webappVersion = ""; } else { this.webappVersion = webappVersion; } } @Override public String getWebappVersion() { return webappVersion; } @Override public String getBaseName() { return new ContextName(path, webappVersion).getBaseName(); } @Override public String getResourceOnlyServlets() { StringBuilder result = new StringBuilder(); boolean first = true; for (String servletName : resourceOnlyServlets) { if (!first) { result.append(','); } result.append(servletName); } return result.toString(); } @Override public void setResourceOnlyServlets(String resourceOnlyServlets) { this.resourceOnlyServlets.clear(); if (resourceOnlyServlets == null) { return; } for (String servletName : resourceOnlyServlets.split(",")) { servletName = servletName.trim(); if (servletName.length()>0) { this.resourceOnlyServlets.add(servletName); } } } @Override public boolean isResourceOnlyServlet(String servletName) { return resourceOnlyServlets.contains(servletName); } @Override public int getEffectiveMajorVersion() { return effectiveMajorVersion; } @Override public void setEffectiveMajorVersion(int effectiveMajorVersion) { this.effectiveMajorVersion = effectiveMajorVersion; } @Override public int getEffectiveMinorVersion() { return effectiveMinorVersion; } @Override public void setEffectiveMinorVersion(int effectiveMinorVersion) { this.effectiveMinorVersion = effectiveMinorVersion; } @Override public void setLogEffectiveWebXml(boolean logEffectiveWebXml) { this.logEffectiveWebXml = logEffectiveWebXml; } @Override public boolean getLogEffectiveWebXml() { return logEffectiveWebXml; } @Override public Authenticator getAuthenticator() { if (this instanceof Authenticator) return (Authenticator) this; Pipeline pipeline = getPipeline(); if (pipeline != null) { Valve basic = pipeline.getBasic(); if ((basic != null) && (basic instanceof Authenticator)) return (Authenticator) basic; Valve valves[] = pipeline.getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof Authenticator) return (Authenticator) valves[i]; } } return null; } @Override public JarScanner getJarScanner() { if (jarScanner == null) { jarScanner = new StandardJarScanner(); } return jarScanner; } @Override public void setJarScanner(JarScanner jarScanner) { this.jarScanner = jarScanner; } @Override public InstanceManager getInstanceManager() { return instanceManager; } @Override public void setInstanceManager(InstanceManager instanceManager) { this.instanceManager = instanceManager; } @Override public String getEncodedPath() { return encodedPath; } /** * Is caching allowed ? */ public boolean isCachingAllowed() { return cachingAllowed; } /** * Set caching allowed flag. */ public void setCachingAllowed(boolean cachingAllowed) { this.cachingAllowed = cachingAllowed; } /** * Set allow linking. */ public void setAllowLinking(boolean allowLinking) { this.allowLinking = allowLinking; } /** * Is linking allowed. */ public boolean isAllowLinking() { return allowLinking; } /** * Set to <code>true</code> to allow requests mapped to servlets that * do not explicitly declare @MultipartConfig or have * &lt;multipart-config&gt; specified in web.xml to parse * multipart/form-data requests. * * @param allowCasualMultipartParsing <code>true</code> to allow such * casual parsing, <code>false</code> otherwise. */ @Override public void setAllowCasualMultipartParsing( boolean allowCasualMultipartParsing) { this.allowCasualMultipartParsing = allowCasualMultipartParsing; } /** * Returns <code>true</code> if requests mapped to servlets without * "multipart config" to parse multipart/form-data requests anyway. * * @return <code>true</code> if requests mapped to servlets without * "multipart config" to parse multipart/form-data requests, * <code>false</code> otherwise. */ @Override public boolean getAllowCasualMultipartParsing() { return this.allowCasualMultipartParsing; } /** * Set to <code>false</code> to disable request data swallowing * after an upload was aborted due to size constraints. * * @param swallowAbortedUploads <code>false</code> to disable * swallowing, <code>true</code> otherwise (default). */ @Override public void setSwallowAbortedUploads(boolean swallowAbortedUploads) { this.swallowAbortedUploads = swallowAbortedUploads; } /** * Returns <code>true</code> if remaining request data will be read * (swallowed) even the request violates a data size constraint. * * @return <code>true</code> if data will be swallowed (default), * <code>false</code> otherwise. */ @Override public boolean getSwallowAbortedUploads() { return this.swallowAbortedUploads; } /** * Set cache TTL. */ public void setCacheTTL(int cacheTTL) { this.cacheTTL = cacheTTL; } /** * Get cache TTL. */ public int getCacheTTL() { return cacheTTL; } /** * Return the maximum size of the cache in KB. */ public int getCacheMaxSize() { return cacheMaxSize; } /** * Set the maximum size of the cache in KB. */ public void setCacheMaxSize(int cacheMaxSize) { this.cacheMaxSize = cacheMaxSize; } /** * Return the maximum size of objects to be cached in KB. */ public int getCacheObjectMaxSize() { return cacheObjectMaxSize; } /** * Set the maximum size of objects to be placed the cache in KB. */ public void setCacheObjectMaxSize(int cacheObjectMaxSize) { this.cacheObjectMaxSize = cacheObjectMaxSize; } /** * Add a ServletContainerInitializer instance to this web application. * * @param sci The instance to add * @param classes The classes in which the initializer expressed an * interest */ @Override public void addServletContainerInitializer( ServletContainerInitializer sci, Set<Class<?>> classes) { initializers.put(sci, classes); } /** * Return the "follow standard delegation model" flag used to configure * our ClassLoader. */ public boolean getDelegate() { return (this.delegate); } /** * Set the "follow standard delegation model" flag used to configure * our ClassLoader. * * @param delegate The new flag */ public void setDelegate(boolean delegate) { boolean oldDelegate = this.delegate; this.delegate = delegate; support.firePropertyChange("delegate", oldDelegate, this.delegate); } /** * Returns true if the internal naming support is used. */ public boolean isUseNaming() { return (useNaming); } /** * Enables or disables naming. */ public void setUseNaming(boolean useNaming) { this.useNaming = useNaming; } /** * Return the set of initialized application event listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @exception IllegalStateException if this method is called before * this application has started, or after it has been stopped */ @Override public Object[] getApplicationEventListeners() { return (applicationEventListenersObjects); } /** * Store the set of initialized application event listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @param listeners The set of instantiated listener objects. */ @Override public void setApplicationEventListeners(Object listeners[]) { applicationEventListenersObjects = listeners; } /** * Add a listener to the end of the list of initialized application event * listeners. */ public void addApplicationEventListener(Object listener) { int len = applicationEventListenersObjects.length; Object[] newListeners = Arrays.copyOf(applicationEventListenersObjects, len + 1); newListeners[len] = listener; applicationEventListenersObjects = newListeners; } /** * Return the set of initialized application lifecycle listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @exception IllegalStateException if this method is called before * this application has started, or after it has been stopped */ @Override public Object[] getApplicationLifecycleListeners() { return (applicationLifecycleListenersObjects); } /** * Store the set of initialized application lifecycle listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @param listeners The set of instantiated listener objects. */ @Override public void setApplicationLifecycleListeners(Object listeners[]) { applicationLifecycleListenersObjects = listeners; } /** * Add a listener to the end of the list of initialized application * lifecycle listeners. */ public void addApplicationLifecycleListener(Object listener) { int len = applicationLifecycleListenersObjects.length; Object[] newListeners = Arrays.copyOf( applicationLifecycleListenersObjects, len + 1); newListeners[len] = listener; applicationLifecycleListenersObjects = newListeners; } /** * Return the antiJARLocking flag for this Context. */ public boolean getAntiJARLocking() { return (this.antiJARLocking); } /** * Return the antiResourceLocking flag for this Context. */ public boolean getAntiResourceLocking() { return (this.antiResourceLocking); } /** * Set the antiJARLocking feature for this Context. * * @param antiJARLocking The new flag value */ public void setAntiJARLocking(boolean antiJARLocking) { boolean oldAntiJARLocking = this.antiJARLocking; this.antiJARLocking = antiJARLocking; support.firePropertyChange("antiJARLocking", oldAntiJARLocking, this.antiJARLocking); } /** * Set the antiResourceLocking feature for this Context. * * @param antiResourceLocking The new flag value */ public void setAntiResourceLocking(boolean antiResourceLocking) { boolean oldAntiResourceLocking = this.antiResourceLocking; this.antiResourceLocking = antiResourceLocking; support.firePropertyChange("antiResourceLocking", oldAntiResourceLocking, this.antiResourceLocking); } /** * Return the Locale to character set mapper for this Context. */ public CharsetMapper getCharsetMapper() { // Create a mapper the first time it is requested if (this.charsetMapper == null) { try { Class<?> clazz = Class.forName(charsetMapperClass); this.charsetMapper = (CharsetMapper) clazz.newInstance(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); this.charsetMapper = new CharsetMapper(); } } return (this.charsetMapper); } /** * Set the Locale to character set mapper for this Context. * * @param mapper The new mapper */ public void setCharsetMapper(CharsetMapper mapper) { CharsetMapper oldCharsetMapper = this.charsetMapper; this.charsetMapper = mapper; if( mapper != null ) this.charsetMapperClass= mapper.getClass().getName(); support.firePropertyChange("charsetMapper", oldCharsetMapper, this.charsetMapper); } @Override public String getCharset(Locale locale) { return getCharsetMapper().getCharset(locale); } /** * Return the URL of the XML descriptor for this context. */ @Override public URL getConfigFile() { return (this.configFile); } /** * Set the URL of the XML descriptor for this context. * * @param configFile The URL of the XML descriptor for this context. */ @Override public void setConfigFile(URL configFile) { this.configFile = configFile; } /** * Return the "correctly configured" flag for this Context. */ @Override public boolean getConfigured() { return (this.configured); } /** * Set the "correctly configured" flag for this Context. This can be * set to false by startup listeners that detect a fatal configuration * error to avoid the application from being made available. * * @param configured The new correctly configured flag */ @Override public void setConfigured(boolean configured) { boolean oldConfigured = this.configured; this.configured = configured; support.firePropertyChange("configured", oldConfigured, this.configured); } /** * Return the "use cookies for session ids" flag. */ @Override public boolean getCookies() { return (this.cookies); } /** * Set the "use cookies for session ids" flag. * * @param cookies The new flag */ @Override public void setCookies(boolean cookies) { boolean oldCookies = this.cookies; this.cookies = cookies; support.firePropertyChange("cookies", oldCookies, this.cookies); } /** * Gets the name to use for session cookies. Overrides any setting that * may be specified by the application. * * @return The value of the default session cookie name or null if not * specified */ @Override public String getSessionCookieName() { return sessionCookieName; } /** * Sets the name to use for session cookies. Overrides any setting that * may be specified by the application. * * @param sessionCookieName The name to use */ @Override public void setSessionCookieName(String sessionCookieName) { String oldSessionCookieName = this.sessionCookieName; this.sessionCookieName = sessionCookieName; support.firePropertyChange("sessionCookieName", oldSessionCookieName, sessionCookieName); } /** * Gets the value of the use HttpOnly cookies for session cookies flag. * * @return <code>true</code> if the HttpOnly flag should be set on session * cookies */ @Override public boolean getUseHttpOnly() { return useHttpOnly; } /** * Sets the use HttpOnly cookies for session cookies flag. * * @param useHttpOnly Set to <code>true</code> to use HttpOnly cookies * for session cookies */ @Override public void setUseHttpOnly(boolean useHttpOnly) { boolean oldUseHttpOnly = this.useHttpOnly; this.useHttpOnly = useHttpOnly; support.firePropertyChange("useHttpOnly", oldUseHttpOnly, this.useHttpOnly); } /** * Gets the domain to use for session cookies. Overrides any setting that * may be specified by the application. * * @return The value of the default session cookie domain or null if not * specified */ @Override public String getSessionCookieDomain() { return sessionCookieDomain; } /** * Sets the domain to use for session cookies. Overrides any setting that * may be specified by the application. * * @param sessionCookieDomain The domain to use */ @Override public void setSessionCookieDomain(String sessionCookieDomain) { String oldSessionCookieDomain = this.sessionCookieDomain; this.sessionCookieDomain = sessionCookieDomain; support.firePropertyChange("sessionCookieDomain", oldSessionCookieDomain, sessionCookieDomain); } /** * Gets the path to use for session cookies. Overrides any setting that * may be specified by the application. * * @return The value of the default session cookie path or null if not * specified */ @Override public String getSessionCookiePath() { return sessionCookiePath; } /** * Sets the path to use for session cookies. Overrides any setting that * may be specified by the application. * * @param sessionCookiePath The path to use */ @Override public void setSessionCookiePath(String sessionCookiePath) { String oldSessionCookiePath = this.sessionCookiePath; this.sessionCookiePath = sessionCookiePath; support.firePropertyChange("sessionCookiePath", oldSessionCookiePath, sessionCookiePath); } @Override public boolean getSessionCookiePathUsesTrailingSlash() { return sessionCookiePathUsesTrailingSlash; } @Override public void setSessionCookiePathUsesTrailingSlash( boolean sessionCookiePathUsesTrailingSlash) { this.sessionCookiePathUsesTrailingSlash = sessionCookiePathUsesTrailingSlash; } /** * Return the "allow crossing servlet contexts" flag. */ @Override public boolean getCrossContext() { return (this.crossContext); } /** * Set the "allow crossing servlet contexts" flag. * * @param crossContext The new cross contexts flag */ @Override public void setCrossContext(boolean crossContext) { boolean oldCrossContext = this.crossContext; this.crossContext = crossContext; support.firePropertyChange("crossContext", oldCrossContext, this.crossContext); } public String getDefaultContextXml() { return defaultContextXml; } /** * Set the location of the default context xml that will be used. * If not absolute, it'll be made relative to the engine's base dir * ( which defaults to catalina.base system property ). * * @param defaultContextXml The default web xml */ public void setDefaultContextXml(String defaultContextXml) { this.defaultContextXml = defaultContextXml; } public String getDefaultWebXml() { return defaultWebXml; } /** * Set the location of the default web xml that will be used. * If not absolute, it'll be made relative to the engine's base dir * ( which defaults to catalina.base system property ). * * @param defaultWebXml The default web xml */ public void setDefaultWebXml(String defaultWebXml) { this.defaultWebXml = defaultWebXml; } /** * Gets the time (in milliseconds) it took to start this context. * * @return Time (in milliseconds) it took to start this context. */ public long getStartupTime() { return startupTime; } public void setStartupTime(long startupTime) { this.startupTime = startupTime; } public long getTldScanTime() { return tldScanTime; } public void setTldScanTime(long tldScanTime) { this.tldScanTime = tldScanTime; } /** * Return the display name of this web application. */ @Override public String getDisplayName() { return (this.displayName); } /** * Return the alternate Deployment Descriptor name. */ @Override public String getAltDDName(){ return altDDName; } /** * Set an alternate Deployment Descriptor name. */ @Override public void setAltDDName(String altDDName) { this.altDDName = altDDName; if (context != null) { context.setAttribute(Globals.ALT_DD_ATTR,altDDName); } } /** * Set the display name of this web application. * * @param displayName The new display name */ @Override public void setDisplayName(String displayName) { String oldDisplayName = this.displayName; this.displayName = displayName; support.firePropertyChange("displayName", oldDisplayName, this.displayName); } /** * Return the distributable flag for this web application. */ @Override public boolean getDistributable() { return (this.distributable); } /** * Set the distributable flag for this web application. * * @param distributable The new distributable flag */ @Override public void setDistributable(boolean distributable) { boolean oldDistributable = this.distributable; this.distributable = distributable; support.firePropertyChange("distributable", oldDistributable, this.distributable); // Bugzilla 32866 if(getManager() != null) { if(log.isDebugEnabled()) { log.debug("Propagating distributable=" + distributable + " to manager"); } getManager().setDistributable(distributable); } } /** * Return the document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. */ @Override public String getDocBase() { return (this.docBase); } /** * Set the document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. * * @param docBase The new document root */ @Override public void setDocBase(String docBase) { this.docBase = docBase; } public String getJ2EEApplication() { return j2EEApplication; } public void setJ2EEApplication(String j2EEApplication) { this.j2EEApplication = j2EEApplication; } public String getJ2EEServer() { return j2EEServer; } public void setJ2EEServer(String j2EEServer) { this.j2EEServer = j2EEServer; } @Override public Loader getLoader() { Lock readLock = loaderLock.readLock(); readLock.lock(); try { return loader; } finally { readLock.unlock(); } } @Override public void setLoader(Loader loader) { Lock writeLock = loaderLock.writeLock(); writeLock.lock(); Loader oldLoader = null; try { // Change components if necessary oldLoader = this.loader; if (oldLoader == loader) return; this.loader = loader; // Stop the old component if necessary if (getState().isAvailable() && (oldLoader != null) && (oldLoader instanceof Lifecycle)) { try { ((Lifecycle) oldLoader).stop(); } catch (LifecycleException e) { log.error("StandardContext.setLoader: stop: ", e); } } // Start the new component if necessary if (loader != null) loader.setContext(this); if (getState().isAvailable() && (loader != null) && (loader instanceof Lifecycle)) { try { ((Lifecycle) loader).start(); } catch (LifecycleException e) { log.error("StandardContext.setLoader: start: ", e); } } } finally { writeLock.unlock(); } // Report this property change to interested listeners support.firePropertyChange("loader", oldLoader, loader); } @Override public Manager getManager() { Lock readLock = managerLock.readLock(); readLock.lock(); try { return manager; } finally { readLock.unlock(); } } @Override public void setManager(Manager manager) { Lock writeLock = managerLock.writeLock(); writeLock.lock(); Manager oldManager = null; try { // Change components if necessary oldManager = this.manager; if (oldManager == manager) return; this.manager = manager; // Stop the old component if necessary if (getState().isAvailable() && (oldManager != null) && (oldManager instanceof Lifecycle)) { try { ((Lifecycle) oldManager).stop(); } catch (LifecycleException e) { log.error("StandardContext.setManager: stop: ", e); } } // Start the new component if necessary if (manager != null) manager.setContext(this); if (getState().isAvailable() && (manager != null) && (manager instanceof Lifecycle)) { try { ((Lifecycle) manager).start(); } catch (LifecycleException e) { log.error("StandardContext.setManager: start: ", e); } } } finally { writeLock.unlock(); } // Report this property change to interested listeners support.firePropertyChange("manager", oldManager, manager); } /** * Return the boolean on the annotations parsing. */ @Override public boolean getIgnoreAnnotations() { return this.ignoreAnnotations; } /** * Set the boolean on the annotations parsing for this web * application. * * @param ignoreAnnotations The boolean on the annotations parsing */ @Override public void setIgnoreAnnotations(boolean ignoreAnnotations) { boolean oldIgnoreAnnotations = this.ignoreAnnotations; this.ignoreAnnotations = ignoreAnnotations; support.firePropertyChange("ignoreAnnotations", oldIgnoreAnnotations, this.ignoreAnnotations); } /** * Return the login configuration descriptor for this web application. */ @Override public LoginConfig getLoginConfig() { return (this.loginConfig); } /** * Set the login configuration descriptor for this web application. * * @param config The new login configuration */ @Override public void setLoginConfig(LoginConfig config) { // Validate the incoming property value if (config == null) throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.required")); String loginPage = config.getLoginPage(); if ((loginPage != null) && !loginPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.loginWarning", loginPage)); config.setLoginPage("/" + loginPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.loginPage", loginPage)); } } String errorPage = config.getErrorPage(); if ((errorPage != null) && !errorPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.errorWarning", errorPage)); config.setErrorPage("/" + errorPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.errorPage", errorPage)); } } // Process the property setting change LoginConfig oldLoginConfig = this.loginConfig; this.loginConfig = config; support.firePropertyChange("loginConfig", oldLoginConfig, this.loginConfig); } /** * Return the naming resources associated with this web application. */ @Override public NamingResources getNamingResources() { if (namingResources == null) { setNamingResources(new NamingResources()); } return (namingResources); } /** * Set the naming resources for this web application. * * @param namingResources The new naming resources */ @Override public void setNamingResources(NamingResources namingResources) { // Process the property setting change NamingResources oldNamingResources = this.namingResources; this.namingResources = namingResources; if (namingResources != null) { namingResources.setContainer(this); } support.firePropertyChange("namingResources", oldNamingResources, this.namingResources); if (getState() == LifecycleState.NEW || getState() == LifecycleState.INITIALIZING || getState() == LifecycleState.INITIALIZED) { // NEW will occur if Context is defined in server.xml // At this point getObjectKeyPropertiesNameOnly() will trigger an // NPE. // INITIALIZED will occur if the Context is defined in a context.xml // file // If started now, a second start will be attempted when the context // starts // In both cases, return and let context init the namingResources // when it starts return; } if (oldNamingResources != null) { try { oldNamingResources.stop(); oldNamingResources.destroy(); } catch (LifecycleException e) { log.warn("standardContext.namingResource.destroy.fail", e); } } if (namingResources != null) { try { namingResources.init(); namingResources.start(); } catch (LifecycleException e) { log.warn("standardContext.namingResource.init.fail", e); } } } /** * Return the context path for this Context. */ @Override public String getPath() { return (path); } /** * Set the context path for this Context. * * @param path The new context path */ @Override public void setPath(String path) { if (path == null || (!path.equals("") && !path.startsWith("/"))) { this.path = "/" + path; log.warn(sm.getString( "standardContext.pathInvalid", path, this.path)); } else { this.path = path; } encodedPath = urlEncoder.encode(this.path); if (getName() == null) { setName(this.path); } } /** * Return the public identifier of the deployment descriptor DTD that is * currently being parsed. */ @Override public String getPublicId() { return (this.publicId); } /** * Set the public identifier of the deployment descriptor DTD that is * currently being parsed. * * @param publicId The public identifier */ @Override public void setPublicId(String publicId) { if (log.isDebugEnabled()) log.debug("Setting deployment descriptor public ID to '" + publicId + "'"); String oldPublicId = this.publicId; this.publicId = publicId; support.firePropertyChange("publicId", oldPublicId, publicId); } /** * Return the reloadable flag for this web application. */ @Override public boolean getReloadable() { return (this.reloadable); } /** * Return the default context override flag for this web application. */ @Override public boolean getOverride() { return (this.override); } /** * Return the original document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. * Is only set as deployment has change docRoot! */ public String getOriginalDocBase() { return (this.originalDocBase); } /** * Set the original document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. * * @param docBase The original document root */ public void setOriginalDocBase(String docBase) { this.originalDocBase = docBase; } /** * Return the parent class loader (if any) for this web application. * This call is meaningful only <strong>after</strong> a Loader has * been configured. */ @Override public ClassLoader getParentClassLoader() { if (parentClassLoader != null) return (parentClassLoader); if (getPrivileged()) { return this.getClass().getClassLoader(); } else if (parent != null) { return (parent.getParentClassLoader()); } return (ClassLoader.getSystemClassLoader()); } /** * Return the privileged flag for this web application. */ @Override public boolean getPrivileged() { return (this.privileged); } /** * Set the privileged flag for this web application. * * @param privileged The new privileged flag */ @Override public void setPrivileged(boolean privileged) { boolean oldPrivileged = this.privileged; this.privileged = privileged; support.firePropertyChange("privileged", oldPrivileged, this.privileged); } /** * Set the reloadable flag for this web application. * * @param reloadable The new reloadable flag */ @Override public void setReloadable(boolean reloadable) { boolean oldReloadable = this.reloadable; this.reloadable = reloadable; support.firePropertyChange("reloadable", oldReloadable, this.reloadable); } /** * Set the default context override flag for this web application. * * @param override The new override flag */ @Override public void setOverride(boolean override) { boolean oldOverride = this.override; this.override = override; support.firePropertyChange("override", oldOverride, this.override); } /** * Set the "replace welcome files" property. * * @param replaceWelcomeFiles The new property value */ public void setReplaceWelcomeFiles(boolean replaceWelcomeFiles) { boolean oldReplaceWelcomeFiles = this.replaceWelcomeFiles; this.replaceWelcomeFiles = replaceWelcomeFiles; support.firePropertyChange("replaceWelcomeFiles", oldReplaceWelcomeFiles, this.replaceWelcomeFiles); } /** * Return the servlet context for which this Context is a facade. */ @Override public ServletContext getServletContext() { if (context == null) { context = new ApplicationContext(this); if (altDDName != null) context.setAttribute(Globals.ALT_DD_ATTR,altDDName); } return (context.getFacade()); } /** * Return the default session timeout (in minutes) for this * web application. */ @Override public int getSessionTimeout() { return (this.sessionTimeout); } /** * Set the default session timeout (in minutes) for this * web application. * * @param timeout The new default session timeout */ @Override public void setSessionTimeout(int timeout) { int oldSessionTimeout = this.sessionTimeout; /* * SRV.13.4 ("Deployment Descriptor"): * If the timeout is 0 or less, the container ensures the default * behaviour of sessions is never to time out. */ this.sessionTimeout = (timeout == 0) ? -1 : timeout; support.firePropertyChange("sessionTimeout", oldSessionTimeout, this.sessionTimeout); } /** * Return the value of the swallowOutput flag. */ @Override public boolean getSwallowOutput() { return (this.swallowOutput); } /** * Set the value of the swallowOutput flag. If set to true, the system.out * and system.err will be redirected to the logger during a servlet * execution. * * @param swallowOutput The new value */ @Override public void setSwallowOutput(boolean swallowOutput) { boolean oldSwallowOutput = this.swallowOutput; this.swallowOutput = swallowOutput; support.firePropertyChange("swallowOutput", oldSwallowOutput, this.swallowOutput); } /** * Return the value of the unloadDelay flag. */ public long getUnloadDelay() { return (this.unloadDelay); } /** * Set the value of the unloadDelay flag, which represents the amount * of ms that the container will wait when unloading servlets. * Setting this to a small value may cause more requests to fail * to complete when stopping a web application. * * @param unloadDelay The new value */ public void setUnloadDelay(long unloadDelay) { long oldUnloadDelay = this.unloadDelay; this.unloadDelay = unloadDelay; support.firePropertyChange("unloadDelay", Long.valueOf(oldUnloadDelay), Long.valueOf(this.unloadDelay)); } /** * Unpack WAR flag accessor. */ public boolean getUnpackWAR() { return (unpackWAR); } /** * Unpack WAR flag mutator. */ public void setUnpackWAR(boolean unpackWAR) { this.unpackWAR = unpackWAR; } public boolean getCopyXML() { return copyXML; } public void setCopyXML(boolean copyXML) { this.copyXML = copyXML; } /** * Return the Java class name of the Wrapper implementation used * for servlets registered in this Context. */ @Override public String getWrapperClass() { return (this.wrapperClassName); } /** * Set the Java class name of the Wrapper implementation used * for servlets registered in this Context. * * @param wrapperClassName The new wrapper class name * * @throws IllegalArgumentException if the specified wrapper class * cannot be found or is not a subclass of StandardWrapper */ @Override public void setWrapperClass(String wrapperClassName) { this.wrapperClassName = wrapperClassName; try { wrapperClass = Class.forName(wrapperClassName); if (!StandardWrapper.class.isAssignableFrom(wrapperClass)) { throw new IllegalArgumentException( sm.getString("standardContext.invalidWrapperClass", wrapperClassName)); } } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); } } @Override public WebResourceRoot getResources() { Lock readLock = resourcesLock.readLock(); readLock.lock(); try { return resources; } finally { readLock.unlock(); } } @Override public void setResources(WebResourceRoot resources) { Lock writeLock = resourcesLock.writeLock(); writeLock.lock(); WebResourceRoot oldResources = null; try { if (getState().isAvailable()) { throw new IllegalStateException (sm.getString("standardContext.resources.started")); } oldResources = this.resources; if (oldResources == resources) return; this.resources = resources; if (oldResources != null) { oldResources.setContext(null); } if (resources != null) { resources.setContext(this); } support.firePropertyChange("resources", oldResources, resources); } finally { writeLock.unlock(); } } @Override public JspConfigDescriptor getJspConfigDescriptor() { return jspConfigDescriptor; } // ------------------------------------------------------ Public Properties /** * Returns whether or not an attempt to modify the JNDI context will trigger * an exception or if the request will be ignored. */ public boolean getJndiExceptionOnFailedWrite() { return jndiExceptionOnFailedWrite; } /** * Controls whether or not an attempt to modify the JNDI context will * trigger an exception or if the request will be ignored. * * @param jndiExceptionOnFailedWrite */ public void setJndiExceptionOnFailedWrite( boolean jndiExceptionOnFailedWrite) { this.jndiExceptionOnFailedWrite = jndiExceptionOnFailedWrite; } /** * Return the Locale to character set mapper class for this Context. */ public String getCharsetMapperClass() { return (this.charsetMapperClass); } /** * Set the Locale to character set mapper class for this Context. * * @param mapper The new mapper class */ public void setCharsetMapperClass(String mapper) { String oldCharsetMapperClass = this.charsetMapperClass; this.charsetMapperClass = mapper; support.firePropertyChange("charsetMapperClass", oldCharsetMapperClass, this.charsetMapperClass); } /** Get the absolute path to the work dir. * To avoid duplication. * * @return The work path */ public String getWorkPath() { if (getWorkDir() == null) { return null; } File workDir = new File(getWorkDir()); if (!workDir.isAbsolute()) { try { workDir = new File(getCatalinaBase().getCanonicalFile(), getWorkDir()); } catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); } } return workDir.getAbsolutePath(); } /** * Return the work directory for this Context. */ public String getWorkDir() { return (this.workDir); } /** * Set the work directory for this Context. * * @param workDir The new work directory */ public void setWorkDir(String workDir) { this.workDir = workDir; if (getState().isAvailable()) { postWorkDirectory(); } } /** * Return the clearReferencesStatic flag for this Context. */ public boolean getClearReferencesStatic() { return (this.clearReferencesStatic); } /** * Set the clearReferencesStatic feature for this Context. * * @param clearReferencesStatic The new flag value */ public void setClearReferencesStatic(boolean clearReferencesStatic) { boolean oldClearReferencesStatic = this.clearReferencesStatic; this.clearReferencesStatic = clearReferencesStatic; support.firePropertyChange("clearReferencesStatic", oldClearReferencesStatic, this.clearReferencesStatic); } /** * Return the clearReferencesStopThreads flag for this Context. */ public boolean getClearReferencesStopThreads() { return (this.clearReferencesStopThreads); } /** * Set the clearReferencesStopThreads feature for this Context. * * @param clearReferencesStopThreads The new flag value */ public void setClearReferencesStopThreads( boolean clearReferencesStopThreads) { boolean oldClearReferencesStopThreads = this.clearReferencesStopThreads; this.clearReferencesStopThreads = clearReferencesStopThreads; support.firePropertyChange("clearReferencesStopThreads", oldClearReferencesStopThreads, this.clearReferencesStopThreads); } /** * Return the clearReferencesStopTimerThreads flag for this Context. */ public boolean getClearReferencesStopTimerThreads() { return (this.clearReferencesStopTimerThreads); } /** * Set the clearReferencesStopTimerThreads feature for this Context. * * @param clearReferencesStopTimerThreads The new flag value */ public void setClearReferencesStopTimerThreads( boolean clearReferencesStopTimerThreads) { boolean oldClearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads; this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads; support.firePropertyChange("clearReferencesStopTimerThreads", oldClearReferencesStopTimerThreads, this.clearReferencesStopTimerThreads); } /** * Return the clearReferencesHttpClientKeepAliveThread flag for this * Context. */ public boolean getClearReferencesHttpClientKeepAliveThread() { return (this.clearReferencesHttpClientKeepAliveThread); } /** * Set the clearReferencesHttpClientKeepAliveThread feature for this * Context. * * @param clearReferencesHttpClientKeepAliveThread The new flag value */ public void setClearReferencesHttpClientKeepAliveThread( boolean clearReferencesHttpClientKeepAliveThread) { this.clearReferencesHttpClientKeepAliveThread = clearReferencesHttpClientKeepAliveThread; } public boolean getRenewThreadsWhenStoppingContext() { return this.renewThreadsWhenStoppingContext; } public void setRenewThreadsWhenStoppingContext( boolean renewThreadsWhenStoppingContext) { boolean oldRenewThreadsWhenStoppingContext = this.renewThreadsWhenStoppingContext; this.renewThreadsWhenStoppingContext = renewThreadsWhenStoppingContext; support.firePropertyChange("renewThreadsWhenStoppingContext", oldRenewThreadsWhenStoppingContext, this.renewThreadsWhenStoppingContext); } // -------------------------------------------------------- Context Methods /** * Add a new Listener class name to the set of Listeners * configured for this application. * * @param listener Java class name of a listener class */ @Override public void addApplicationListener(ApplicationListener listener) { synchronized (applicationListenersLock) { ApplicationListener results[] = new ApplicationListener[applicationListeners.length + 1]; for (int i = 0; i < applicationListeners.length; i++) { if (listener.equals(applicationListeners[i])) { log.info(sm.getString( "standardContext.duplicateListener",listener)); return; } results[i] = applicationListeners[i]; } results[applicationListeners.length] = listener; applicationListeners = results; } fireContainerEvent("addApplicationListener", listener); // FIXME - add instance if already started? } /** * Add a new application parameter for this application. * * @param parameter The new application parameter */ @Override public void addApplicationParameter(ApplicationParameter parameter) { synchronized (applicationParametersLock) { String newName = parameter.getName(); for (ApplicationParameter p : applicationParameters) { if (newName.equals(p.getName()) && !p.getOverride()) return; } ApplicationParameter results[] = Arrays.copyOf( applicationParameters, applicationParameters.length + 1); results[applicationParameters.length] = parameter; applicationParameters = results; } fireContainerEvent("addApplicationParameter", parameter); } /** * Add a child Container, only if the proposed child is an implementation * of Wrapper. * * @param child Child container to be added * * @exception IllegalArgumentException if the proposed container is * not an implementation of Wrapper */ @Override public void addChild(Container child) { // Global JspServlet Wrapper oldJspServlet = null; if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } boolean isJspServlet = "jsp".equals(child.getName()); // Allow webapp to override JspServlet inherited from global web.xml. if (isJspServlet) { oldJspServlet = (Wrapper) findChild("jsp"); if (oldJspServlet != null) { removeChild(oldJspServlet); } } super.addChild(child); if (isJspServlet && oldJspServlet != null) { /* * The webapp-specific JspServlet inherits all the mappings * specified in the global web.xml, and may add additional ones. */ String[] jspMappings = oldJspServlet.findMappings(); for (int i=0; jspMappings!=null && i<jspMappings.length; i++) { addServletMapping(jspMappings[i], child.getName()); } } } /** * Add a security constraint to the set for this web application. */ @Override public void addConstraint(SecurityConstraint constraint) { // Validate the proposed constraint SecurityCollection collections[] = constraint.findCollections(); for (int i = 0; i < collections.length; i++) { String patterns[] = collections[i].findPatterns(); for (int j = 0; j < patterns.length; j++) { patterns[j] = adjustURLPattern(patterns[j]); if (!validateURLPattern(patterns[j])) throw new IllegalArgumentException (sm.getString ("standardContext.securityConstraint.pattern", patterns[j])); } if (collections[i].findMethods().length > 0 && collections[i].findOmittedMethods().length > 0) { throw new IllegalArgumentException(sm.getString( "standardContext.securityConstraint.mixHttpMethod")); } } // Add this constraint to the set for our web application synchronized (constraintsLock) { SecurityConstraint results[] = new SecurityConstraint[constraints.length + 1]; for (int i = 0; i < constraints.length; i++) results[i] = constraints[i]; results[constraints.length] = constraint; constraints = results; } } /** * Add an error page for the specified error or Java exception. * * @param errorPage The error page definition to be added */ @Override public void addErrorPage(ErrorPage errorPage) { // Validate the input parameters if (errorPage == null) throw new IllegalArgumentException (sm.getString("standardContext.errorPage.required")); String location = errorPage.getLocation(); if ((location != null) && !location.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.errorPage.warning", location)); errorPage.setLocation("/" + location); } else { throw new IllegalArgumentException (sm.getString("standardContext.errorPage.error", location)); } } // Add the specified error page to our internal collections String exceptionType = errorPage.getExceptionType(); if (exceptionType != null) { synchronized (exceptionPages) { exceptionPages.put(exceptionType, errorPage); } } else { synchronized (statusPages) { statusPages.put(Integer.valueOf(errorPage.getErrorCode()), errorPage); } } fireContainerEvent("addErrorPage", errorPage); } /** * Add a filter definition to this Context. * * @param filterDef The filter definition to be added */ @Override public void addFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.put(filterDef.getFilterName(), filterDef); } fireContainerEvent("addFilterDef", filterDef); } /** * Add a filter mapping to this Context at the end of the current set * of filter mappings. * * @param filterMap The filter mapping to be added * * @exception IllegalArgumentException if the specified filter name * does not match an existing filter definition, or the filter mapping * is malformed */ @Override public void addFilterMap(FilterMap filterMap) { validateFilterMap(filterMap); // Add this filter mapping to our registered set filterMaps.add(filterMap); fireContainerEvent("addFilterMap", filterMap); } /** * Add a filter mapping to this Context before the mappings defined in the * deployment descriptor but after any other mappings added via this method. * * @param filterMap The filter mapping to be added * * @exception IllegalArgumentException if the specified filter name * does not match an existing filter definition, or the filter mapping * is malformed */ @Override public void addFilterMapBefore(FilterMap filterMap) { validateFilterMap(filterMap); // Add this filter mapping to our registered set filterMaps.addBefore(filterMap); fireContainerEvent("addFilterMap", filterMap); } /** * Validate the supplied FilterMap. */ private void validateFilterMap(FilterMap filterMap) { // Validate the proposed filter mapping String filterName = filterMap.getFilterName(); String[] servletNames = filterMap.getServletNames(); String[] urlPatterns = filterMap.getURLPatterns(); if (findFilterDef(filterName) == null) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.name", filterName)); if (!filterMap.getMatchAllServletNames() && !filterMap.getMatchAllUrlPatterns() && (servletNames.length == 0) && (urlPatterns.length == 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); // FIXME: Older spec revisions may still check this /* if ((servletNames.length != 0) && (urlPatterns.length != 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); */ for (int i = 0; i < urlPatterns.length; i++) { if (!validateURLPattern(urlPatterns[i])) { throw new IllegalArgumentException (sm.getString("standardContext.filterMap.pattern", urlPatterns[i])); } } } /** * Add the classname of an InstanceListener to be added to each * Wrapper appended to this Context. * * @param listener Java class name of an InstanceListener class */ @Override public void addInstanceListener(String listener) { synchronized (instanceListenersLock) { String results[] =new String[instanceListeners.length + 1]; for (int i = 0; i < instanceListeners.length; i++) results[i] = instanceListeners[i]; results[instanceListeners.length] = listener; instanceListeners = results; } fireContainerEvent("addInstanceListener", listener); } /** * Add a Locale Encoding Mapping (see Sec 5.4 of Servlet spec 2.4) * * @param locale locale to map an encoding for * @param encoding encoding to be used for a give locale */ @Override public void addLocaleEncodingMappingParameter(String locale, String encoding){ getCharsetMapper().addCharsetMappingFromDeploymentDescriptor(locale, encoding); } /** * Add a message destination for this web application. * * @param md New message destination */ public void addMessageDestination(MessageDestination md) { synchronized (messageDestinations) { messageDestinations.put(md.getName(), md); } fireContainerEvent("addMessageDestination", md.getName()); } /** * Add a message destination reference for this web application. * * @param mdr New message destination reference */ public void addMessageDestinationRef (MessageDestinationRef mdr) { namingResources.addMessageDestinationRef(mdr); fireContainerEvent("addMessageDestinationRef", mdr.getName()); } /** * Add a new MIME mapping, replacing any existing mapping for * the specified extension. * * @param extension Filename extension being mapped * @param mimeType Corresponding MIME type */ @Override public void addMimeMapping(String extension, String mimeType) { synchronized (mimeMappings) { mimeMappings.put(extension.toLowerCase(Locale.ENGLISH), mimeType); } fireContainerEvent("addMimeMapping", extension); } /** * Add a new context initialization parameter. * * @param name Name of the new parameter * @param value Value of the new parameter * * @exception IllegalArgumentException if the name or value is missing, * or if this context initialization parameter has already been * registered */ @Override public void addParameter(String name, String value) { // Validate the proposed context initialization parameter if ((name == null) || (value == null)) throw new IllegalArgumentException (sm.getString("standardContext.parameter.required")); if (parameters.get(name) != null) throw new IllegalArgumentException (sm.getString("standardContext.parameter.duplicate", name)); // Add this parameter to our defined set synchronized (parameters) { parameters.put(name, value); } fireContainerEvent("addParameter", name); } /** * Add a security role reference for this web application. * * @param role Security role used in the application * @param link Actual security role to check for */ @Override public void addRoleMapping(String role, String link) { synchronized (roleMappings) { roleMappings.put(role, link); } fireContainerEvent("addRoleMapping", role); } /** * Add a new security role for this web application. * * @param role New security role */ @Override public void addSecurityRole(String role) { synchronized (securityRolesLock) { String results[] =new String[securityRoles.length + 1]; for (int i = 0; i < securityRoles.length; i++) results[i] = securityRoles[i]; results[securityRoles.length] = role; securityRoles = results; } fireContainerEvent("addSecurityRole", role); } /** * Add a new servlet mapping, replacing any existing mapping for * the specified pattern. * * @param pattern URL pattern to be mapped * @param name Name of the corresponding servlet to execute * * @exception IllegalArgumentException if the specified servlet name * is not known to this Context */ @Override public void addServletMapping(String pattern, String name) { addServletMapping(pattern, name, false); } /** * Add a new servlet mapping, replacing any existing mapping for * the specified pattern. * * @param pattern URL pattern to be mapped * @param name Name of the corresponding servlet to execute * @param jspWildCard true if name identifies the JspServlet * and pattern contains a wildcard; false otherwise * * @exception IllegalArgumentException if the specified servlet name * is not known to this Context */ @Override public void addServletMapping(String pattern, String name, boolean jspWildCard) { // Validate the proposed mapping if (findChild(name) == null) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.name", name)); String decodedPattern = adjustURLPattern(RequestUtil.URLDecode(pattern)); if (!validateURLPattern(decodedPattern)) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.pattern", decodedPattern)); // Add this mapping to our registered set synchronized (servletMappingsLock) { String name2 = servletMappings.get(decodedPattern); if (name2 != null) { // Don't allow more than one servlet on the same pattern Wrapper wrapper = (Wrapper) findChild(name2); wrapper.removeMapping(decodedPattern); } servletMappings.put(decodedPattern, name); } Wrapper wrapper = (Wrapper) findChild(name); wrapper.addMapping(decodedPattern); fireContainerEvent("addServletMapping", decodedPattern); } /** * Add a new watched resource to the set recognized by this Context. * * @param name New watched resource file name */ @Override public void addWatchedResource(String name) { synchronized (watchedResourcesLock) { String results[] = new String[watchedResources.length + 1]; for (int i = 0; i < watchedResources.length; i++) results[i] = watchedResources[i]; results[watchedResources.length] = name; watchedResources = results; } fireContainerEvent("addWatchedResource", name); } /** * Add a new welcome file to the set recognized by this Context. * * @param name New welcome file name */ @Override public void addWelcomeFile(String name) { synchronized (welcomeFilesLock) { // Welcome files from the application deployment descriptor // completely replace those from the default conf/web.xml file if (replaceWelcomeFiles) { fireContainerEvent(CLEAR_WELCOME_FILES_EVENT, null); welcomeFiles = new String[0]; setReplaceWelcomeFiles(false); } String results[] =new String[welcomeFiles.length + 1]; for (int i = 0; i < welcomeFiles.length; i++) results[i] = welcomeFiles[i]; results[welcomeFiles.length] = name; welcomeFiles = results; } if(this.getState().equals(LifecycleState.STARTED)) fireContainerEvent(ADD_WELCOME_FILE_EVENT, name); } /** * Add the classname of a LifecycleListener to be added to each * Wrapper appended to this Context. * * @param listener Java class name of a LifecycleListener class */ @Override public void addWrapperLifecycle(String listener) { synchronized (wrapperLifecyclesLock) { String results[] =new String[wrapperLifecycles.length + 1]; for (int i = 0; i < wrapperLifecycles.length; i++) results[i] = wrapperLifecycles[i]; results[wrapperLifecycles.length] = listener; wrapperLifecycles = results; } fireContainerEvent("addWrapperLifecycle", listener); } /** * Add the classname of a ContainerListener to be added to each * Wrapper appended to this Context. * * @param listener Java class name of a ContainerListener class */ @Override public void addWrapperListener(String listener) { synchronized (wrapperListenersLock) { String results[] =new String[wrapperListeners.length + 1]; for (int i = 0; i < wrapperListeners.length; i++) results[i] = wrapperListeners[i]; results[wrapperListeners.length] = listener; wrapperListeners = results; } fireContainerEvent("addWrapperListener", listener); } /** * Factory method to create and return a new Wrapper instance, of * the Java implementation class appropriate for this Context * implementation. The constructor of the instantiated Wrapper * will have been called, but no properties will have been set. */ @Override public Wrapper createWrapper() { Wrapper wrapper = null; if (wrapperClass != null) { try { wrapper = (Wrapper) wrapperClass.newInstance(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } else { wrapper = new StandardWrapper(); } synchronized (instanceListenersLock) { for (int i = 0; i < instanceListeners.length; i++) { try { Class<?> clazz = Class.forName(instanceListeners[i]); InstanceListener listener = (InstanceListener) clazz.newInstance(); wrapper.addInstanceListener(listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } } synchronized (wrapperLifecyclesLock) { for (int i = 0; i < wrapperLifecycles.length; i++) { try { Class<?> clazz = Class.forName(wrapperLifecycles[i]); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); wrapper.addLifecycleListener(listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } } synchronized (wrapperListenersLock) { for (int i = 0; i < wrapperListeners.length; i++) { try { Class<?> clazz = Class.forName(wrapperListeners[i]); ContainerListener listener = (ContainerListener) clazz.newInstance(); wrapper.addContainerListener(listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } } return (wrapper); } /** * Return the set of application listener class names configured * for this application. */ @Override public ApplicationListener[] findApplicationListeners() { return (applicationListeners); } /** * Return the set of application parameters for this application. */ @Override public ApplicationParameter[] findApplicationParameters() { synchronized (applicationParametersLock) { return (applicationParameters); } } /** * Return the security constraints for this web application. * If there are none, a zero-length array is returned. */ @Override public SecurityConstraint[] findConstraints() { return (constraints); } /** * Return the error page entry for the specified HTTP error code, * if any; otherwise return <code>null</code>. * * @param errorCode Error code to look up */ @Override public ErrorPage findErrorPage(int errorCode) { return statusPages.get(Integer.valueOf(errorCode)); } /** * Return the error page entry for the specified Java exception type, * if any; otherwise return <code>null</code>. * * @param exceptionType Exception type to look up */ @Override public ErrorPage findErrorPage(String exceptionType) { synchronized (exceptionPages) { return (exceptionPages.get(exceptionType)); } } /** * Return the set of defined error pages for all specified error codes * and exception types. */ @Override public ErrorPage[] findErrorPages() { synchronized(exceptionPages) { synchronized(statusPages) { ErrorPage results1[] = new ErrorPage[exceptionPages.size()]; results1 = exceptionPages.values().toArray(results1); ErrorPage results2[] = new ErrorPage[statusPages.size()]; results2 = statusPages.values().toArray(results2); ErrorPage results[] = new ErrorPage[results1.length + results2.length]; for (int i = 0; i < results1.length; i++) results[i] = results1[i]; for (int i = results1.length; i < results.length; i++) results[i] = results2[i - results1.length]; return (results); } } } /** * Return the filter definition for the specified filter name, if any; * otherwise return <code>null</code>. * * @param filterName Filter name to look up */ @Override public FilterDef findFilterDef(String filterName) { synchronized (filterDefs) { return (filterDefs.get(filterName)); } } /** * Return the set of defined filters for this Context. */ @Override public FilterDef[] findFilterDefs() { synchronized (filterDefs) { FilterDef results[] = new FilterDef[filterDefs.size()]; return (filterDefs.values().toArray(results)); } } /** * Return the set of filter mappings for this Context. */ @Override public FilterMap[] findFilterMaps() { return filterMaps.asArray(); } /** * Return the set of InstanceListener classes that will be added to * newly created Wrappers automatically. */ @Override public String[] findInstanceListeners() { synchronized (instanceListenersLock) { return (instanceListeners); } } /** * Return the message destination with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired message destination */ public MessageDestination findMessageDestination(String name) { synchronized (messageDestinations) { return (messageDestinations.get(name)); } } /** * Return the set of defined message destinations for this web * application. If none have been defined, a zero-length array * is returned. */ public MessageDestination[] findMessageDestinations() { synchronized (messageDestinations) { MessageDestination results[] = new MessageDestination[messageDestinations.size()]; return (messageDestinations.values().toArray(results)); } } /** * Return the message destination ref with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired message destination ref */ public MessageDestinationRef findMessageDestinationRef(String name) { return namingResources.findMessageDestinationRef(name); } /** * Return the set of defined message destination refs for this web * application. If none have been defined, a zero-length array * is returned. */ public MessageDestinationRef[] findMessageDestinationRefs() { return namingResources.findMessageDestinationRefs(); } /** * Return the MIME type to which the specified extension is mapped, * if any; otherwise return <code>null</code>. * * @param extension Extension to map to a MIME type */ @Override public String findMimeMapping(String extension) { return (mimeMappings.get(extension.toLowerCase(Locale.ENGLISH))); } /** * Return the extensions for which MIME mappings are defined. If there * are none, a zero-length array is returned. */ @Override public String[] findMimeMappings() { synchronized (mimeMappings) { String results[] = new String[mimeMappings.size()]; return (mimeMappings.keySet().toArray(results)); } } /** * Return the value for the specified context initialization * parameter name, if any; otherwise return <code>null</code>. * * @param name Name of the parameter to return */ @Override public String findParameter(String name) { synchronized (parameters) { return (parameters.get(name)); } } /** * Return the names of all defined context initialization parameters * for this Context. If no parameters are defined, a zero-length * array is returned. */ @Override public String[] findParameters() { synchronized (parameters) { String results[] = new String[parameters.size()]; return (parameters.keySet().toArray(results)); } } /** * For the given security role (as used by an application), return the * corresponding role name (as defined by the underlying Realm) if there * is one. Otherwise, return the specified role unchanged. * * @param role Security role to map */ @Override public String findRoleMapping(String role) { String realRole = null; synchronized (roleMappings) { realRole = roleMappings.get(role); } if (realRole != null) return (realRole); else return (role); } /** * Return <code>true</code> if the specified security role is defined * for this application; otherwise return <code>false</code>. * * @param role Security role to verify */ @Override public boolean findSecurityRole(String role) { synchronized (securityRolesLock) { for (int i = 0; i < securityRoles.length; i++) { if (role.equals(securityRoles[i])) return (true); } } return (false); } /** * Return the security roles defined for this application. If none * have been defined, a zero-length array is returned. */ @Override public String[] findSecurityRoles() { synchronized (securityRolesLock) { return (securityRoles); } } /** * Return the servlet name mapped by the specified pattern (if any); * otherwise return <code>null</code>. * * @param pattern Pattern for which a mapping is requested */ @Override public String findServletMapping(String pattern) { synchronized (servletMappingsLock) { return (servletMappings.get(pattern)); } } /** * Return the patterns of all defined servlet mappings for this * Context. If no mappings are defined, a zero-length array is returned. */ @Override public String[] findServletMappings() { synchronized (servletMappingsLock) { String results[] = new String[servletMappings.size()]; return (servletMappings.keySet().toArray(results)); } } /** * Return the context-relative URI of the error page for the specified * HTTP status code, if any; otherwise return <code>null</code>. * * @param status HTTP status code to look up */ @Override public String findStatusPage(int status) { ErrorPage errorPage = statusPages.get(Integer.valueOf(status)); if (errorPage!=null) { return errorPage.getLocation(); } return null; } /** * Return the set of HTTP status codes for which error pages have * been specified. If none are specified, a zero-length array * is returned. */ @Override public int[] findStatusPages() { synchronized (statusPages) { int results[] = new int[statusPages.size()]; Iterator<Integer> elements = statusPages.keySet().iterator(); int i = 0; while (elements.hasNext()) results[i++] = elements.next().intValue(); return (results); } } /** * Return <code>true</code> if the specified welcome file is defined * for this Context; otherwise return <code>false</code>. * * @param name Welcome file to verify */ @Override public boolean findWelcomeFile(String name) { synchronized (welcomeFilesLock) { for (int i = 0; i < welcomeFiles.length; i++) { if (name.equals(welcomeFiles[i])) return (true); } } return (false); } /** * Return the set of watched resources for this Context. If none are * defined, a zero length array will be returned. */ @Override public String[] findWatchedResources() { synchronized (watchedResourcesLock) { return watchedResources; } } /** * Return the set of welcome files defined for this Context. If none are * defined, a zero-length array is returned. */ @Override public String[] findWelcomeFiles() { synchronized (welcomeFilesLock) { return (welcomeFiles); } } /** * Return the set of LifecycleListener classes that will be added to * newly created Wrappers automatically. */ @Override public String[] findWrapperLifecycles() { synchronized (wrapperLifecyclesLock) { return (wrapperLifecycles); } } /** * Return the set of ContainerListener classes that will be added to * newly created Wrappers automatically. */ @Override public String[] findWrapperListeners() { synchronized (wrapperListenersLock) { return (wrapperListeners); } } /** * Reload this web application, if reloading is supported. * <p> * <b>IMPLEMENTATION NOTE</b>: This method is designed to deal with * reloads required by changes to classes in the underlying repositories * of our class loader and changes to the web.xml file. It does not handle * changes to any context.xml file. If the context.xml has changed, you * should stop this Context and create (and start) a new Context instance * instead. Note that there is additional code in * <code>CoyoteAdapter#postParseRequest()</code> to handle mapping requests * to paused Contexts. * * @exception IllegalStateException if the <code>reloadable</code> * property is set to <code>false</code>. */ @Override public synchronized void reload() { // Validate our current component state if (!getState().isAvailable()) throw new IllegalStateException (sm.getString("standardContext.notStarted", getName())); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingStarted", getName())); // Stop accepting requests temporarily. setPaused(true); try { stop(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); } try { start(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); } setPaused(false); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingCompleted", getName())); } /** * Remove the specified application listener class from the set of * listeners for this application. * * @param listener Java class name of the listener to be removed */ @Override public void removeApplicationListener(String listener) { synchronized (applicationListenersLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < applicationListeners.length; i++) { if (applicationListeners[i].getClassName().equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; ApplicationListener results[] = new ApplicationListener[applicationListeners.length - 1]; for (int i = 0; i < applicationListeners.length; i++) { if (i != n) results[j++] = applicationListeners[i]; } applicationListeners = results; } // Inform interested listeners fireContainerEvent("removeApplicationListener", listener); // FIXME - behavior if already started? } /** * Remove the application parameter with the specified name from * the set for this application. * * @param name Name of the application parameter to remove */ @Override public void removeApplicationParameter(String name) { synchronized (applicationParametersLock) { // Make sure this parameter is currently present int n = -1; for (int i = 0; i < applicationParameters.length; i++) { if (name.equals(applicationParameters[i].getName())) { n = i; break; } } if (n < 0) return; // Remove the specified parameter int j = 0; ApplicationParameter results[] = new ApplicationParameter[applicationParameters.length - 1]; for (int i = 0; i < applicationParameters.length; i++) { if (i != n) results[j++] = applicationParameters[i]; } applicationParameters = results; } // Inform interested listeners fireContainerEvent("removeApplicationParameter", name); } /** * Add a child Container, only if the proposed child is an implementation * of Wrapper. * * @param child Child container to be added * * @exception IllegalArgumentException if the proposed container is * not an implementation of Wrapper */ @Override public void removeChild(Container child) { if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } super.removeChild(child); } /** * Remove the specified security constraint from this web application. * * @param constraint Constraint to be removed */ @Override public void removeConstraint(SecurityConstraint constraint) { synchronized (constraintsLock) { // Make sure this constraint is currently present int n = -1; for (int i = 0; i < constraints.length; i++) { if (constraints[i].equals(constraint)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; SecurityConstraint results[] = new SecurityConstraint[constraints.length - 1]; for (int i = 0; i < constraints.length; i++) { if (i != n) results[j++] = constraints[i]; } constraints = results; } // Inform interested listeners fireContainerEvent("removeConstraint", constraint); } /** * Remove the error page for the specified error code or * Java language exception, if it exists; otherwise, no action is taken. * * @param errorPage The error page definition to be removed */ @Override public void removeErrorPage(ErrorPage errorPage) { String exceptionType = errorPage.getExceptionType(); if (exceptionType != null) { synchronized (exceptionPages) { exceptionPages.remove(exceptionType); } } else { synchronized (statusPages) { statusPages.remove(Integer.valueOf(errorPage.getErrorCode())); } } fireContainerEvent("removeErrorPage", errorPage); } /** * Remove the specified filter definition from this Context, if it exists; * otherwise, no action is taken. * * @param filterDef Filter definition to be removed */ @Override public void removeFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.remove(filterDef.getFilterName()); } fireContainerEvent("removeFilterDef", filterDef); } /** * Remove a filter mapping from this Context. * * @param filterMap The filter mapping to be removed */ @Override public void removeFilterMap(FilterMap filterMap) { filterMaps.remove(filterMap); // Inform interested listeners fireContainerEvent("removeFilterMap", filterMap); } /** * Remove a class name from the set of InstanceListener classes that * will be added to newly created Wrappers. * * @param listener Class name of an InstanceListener class to be removed */ @Override public void removeInstanceListener(String listener) { synchronized (instanceListenersLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < instanceListeners.length; i++) { if (instanceListeners[i].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[instanceListeners.length - 1]; for (int i = 0; i < instanceListeners.length; i++) { if (i != n) results[j++] = instanceListeners[i]; } instanceListeners = results; } // Inform interested listeners fireContainerEvent("removeInstanceListener", listener); } /** * Remove any message destination with the specified name. * * @param name Name of the message destination to remove */ public void removeMessageDestination(String name) { synchronized (messageDestinations) { messageDestinations.remove(name); } fireContainerEvent("removeMessageDestination", name); } /** * Remove any message destination ref with the specified name. * * @param name Name of the message destination ref to remove */ public void removeMessageDestinationRef(String name) { namingResources.removeMessageDestinationRef(name); fireContainerEvent("removeMessageDestinationRef", name); } /** * Remove the MIME mapping for the specified extension, if it exists; * otherwise, no action is taken. * * @param extension Extension to remove the mapping for */ @Override public void removeMimeMapping(String extension) { synchronized (mimeMappings) { mimeMappings.remove(extension); } fireContainerEvent("removeMimeMapping", extension); } /** * Remove the context initialization parameter with the specified * name, if it exists; otherwise, no action is taken. * * @param name Name of the parameter to remove */ @Override public void removeParameter(String name) { synchronized (parameters) { parameters.remove(name); } fireContainerEvent("removeParameter", name); } /** * Remove any security role reference for the specified name * * @param role Security role (as used in the application) to remove */ @Override public void removeRoleMapping(String role) { synchronized (roleMappings) { roleMappings.remove(role); } fireContainerEvent("removeRoleMapping", role); } /** * Remove any security role with the specified name. * * @param role Security role to remove */ @Override public void removeSecurityRole(String role) { synchronized (securityRolesLock) { // Make sure this security role is currently present int n = -1; for (int i = 0; i < securityRoles.length; i++) { if (role.equals(securityRoles[i])) { n = i; break; } } if (n < 0) return; // Remove the specified security role int j = 0; String results[] = new String[securityRoles.length - 1]; for (int i = 0; i < securityRoles.length; i++) { if (i != n) results[j++] = securityRoles[i]; } securityRoles = results; } // Inform interested listeners fireContainerEvent("removeSecurityRole", role); } /** * Remove any servlet mapping for the specified pattern, if it exists; * otherwise, no action is taken. * * @param pattern URL pattern of the mapping to remove */ @Override public void removeServletMapping(String pattern) { String name = null; synchronized (servletMappingsLock) { name = servletMappings.remove(pattern); } Wrapper wrapper = (Wrapper) findChild(name); if( wrapper != null ) { wrapper.removeMapping(pattern); } fireContainerEvent("removeServletMapping", pattern); } /** * Remove the specified watched resource name from the list associated * with this Context. * * @param name Name of the watched resource to be removed */ @Override public void removeWatchedResource(String name) { synchronized (watchedResourcesLock) { // Make sure this watched resource is currently present int n = -1; for (int i = 0; i < watchedResources.length; i++) { if (watchedResources[i].equals(name)) { n = i; break; } } if (n < 0) return; // Remove the specified watched resource int j = 0; String results[] = new String[watchedResources.length - 1]; for (int i = 0; i < watchedResources.length; i++) { if (i != n) results[j++] = watchedResources[i]; } watchedResources = results; } fireContainerEvent("removeWatchedResource", name); } /** * Remove the specified welcome file name from the list recognized * by this Context. * * @param name Name of the welcome file to be removed */ @Override public void removeWelcomeFile(String name) { synchronized (welcomeFilesLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < welcomeFiles.length; i++) { if (welcomeFiles[i].equals(name)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[welcomeFiles.length - 1]; for (int i = 0; i < welcomeFiles.length; i++) { if (i != n) results[j++] = welcomeFiles[i]; } welcomeFiles = results; } // Inform interested listeners if(this.getState().equals(LifecycleState.STARTED)) fireContainerEvent(REMOVE_WELCOME_FILE_EVENT, name); } /** * Remove a class name from the set of LifecycleListener classes that * will be added to newly created Wrappers. * * @param listener Class name of a LifecycleListener class to be removed */ @Override public void removeWrapperLifecycle(String listener) { synchronized (wrapperLifecyclesLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < wrapperLifecycles.length; i++) { if (wrapperLifecycles[i].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[wrapperLifecycles.length - 1]; for (int i = 0; i < wrapperLifecycles.length; i++) { if (i != n) results[j++] = wrapperLifecycles[i]; } wrapperLifecycles = results; } // Inform interested listeners fireContainerEvent("removeWrapperLifecycle", listener); } /** * Remove a class name from the set of ContainerListener classes that * will be added to newly created Wrappers. * * @param listener Class name of a ContainerListener class to be removed */ @Override public void removeWrapperListener(String listener) { synchronized (wrapperListenersLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < wrapperListeners.length; i++) { if (wrapperListeners[i].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[wrapperListeners.length - 1]; for (int i = 0; i < wrapperListeners.length; i++) { if (i != n) results[j++] = wrapperListeners[i]; } wrapperListeners = results; } // Inform interested listeners fireContainerEvent("removeWrapperListener", listener); } /** * Gets the cumulative processing times of all servlets in this * StandardContext. * * @return Cumulative processing times of all servlets in this * StandardContext */ public long getProcessingTime() { long result = 0; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { result += ((StandardWrapper)children[i]).getProcessingTime(); } } return result; } /** * Gets the maximum processing time of all servlets in this * StandardContext. * * @return Maximum processing time of all servlets in this * StandardContext */ public long getMaxTime() { long result = 0; long time; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { time = ((StandardWrapper)children[i]).getMaxTime(); if (time > result) result = time; } } return result; } /** * Gets the minimum processing time of all servlets in this * StandardContext. * * @return Minimum processing time of all servlets in this * StandardContext */ public long getMinTime() { long result = -1; long time; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { time = ((StandardWrapper)children[i]).getMinTime(); if (result < 0 || time < result) result = time; } } return result; } /** * Gets the cumulative request count of all servlets in this * StandardContext. * * @return Cumulative request count of all servlets in this * StandardContext */ public int getRequestCount() { int result = 0; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { result += ((StandardWrapper)children[i]).getRequestCount(); } } return result; } /** * Gets the cumulative error count of all servlets in this * StandardContext. * * @return Cumulative error count of all servlets in this * StandardContext */ public int getErrorCount() { int result = 0; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { result += ((StandardWrapper)children[i]).getErrorCount(); } } return result; } /** * Return the real path for a given virtual path, if possible; otherwise * return <code>null</code>. * * @param path The path to the desired resource */ @Override public String getRealPath(String path) { if (resources != null) { return resources.getResource(path).getCanonicalPath(); } return null; } /** * hook to register that we need to scan for security annotations. * @param wrapper The wrapper for the Servlet that was added */ public ServletRegistration.Dynamic dynamicServletAdded(Wrapper wrapper) { Servlet s = wrapper.getServlet(); if (s != null && createdServlets.contains(s)) { // Mark the wrapper to indicate annotations need to be scanned wrapper.setServletSecurityAnnotationScanRequired(true); } return new ApplicationServletRegistration(wrapper, this); } /** * hook to track which registrations need annotation scanning * @param servlet */ public void dynamicServletCreated(Servlet servlet) { createdServlets.add(servlet); } /** * A helper class to manage the filter mappings in a Context. */ private static final class ContextFilterMaps { private final Object lock = new Object(); /** * The set of filter mappings for this application, in the order they * were defined in the deployment descriptor with additional mappings * added via the {@link ServletContext} possibly both before and after * those defined in the deployment descriptor. */ private FilterMap[] array = new FilterMap[0]; /** * Filter mappings added via {@link ServletContext} may have to be * inserted before the mappings in the deployment descriptor but must be * inserted in the order the {@link ServletContext} methods are called. * This isn't an issue for the mappings added after the deployment * descriptor - they are just added to the end - but correctly the * adding mappings before the deployment descriptor mappings requires * knowing where the last 'before' mapping was added. */ private int insertPoint = 0; /** * Return the set of filter mappings. */ public FilterMap[] asArray() { synchronized (lock) { return array; } } /** * Add a filter mapping at the end of the current set of filter * mappings. * * @param filterMap * The filter mapping to be added */ public void add(FilterMap filterMap) { synchronized (lock) { FilterMap results[] = Arrays.copyOf(array, array.length + 1); results[array.length] = filterMap; array = results; } } /** * Add a filter mapping before the mappings defined in the deployment * descriptor but after any other mappings added via this method. * * @param filterMap * The filter mapping to be added */ public void addBefore(FilterMap filterMap) { synchronized (lock) { FilterMap results[] = new FilterMap[array.length + 1]; System.arraycopy(array, 0, results, 0, insertPoint); System.arraycopy(array, insertPoint, results, insertPoint + 1, array.length - insertPoint); results[insertPoint] = filterMap; array = results; insertPoint++; } } /** * Remove a filter mapping. * * @param filterMap The filter mapping to be removed */ public void remove(FilterMap filterMap) { synchronized (lock) { // Make sure this filter mapping is currently present int n = -1; for (int i = 0; i < array.length; i++) { if (array[i] == filterMap) { n = i; break; } } if (n < 0) return; // Remove the specified filter mapping FilterMap results[] = new FilterMap[array.length - 1]; System.arraycopy(array, 0, results, 0, n); System.arraycopy(array, n + 1, results, n, (array.length - 1) - n); array = results; if (n < insertPoint) { insertPoint--; } } } } // --------------------------------------------------------- Public Methods /** * Configure and initialize the set of filters for this Context. * Return <code>true</code> if all filter initialization completed * successfully, or <code>false</code> otherwise. */ public boolean filterStart() { if (getLogger().isDebugEnabled()) getLogger().debug("Starting filters"); // Instantiate and record a FilterConfig for each defined filter boolean ok = true; synchronized (filterConfigs) { filterConfigs.clear(); Iterator<String> names = filterDefs.keySet().iterator(); while (names.hasNext()) { String name = names.next(); if (getLogger().isDebugEnabled()) getLogger().debug(" Starting filter '" + name + "'"); ApplicationFilterConfig filterConfig = null; try { filterConfig = new ApplicationFilterConfig(this, filterDefs.get(name)); filterConfigs.put(name, filterConfig); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; } } } return (ok); } /** * Finalize and release the set of filters for this Context. * Return <code>true</code> if all filter finalization completed * successfully, or <code>false</code> otherwise. */ public boolean filterStop() { if (getLogger().isDebugEnabled()) getLogger().debug("Stopping filters"); // Release all Filter and FilterConfig instances synchronized (filterConfigs) { Iterator<String> names = filterConfigs.keySet().iterator(); while (names.hasNext()) { String name = names.next(); if (getLogger().isDebugEnabled()) getLogger().debug(" Stopping filter '" + name + "'"); ApplicationFilterConfig filterConfig = filterConfigs.get(name); filterConfig.release(); } filterConfigs.clear(); } return (true); } /** * Find and return the initialized <code>FilterConfig</code> for the * specified filter name, if any; otherwise return <code>null</code>. * * @param name Name of the desired filter */ public FilterConfig findFilterConfig(String name) { return (filterConfigs.get(name)); } /** * Configure the set of instantiated application event listeners * for this Context. Return <code>true</code> if all listeners wre * initialized successfully, or <code>false</code> otherwise. */ public boolean listenerStart() { if (log.isDebugEnabled()) log.debug("Configuring application event listeners"); // Instantiate the required listeners ApplicationListener listeners[] = findApplicationListeners(); Object results[] = new Object[listeners.length]; boolean ok = true; Set<Object> noPluggabilityListeners = new HashSet<>(); for (int i = 0; i < results.length; i++) { if (getLogger().isDebugEnabled()) getLogger().debug(" Configuring event listener class '" + listeners[i] + "'"); try { ApplicationListener listener = listeners[i]; results[i] = instanceManager.newInstance( listener.getClassName()); if (listener.isPluggabilityBlocked()) { noPluggabilityListeners.add(results[i]); } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; } } if (!ok) { getLogger().error(sm.getString("standardContext.applicationSkipped")); return (false); } // Sort listeners in two arrays ArrayList<Object> eventListeners = new ArrayList<>(); ArrayList<Object> lifecycleListeners = new ArrayList<>(); for (int i = 0; i < results.length; i++) { if ((results[i] instanceof ServletContextAttributeListener) || (results[i] instanceof ServletRequestAttributeListener) || (results[i] instanceof ServletRequestListener) || (results[i] instanceof HttpSessionIdListener) || (results[i] instanceof HttpSessionAttributeListener)) { eventListeners.add(results[i]); } if ((results[i] instanceof ServletContextListener) || (results[i] instanceof HttpSessionListener)) { lifecycleListeners.add(results[i]); } } // Listener instances may have been added directly to this Context by // ServletContextInitializers and other code via the pluggability APIs. // Put them these listeners after the ones defined in web.xml and/or // annotations then overwrite the list of instances with the new, full // list. for (Object eventListener: getApplicationEventListeners()) { eventListeners.add(eventListener); } setApplicationEventListeners(eventListeners.toArray()); for (Object lifecycleListener: getApplicationLifecycleListeners()) { lifecycleListeners.add(lifecycleListener); if (lifecycleListener instanceof ServletContextListener) { noPluggabilityListeners.add(lifecycleListener); } } setApplicationLifecycleListeners(lifecycleListeners.toArray()); // Send application start events if (getLogger().isDebugEnabled()) getLogger().debug("Sending application start events"); // Ensure context is not null getServletContext(); context.setNewServletContextListenerAllowed(false); Object instances[] = getApplicationLifecycleListeners(); if (instances == null || instances.length == 0) { return ok; } ServletContextEvent event = new ServletContextEvent(getServletContext()); ServletContextEvent tldEvent = null; if (noPluggabilityListeners.size() > 0) { tldEvent = new ServletContextEvent(new NoPluggabilityServletContext( getServletContext())); } for (int i = 0; i < instances.length; i++) { if (instances[i] == null) continue; if (!(instances[i] instanceof ServletContextListener)) continue; ServletContextListener listener = (ServletContextListener) instances[i]; try { fireContainerEvent("beforeContextInitialized", listener); if (noPluggabilityListeners.contains(listener)) { listener.contextInitialized(tldEvent); } else { listener.contextInitialized(event); } fireContainerEvent("afterContextInitialized", listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; } } return (ok); } /** * Send an application stop event to all interested listeners. * Return <code>true</code> if all events were sent successfully, * or <code>false</code> otherwise. */ public boolean listenerStop() { if (log.isDebugEnabled()) log.debug("Sending application stop events"); boolean ok = true; Object listeners[] = getApplicationLifecycleListeners(); if (listeners != null && listeners.length > 0) { ServletContextEvent event = new ServletContextEvent(getServletContext()); for (int i = 0; i < listeners.length; i++) { int j = (listeners.length - 1) - i; if (listeners[j] == null) continue; if (listeners[j] instanceof ServletContextListener) { ServletContextListener listener = (ServletContextListener) listeners[j]; try { fireContainerEvent("beforeContextDestroyed", listener); listener.contextDestroyed(event); fireContainerEvent("afterContextDestroyed", listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; } } try { getInstanceManager().destroyInstance(listeners[j]); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; } } } // Annotation processing listeners = getApplicationEventListeners(); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { int j = (listeners.length - 1) - i; if (listeners[j] == null) continue; try { getInstanceManager().destroyInstance(listeners[j]); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; } } } setApplicationEventListeners(null); setApplicationLifecycleListeners(null); return (ok); } /** * Allocate resources, including proxy. * Return <code>true</code> if initialization was successfull, * or <code>false</code> otherwise. */ public boolean resourcesStart() throws LifecycleException { boolean ok = true; resources.setAllowLinking(isAllowLinking()); resources.setCachingAllowed(isCachingAllowed()); resources.setCacheTtl(getCacheTTL()); resources.setCacheMaxSize(getCacheMaxSize()); resources.setCacheMaxObjectSize(getCacheObjectMaxSize()); // May have been started (but not fully configured) in init() so no need // to start the resources if they are already available if (!resources.getState().isAvailable()) { resources.start(); } if (effectiveMajorVersion >=3 && addWebinfClassesResources) { WebResource webinfClassesResource = resources.getResource( "/WEB-INF/classes/META-INF/resources"); if (webinfClassesResource.isDirectory()) { getResources().createWebResourceSet( WebResourceRoot.ResourceSetType.RESOURCE_JAR, webinfClassesResource.getURL(), "/", "/"); } } return ok; } /** * Deallocate resources and destroy proxy. */ public boolean resourcesStop() { boolean ok = true; Lock writeLock = resourcesLock.writeLock(); writeLock.lock(); try { if (resources != null) { resources.stop(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; } finally { writeLock.unlock(); } return ok; } /** * Load and initialize all servlets marked "load on startup" in the * web application deployment descriptor. * * @param children Array of wrappers for all currently defined * servlets (including those not declared load on startup) */ public void loadOnStartup(Container children[]) { // Collect "load on startup" servlets that need to be initialized TreeMap<Integer, ArrayList<Wrapper>> map = new TreeMap<>(); for (int i = 0; i < children.length; i++) { Wrapper wrapper = (Wrapper) children[i]; int loadOnStartup = wrapper.getLoadOnStartup(); if (loadOnStartup < 0) continue; Integer key = Integer.valueOf(loadOnStartup); ArrayList<Wrapper> list = map.get(key); if (list == null) { list = new ArrayList<>(); map.put(key, list); } list.add(wrapper); } // Load the collected "load on startup" servlets for (ArrayList<Wrapper> list : map.values()) { for (Wrapper wrapper : list) { try { wrapper.load(); } catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup } } } } /** * Start this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void startInternal() throws LifecycleException { if(log.isDebugEnabled()) log.debug("Starting " + getBaseName()); // Send j2ee.state.starting notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setConfigured(false); boolean ok = true; // Currently this is effectively a NO-OP but needs to be called to // ensure the NamingResources follows the correct lifecycle if (namingResources != null) { namingResources.start(); } // Add missing components as necessary if (getResources() == null) { // (1) Required by Loader if (log.isDebugEnabled()) log.debug("Configuring default Resources"); try { setResources(new StandardRoot(this)); } catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; } } if (ok) { if (!resourcesStart()) { log.error( "Error in resourceStart()"); ok = false; } } if (getLoader() == null) { WebappLoader webappLoader = new WebappLoader(getParentClassLoader()); webappLoader.setDelegate(getDelegate()); setLoader(webappLoader); } // Initialize character set mapper getCharsetMapper(); // Post work directory postWorkDirectory(); // Validate required extensions boolean dependencyCheck = true; try { dependencyCheck = ExtensionValidator.validateApplication (getResources(), this); } catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; } if (!dependencyCheck) { // do not make application available if depency check fails ok = false; } // Reading the "catalina.useNaming" environment variable String useNamingProperty = System.getProperty("catalina.useNaming"); if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) { useNaming = false; } if (ok && isUseNaming()) { if (getNamingContextListener() == null) { NamingContextListener ncl = new NamingContextListener(); ncl.setName(getNamingContextName()); ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite()); addLifecycleListener(ncl); setNamingContextListener(ncl); } } // Standard container startup if (log.isDebugEnabled()) log.debug("Processing standard container startup"); // Binding thread ClassLoader oldCCL = bindThread(); try { if (ok) { // Start our subordinate components, if any Loader loader = getLoader(); if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); // since the loader just started, the webapp classloader is now // created. setClassLoaderProperty("antiJARLocking", getAntiJARLocking()); setClassLoaderProperty("clearReferencesStatic", getClearReferencesStatic()); setClassLoaderProperty("clearReferencesStopThreads", getClearReferencesStopThreads()); setClassLoaderProperty("clearReferencesStopTimerThreads", getClearReferencesStopTimerThreads()); setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread", getClearReferencesHttpClientKeepAliveThread()); // By calling unbindThread and bindThread in a row, we setup the // current Thread CCL to be the webapp classloader unbindThread(oldCCL); oldCCL = bindThread(); // Initialize logger again. Other components might have used it // too early, so it should be reset. logger = null; getLogger(); Cluster cluster = getClusterInternal(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); // Notify our interested LifecycleListeners fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null); // Start our child containers, if not already started for (Container child : findChildren()) { if (!child.getState().isAvailable()) { child.start(); } } // Start the Valves in our pipeline (including the basic), // if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).start(); } // Acquire clustered manager Manager contextManager = null; Manager manager = getManager(); if (manager == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable))); } if ( (getCluster() != null) && distributable) { try { contextManager = getCluster().createManager(getName()); } catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; } } else { contextManager = new StandardManager(); } } // Configure default manager if none was specified if (contextManager != null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName())); } setManager(contextManager); } if (manager!=null && (getCluster() != null) && distributable) { //let the cluster know that there is a context that is distributable //and that it has its own manager getCluster().registerManager(manager); } } } finally { // Unbinding thread unbindThread(oldCCL); } if (!getConfigured()) { log.error( "Error getConfigured"); ok = false; } // We put the resources into the servlet context if (ok) getServletContext().setAttribute (Globals.RESOURCES_ATTR, getResources()); // Binding thread oldCCL = bindThread(); if (ok ) { if (getInstanceManager() == null) { javax.naming.Context context = null; if (isUseNaming() && getNamingContextListener() != null) { context = getNamingContextListener().getEnvContext(); } Map<String, Map<String, String>> injectionMap = buildInjectionMap( getIgnoreAnnotations() ? new NamingResources(): getNamingResources()); setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader())); getServletContext().setAttribute( InstanceManager.class.getName(), getInstanceManager()); } } try { // Create context attributes that will be required if (ok) { getServletContext().setAttribute( JarScanner.class.getName(), getJarScanner()); } // Set up the context init params mergeParameters(); // Call ServletContainerInitializers for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) { try { entry.getKey().onStartup(entry.getValue(), getServletContext()); } catch (ServletException e) { log.error(sm.getString("standardContext.sciFail"), e); ok = false; break; } } // Configure and call application event listeners if (ok) { if (!listenerStart()) { log.error( "Error listenerStart"); ok = false; } } try { // Start manager Manager manager = getManager(); if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) getManager()).start(); } } catch(Exception e) { log.error("Error manager.start()", e); ok = false; } // Configure and call application filters if (ok) { if (!filterStart()) { log.error("Error filterStart"); ok = false; } } // Load and initialize all "load on startup" servlets if (ok) { loadOnStartup(findChildren()); } // Start ContainerBackgroundProcessor thread super.threadStart(); } finally { // Unbinding thread unbindThread(oldCCL); } // Set available status depending upon startup success if (ok) { if (log.isDebugEnabled()) log.debug("Starting completed"); } else { log.error(sm.getString("standardContext.startFailed", getName())); } startTime=System.currentTimeMillis(); // Send j2ee.state.running notification if (ok && (this.getObjectName() != null)) { Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Close all JARs right away to avoid always opening a peak number // of files on startup if (getLoader() instanceof WebappLoader) { ((WebappLoader) getLoader()).closeJARs(true); } // Reinitializing if something went wrong if (!ok) { setState(LifecycleState.FAILED); } else { setState(LifecycleState.STARTING); } } private void setClassLoaderProperty(String name, boolean value) { ClassLoader cl = getLoader().getClassLoader(); if (!IntrospectionUtils.setProperty(cl, name, Boolean.toString(value))) { // Failed to set log.info(sm.getString( "standardContext.webappClassLoader.missingProperty", name, Boolean.toString(value))); } } private Map<String, Map<String, String>> buildInjectionMap(NamingResources namingResources) { Map<String, Map<String, String>> injectionMap = new HashMap<>(); for (Injectable resource: namingResources.findLocalEjbs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findEjbs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findEnvironments()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findMessageDestinationRefs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findResourceEnvRefs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findResources()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findServices()) { addInjectionTarget(resource, injectionMap); } return injectionMap; } private void addInjectionTarget(Injectable resource, Map<String, Map<String, String>> injectionMap) { List<InjectionTarget> injectionTargets = resource.getInjectionTargets(); if (injectionTargets != null && injectionTargets.size() > 0) { String jndiName = resource.getName(); for (InjectionTarget injectionTarget: injectionTargets) { String clazz = injectionTarget.getTargetClass(); Map<String, String> injections = injectionMap.get(clazz); if (injections == null) { injections = new HashMap<>(); injectionMap.put(clazz, injections); } injections.put(injectionTarget.getTargetName(), jndiName); } } } /** * Merge the context initialization parameters specified in the application * deployment descriptor with the application parameters described in the * server configuration, respecting the <code>override</code> property of * the application parameters appropriately. */ private void mergeParameters() { Map<String,String> mergedParams = new HashMap<>(); String names[] = findParameters(); for (int i = 0; i < names.length; i++) { mergedParams.put(names[i], findParameter(names[i])); } ApplicationParameter params[] = findApplicationParameters(); for (int i = 0; i < params.length; i++) { if (params[i].getOverride()) { if (mergedParams.get(params[i].getName()) == null) { mergedParams.put(params[i].getName(), params[i].getValue()); } } else { mergedParams.put(params[i].getName(), params[i].getValue()); } } ServletContext sc = getServletContext(); for (Map.Entry<String,String> entry : mergedParams.entrySet()) { sc.setInitParameter(entry.getKey(), entry.getValue()); } } /** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { // Send j2ee.state.stopping notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setState(LifecycleState.STOPPING); // Binding thread ClassLoader oldCCL = bindThread(); try { // Stop our child containers, if any final Container[] children = findChildren(); ClassLoader old = bindThread(); try { // Stop ContainerBackgroundProcessor thread threadStop(); for (int i = 0; i < children.length; i++) { children[i].stop(); } // Stop our filters filterStop(); Manager manager = getManager(); if (manager != null && manager instanceof Lifecycle && ((Lifecycle) manager).getState().isAvailable()) { ((Lifecycle) manager).stop(); } // Stop our application listeners listenerStop(); } finally{ unbindThread(old); } // Finalize our character set mapper setCharsetMapper(null); // Normal container shutdown processing if (log.isDebugEnabled()) log.debug("Processing standard container shutdown"); // JNDI resources are unbound in CONFIGURE_STOP_EVENT so stop // naming resoucres before they are unbound since NamingResoucres // does a JNDI lookup to retrieve the resource. This needs to be // after the application has finished with the resource if (namingResources != null) { namingResources.stop(); } fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Clear all application-originated servlet context attributes if (context != null) context.clearAttributes(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } Cluster cluster = getClusterInternal(); if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } Loader loader = getLoader(); if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } // Stop resources resourcesStop(); } finally { // Unbinding thread unbindThread(oldCCL); } // Send j2ee.state.stopped notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Reset application context context = null; // This object will no longer be visible or used. try { resetContext(); } catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); } //reset the instance manager instanceManager = null; if (log.isDebugEnabled()) log.debug("Stopping complete"); } /** Destroy needs to clean up the context completely. * * The problem is that undoing all the config in start() and restoring * a 'fresh' state is impossible. After stop()/destroy()/init()/start() * we should have the same state as if a fresh start was done - i.e * read modified web.xml, etc. This can only be done by completely * removing the context object and remapping a new one, or by cleaning * up everything. * * XXX Should this be done in stop() ? * */ @Override protected void destroyInternal() throws LifecycleException { // If in state NEW when destroy is called, the object name will never // have been set so the notification can't be created if (getObjectName() != null) { // Send j2ee.object.deleted notification Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } if (namingResources != null) { namingResources.destroy(); } synchronized (instanceListenersLock) { instanceListeners = new String[0]; } Loader loader = getLoader(); if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).destroy(); } Manager manager = getManager(); if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) manager).destroy(); } if (resources != null) { resources.destroy(); } super.destroyInternal(); } @Override public void backgroundProcess() { if (!getState().isAvailable()) return; Loader loader = getLoader(); if (loader != null) { try { loader.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString( "standardContext.backgroundProcess.loader", loader), e); } } Manager manager = getManager(); if (manager != null) { try { manager.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString( "standardContext.backgroundProcess.manager", manager), e); } } WebResourceRoot resources = getResources(); if (resources != null) { try { resources.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString( "standardContext.backgroundProcess.resources", resources), e); } } super.backgroundProcess(); } private void resetContext() throws Exception { // Restore the original state ( pre reading web.xml in start ) // If you extend this - override this method and make sure to clean up // Don't reset anything that is read from a <Context.../> element since // <Context .../> elements are read at initialisation will not be read // again for this object for (Container child : findChildren()) { removeChild(child); } startupTime = 0; startTime = 0; tldScanTime = 0; // Bugzilla 32867 distributable = false; applicationListeners = new ApplicationListener[0]; applicationEventListenersObjects = new Object[0]; applicationLifecycleListenersObjects = new Object[0]; jspConfigDescriptor = new ApplicationJspConfigDescriptor(); initializers.clear(); createdServlets.clear(); postConstructMethods.clear(); preDestroyMethods.clear(); if(log.isDebugEnabled()) log.debug("resetContext " + getObjectName()); } /** * Return a String representation of this component. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (getParent() != null) { sb.append(getParent().toString()); sb.append("."); } sb.append("StandardContext["); sb.append(getName()); sb.append("]"); return (sb.toString()); } // ------------------------------------------------------ Protected Methods /** * Adjust the URL pattern to begin with a leading slash, if appropriate * (i.e. we are running a servlet 2.2 application). Otherwise, return * the specified URL pattern unchanged. * * @param urlPattern The URL pattern to be adjusted (if needed) * and returned */ protected String adjustURLPattern(String urlPattern) { if (urlPattern == null) return (urlPattern); if (urlPattern.startsWith("/") || urlPattern.startsWith("*.")) return (urlPattern); if (!isServlet22()) return (urlPattern); if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.urlPattern.patternWarning", urlPattern)); return ("/" + urlPattern); } /** * Are we processing a version 2.2 deployment descriptor? */ @Override public boolean isServlet22() { if (this.publicId == null) return (false); if (this.publicId.equals (org.apache.catalina.startup.Constants.WebDtdPublicId_22)) return (true); else return (false); } @Override public Set<String> addServletSecurity( ServletRegistration.Dynamic registration, ServletSecurityElement servletSecurityElement) { Set<String> conflicts = new HashSet<>(); Collection<String> urlPatterns = registration.getMappings(); for (String urlPattern : urlPatterns) { boolean foundConflict = false; SecurityConstraint[] securityConstraints = findConstraints(); for (SecurityConstraint securityConstraint : securityConstraints) { SecurityCollection[] collections = securityConstraint.findCollections(); for (SecurityCollection collection : collections) { if (collection.findPattern(urlPattern)) { // First pattern found will indicate if there is a // conflict since for any given pattern all matching // constraints will be from either the descriptor or // not. It is not permitted to have a mixture if (collection.isFromDescriptor()) { // Skip this pattern foundConflict = true; conflicts.add(urlPattern); } else { // Need to overwrite constraint for this pattern // so remove every pattern found // TODO spec 13.4.2 appears to say only the // conflicting pattern is overwritten, not the // entire security constraint. removeConstraint(securityConstraint); } } if (foundConflict) { break; } } if (foundConflict) { break; } } // TODO spec 13.4.2 appears to say that non-conflicting patterns are // still used. // TODO you can't calculate the eventual security constraint now, // you have to wait until the context is started, since application // code can add url patterns after calling setSecurity. if (!foundConflict) { SecurityConstraint[] newSecurityConstraints = SecurityConstraint.createConstraints( servletSecurityElement, urlPattern); for (SecurityConstraint securityConstraint : newSecurityConstraints) { addConstraint(securityConstraint); } } } return conflicts; } /** * Bind current thread, both for CL purposes and for JNDI ENC support * during : startup, shutdown and realoading of the context. * * @return the previous context class loader */ protected ClassLoader bindThread() { ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); if (getLoader() != null && getLoader().getClassLoader() != null) { Thread.currentThread().setContextClassLoader (getLoader().getClassLoader()); } if (isUseNaming()) { try { ContextBindings.bindThread(this, this); } catch (NamingException e) { // Silent catch, as this is a normal case during the early // startup stages } } return oldContextClassLoader; } /** * Unbind thread. */ protected void unbindThread(ClassLoader oldContextClassLoader) { if (isUseNaming()) { ContextBindings.unbindThread(this, this); } Thread.currentThread().setContextClassLoader(oldContextClassLoader); } /** * Get base path. */ protected String getBasePath() { String docBase = null; Container container = this; while (container != null) { if (container instanceof Host) break; container = container.getParent(); } File file = new File(getDocBase()); if (!file.isAbsolute()) { if (container == null) { docBase = (new File(getCatalinaBase(), getDocBase())).getPath(); } else { // Use the "appBase" property of this container file = ((Host) container).getAppBaseFile(); docBase = (new File(file, getDocBase())).getPath(); } } else { docBase = file.getPath(); } return docBase; } /** * Get naming context full name. */ private String getNamingContextName() { if (namingContextName == null) { Container parent = getParent(); if (parent == null) { namingContextName = getName(); } else { Stack<String> stk = new Stack<>(); StringBuilder buff = new StringBuilder(); while (parent != null) { stk.push(parent.getName()); parent = parent.getParent(); } while (!stk.empty()) { buff.append("/" + stk.pop()); } buff.append(getName()); namingContextName = buff.toString(); } } return namingContextName; } /** * Naming context listener accessor. */ public NamingContextListener getNamingContextListener() { return namingContextListener; } /** * Naming context listener setter. */ public void setNamingContextListener(NamingContextListener namingContextListener) { this.namingContextListener = namingContextListener; } /** * Return the request processing paused flag for this Context. */ @Override public boolean getPaused() { return (this.paused); } @Override public boolean fireRequestInitEvent(ServletRequest request) { Object instances[] = getApplicationEventListeners(); if ((instances != null) && (instances.length > 0)) { ServletRequestEvent event = new ServletRequestEvent(getServletContext(), request); for (int i = 0; i < instances.length; i++) { if (instances[i] == null) continue; if (!(instances[i] instanceof ServletRequestListener)) continue; ServletRequestListener listener = (ServletRequestListener) instances[i]; try { listener.requestInitialized(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; } } } return true; } @Override public boolean fireRequestDestroyEvent(ServletRequest request) { Object instances[] = getApplicationEventListeners(); if ((instances != null) && (instances.length > 0)) { ServletRequestEvent event = new ServletRequestEvent(getServletContext(), request); for (int i = 0; i < instances.length; i++) { int j = (instances.length -1) -i; if (instances[j] == null) continue; if (!(instances[j] instanceof ServletRequestListener)) continue; ServletRequestListener listener = (ServletRequestListener) instances[j]; try { listener.requestDestroyed(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; } } } return true; } @Override public void addPostConstructMethod(String clazz, String method) { if (clazz == null || method == null) throw new IllegalArgumentException( sm.getString("standardContext.postconstruct.required")); if (postConstructMethods.get(clazz) != null) throw new IllegalArgumentException(sm.getString( "standardContext.postconstruct.duplicate", clazz)); postConstructMethods.put(clazz, method); fireContainerEvent("addPostConstructMethod", clazz); } @Override public void removePostConstructMethod(String clazz) { postConstructMethods.remove(clazz); fireContainerEvent("removePostConstructMethod", clazz); } @Override public void addPreDestroyMethod(String clazz, String method) { if (clazz == null || method == null) throw new IllegalArgumentException( sm.getString("standardContext.predestroy.required")); if (preDestroyMethods.get(clazz) != null) throw new IllegalArgumentException(sm.getString( "standardContext.predestroy.duplicate", clazz)); preDestroyMethods.put(clazz, method); fireContainerEvent("addPreDestroyMethod", clazz); } @Override public void removePreDestroyMethod(String clazz) { preDestroyMethods.remove(clazz); fireContainerEvent("removePreDestroyMethod", clazz); } @Override public String findPostConstructMethod(String clazz) { return postConstructMethods.get(clazz); } @Override public String findPreDestroyMethod(String clazz) { return preDestroyMethods.get(clazz); } @Override public Map<String, String> findPostConstructMethods() { return postConstructMethods; } @Override public Map<String, String> findPreDestroyMethods() { return preDestroyMethods; } /** * Set the appropriate context attribute for our work directory. */ private void postWorkDirectory() { // Acquire (or calculate) the work directory path String workDir = getWorkDir(); if (workDir == null || workDir.length() == 0) { // Retrieve our parent (normally a host) name String hostName = null; String engineName = null; String hostWorkDir = null; Container parentHost = getParent(); if (parentHost != null) { hostName = parentHost.getName(); if (parentHost instanceof StandardHost) { hostWorkDir = ((StandardHost)parentHost).getWorkDir(); } Container parentEngine = parentHost.getParent(); if (parentEngine != null) { engineName = parentEngine.getName(); } } if ((hostName == null) || (hostName.length() < 1)) hostName = "_"; if ((engineName == null) || (engineName.length() < 1)) engineName = "_"; String temp = getBaseName(); if (temp.startsWith("/")) temp = temp.substring(1); temp = temp.replace('/', '_'); temp = temp.replace('\\', '_'); if (temp.length() < 1) temp = ContextName.ROOT_NAME; if (hostWorkDir != null ) { workDir = hostWorkDir + File.separator + temp; } else { workDir = "work" + File.separator + engineName + File.separator + hostName + File.separator + temp; } setWorkDir(workDir); } // Create this directory if necessary File dir = new File(workDir); if (!dir.isAbsolute()) { String catalinaHomePath = null; try { catalinaHomePath = getCatalinaBase().getCanonicalPath(); dir = new File(catalinaHomePath, workDir); } catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); } } if (!dir.mkdirs() && !dir.isDirectory()) { log.warn(sm.getString("standardContext.workCreateFail", dir, getName())); } // Set the appropriate servlet context attribute if (context == null) { getServletContext(); } context.setAttribute(ServletContext.TEMPDIR, dir); context.setAttributeReadOnly(ServletContext.TEMPDIR); } /** * Set the request processing paused flag for this Context. * * @param paused The new request processing paused flag */ private void setPaused(boolean paused) { this.paused = paused; } /** * Validate the syntax of a proposed <code>&lt;url-pattern&gt;</code> * for conformance with specification requirements. * * @param urlPattern URL pattern to be validated */ private boolean validateURLPattern(String urlPattern) { if (urlPattern == null) return (false); if (urlPattern.indexOf('\n') >= 0 || urlPattern.indexOf('\r') >= 0) { return (false); } if (urlPattern.equals("")) { return true; } if (urlPattern.startsWith("*.")) { if (urlPattern.indexOf('/') < 0) { checkUnusualURLPattern(urlPattern); return (true); } else return (false); } if ( (urlPattern.startsWith("/")) && (urlPattern.indexOf("*.") < 0)) { checkUnusualURLPattern(urlPattern); return (true); } else return (false); } /** * Check for unusual but valid <code>&lt;url-pattern&gt;</code>s. * See Bugzilla 34805, 43079 & 43080 */ private void checkUnusualURLPattern(String urlPattern) { if (log.isInfoEnabled()) { if(urlPattern.endsWith("*") && (urlPattern.length() < 2 || urlPattern.charAt(urlPattern.length()-2) != '/')) { log.info("Suspicious url pattern: \"" + urlPattern + "\"" + " in context [" + getName() + "] - see" + " section SRV.11.2 of the Servlet specification" ); } } } // ------------------------------------------------------------- Operations /** * JSR77 deploymentDescriptor attribute * * @return string deployment descriptor */ public String getDeploymentDescriptor() { InputStream stream = null; ServletContext servletContext = getServletContext(); if (servletContext != null) { stream = servletContext.getResourceAsStream( org.apache.catalina.startup.Constants.ApplicationWebXml); } if (stream == null) { return ""; } StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(stream)); String strRead = ""; while (strRead != null) { sb.append(strRead); strRead = br.readLine(); } } catch (IOException e) { return ""; } finally { if (br != null) { try { br.close(); } catch (IOException ioe) {/*Ignore*/} } } return sb.toString(); } /** * JSR77 servlets attribute * * @return list of all servlets ( we know about ) */ public String[] getServlets() { String[] result = null; Container[] children = findChildren(); if (children != null) { result = new String[children.length]; for( int i=0; i< children.length; i++ ) { result[i] = children[i].getObjectName().toString(); } } return result; } @Override protected String getObjectNameKeyProperties() { StringBuilder keyProperties = new StringBuilder("j2eeType=WebModule,"); keyProperties.append(getObjectKeyPropertiesNameOnly()); keyProperties.append(",J2EEApplication="); keyProperties.append(getJ2EEApplication()); keyProperties.append(",J2EEServer="); keyProperties.append(getJ2EEServer()); return keyProperties.toString(); } private String getObjectKeyPropertiesNameOnly() { StringBuilder result = new StringBuilder("name=//"); String hostname = getParent().getName(); if (hostname == null) { result.append("DEFAULT"); } else { result.append(hostname); } String contextName = getName(); if (!contextName.startsWith("/")) { result.append('/'); } result.append(contextName); return result.toString(); } @Override protected void initInternal() throws LifecycleException { super.initInternal(); if (processTlds) { this.addLifecycleListener(new TldConfig()); } // Register the naming resources if (namingResources != null) { namingResources.init(); } if (resources != null) { resources.start(); } // Send j2ee.object.created notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.object.created", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } } /* Remove a JMX notficationListener * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object) */ @Override public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener,filter,object); } private MBeanNotificationInfo[] notificationInfo; /* Get JMX Broadcaster Info * @TODO use StringManager for international support! * @TODO This two events we not send j2ee.state.failed and j2ee.attribute.changed! * @see javax.management.NotificationBroadcaster#getNotificationInfo() */ @Override public MBeanNotificationInfo[] getNotificationInfo() { // FIXME: i18n if(notificationInfo == null) { notificationInfo = new MBeanNotificationInfo[]{ new MBeanNotificationInfo(new String[] { "j2ee.object.created"}, Notification.class.getName(), "web application is created" ), new MBeanNotificationInfo(new String[] { "j2ee.state.starting"}, Notification.class.getName(), "change web application is starting" ), new MBeanNotificationInfo(new String[] { "j2ee.state.running"}, Notification.class.getName(), "web application is running" ), new MBeanNotificationInfo(new String[] { "j2ee.state.stopping"}, Notification.class.getName(), "web application start to stopped" ), new MBeanNotificationInfo(new String[] { "j2ee.object.stopped"}, Notification.class.getName(), "web application is stopped" ), new MBeanNotificationInfo(new String[] { "j2ee.object.deleted"}, Notification.class.getName(), "web application is deleted" ) }; } return notificationInfo; } /* Add a JMX-NotificationListener * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object) */ @Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,object); } /** * Remove a JMX-NotificationListener * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener) */ @Override public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener); } // ------------------------------------------------------------- Attributes /** * Return the naming resources associated with this web application. */ public String[] getWelcomeFiles() { return findWelcomeFiles(); } /** * Set the validation feature of the XML parser used when * parsing xml instances. * @param webXmlValidation true to enable xml instance validation */ @Override public void setXmlValidation(boolean webXmlValidation){ this.webXmlValidation = webXmlValidation; } /** * Get the server.xml <context> attribute's xmlValidation. * @return true if validation is enabled. * */ @Override public boolean getXmlValidation(){ return webXmlValidation; } /** * Get the server.xml <context> attribute's xmlNamespaceAware. * @return true if namespace awarenes is enabled. */ @Override public boolean getXmlNamespaceAware(){ return webXmlNamespaceAware; } /** * Set the namespace aware feature of the XML parser used when * parsing xml instances. * @param webXmlNamespaceAware true to enable namespace awareness */ @Override public void setXmlNamespaceAware(boolean webXmlNamespaceAware){ this.webXmlNamespaceAware= webXmlNamespaceAware; } /** * Set the validation feature of the XML parser used when * parsing tlds files. * @param tldValidation true to enable xml instance validation */ @Override public void setTldValidation(boolean tldValidation){ this.tldValidation = tldValidation; } /** * Get the server.xml <context> attribute's webXmlValidation. * @return true if validation is enabled. * */ @Override public boolean getTldValidation(){ return tldValidation; } /** * Sets the process TLDs attribute. * * @param newProcessTlds The new value */ public void setProcessTlds(boolean newProcessTlds) { processTlds = newProcessTlds; } /** * Returns the processTlds attribute value. */ public boolean getProcessTlds() { return processTlds; } /** * Get the server.xml &lt;host&gt; attribute's xmlNamespaceAware. * @return true if namespace awarenes is enabled. */ @Override public boolean getTldNamespaceAware(){ return tldNamespaceAware; } /** * Set the namespace aware feature of the XML parser used when * parsing xml instances. * @param tldNamespaceAware true to enable namespace awareness */ @Override public void setTldNamespaceAware(boolean tldNamespaceAware){ this.tldNamespaceAware= tldNamespaceAware; } /** * Support for "stateManageable" JSR77 */ public boolean isStateManageable() { return true; } /** * The J2EE Server ObjectName this module is deployed on. */ private String server = null; /** * The Java virtual machines on which this module is running. */ private String[] javaVMs = null; public String getServer() { return server; } public String setServer(String server) { return this.server=server; } public String[] getJavaVMs() { return javaVMs; } public String[] setJavaVMs(String[] javaVMs) { return this.javaVMs = javaVMs; } /** * Gets the time this context was started. * * @return Time (in milliseconds since January 1, 1970, 00:00:00) when this * context was started */ public long getStartTime() { return startTime; } private static class NoPluggabilityServletContext implements ServletContext { private final ServletContext sc; public NoPluggabilityServletContext(ServletContext sc) { this.sc = sc; } @Override public String getContextPath() { return sc.getContextPath(); } @Override public ServletContext getContext(String uripath) { return sc.getContext(uripath); } @Override public int getMajorVersion() { return sc.getMajorVersion(); } @Override public int getMinorVersion() { return sc.getMinorVersion(); } @Override public int getEffectiveMajorVersion() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public int getEffectiveMinorVersion() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public String getMimeType(String file) { return sc.getMimeType(file); } @Override public Set<String> getResourcePaths(String path) { return sc.getResourcePaths(path); } @Override public URL getResource(String path) throws MalformedURLException { return sc.getResource(path); } @Override public InputStream getResourceAsStream(String path) { return sc.getResourceAsStream(path); } @Override public RequestDispatcher getRequestDispatcher(String path) { return sc.getRequestDispatcher(path); } @Override public RequestDispatcher getNamedDispatcher(String name) { return sc.getNamedDispatcher(name); } @Override @Deprecated public Servlet getServlet(String name) throws ServletException { return sc.getServlet(name); } @Override @Deprecated public Enumeration<Servlet> getServlets() { return sc.getServlets(); } @Override @Deprecated public Enumeration<String> getServletNames() { return sc.getServletNames(); } @Override public void log(String msg) { sc.log(msg); } @Override @Deprecated public void log(Exception exception, String msg) { sc.log(exception, msg); } @Override public void log(String message, Throwable throwable) { sc.log(message, throwable); } @Override public String getRealPath(String path) { return sc.getRealPath(path); } @Override public String getServerInfo() { return sc.getServerInfo(); } @Override public String getInitParameter(String name) { return sc.getInitParameter(name); } @Override public Enumeration<String> getInitParameterNames() { return sc.getInitParameterNames(); } @Override public boolean setInitParameter(String name, String value) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Object getAttribute(String name) { return sc.getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { return sc.getAttributeNames(); } @Override public void setAttribute(String name, Object object) { sc.setAttribute(name, object); } @Override public void removeAttribute(String name) { sc.removeAttribute(name); } @Override public String getServletContextName() { return sc.getServletContextName(); } @Override public Dynamic addServlet(String servletName, String className) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Dynamic addServlet(String servletName, Servlet servlet) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public ServletRegistration getServletRegistration(String servletName) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Map<String,? extends ServletRegistration> getServletRegistrations() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, String className) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, Filter filter) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, Class<? extends Filter> filterClass) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public FilterRegistration getFilterRegistration(String filterName) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Map<String,? extends FilterRegistration> getFilterRegistrations() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public SessionCookieConfig getSessionCookieConfig() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void addListener(String className) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends EventListener> void addListener(T t) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void addListener(Class<? extends EventListener> listenerClass) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public JspConfigDescriptor getJspConfigDescriptor() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public ClassLoader getClassLoader() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void declareRoles(String... roleNames) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public String getVirtualServerName() { return sc.getVirtualServerName(); } } }
54,745
Bug 54745 Tomcat JarScanning does not work when Tomcat started with Java Web Start
null
resolved fixed
c7c30b6
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-20T15:07:55Z
2013-03-23T03:40:00Z
java/org/apache/tomcat/util/scan/StandardJarScanner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.scan; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLConnection; import java.util.Iterator; import java.util.Set; import javax.servlet.ServletContext; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.JarScanFilter; import org.apache.tomcat.JarScanType; import org.apache.tomcat.JarScanner; import org.apache.tomcat.JarScannerCallback; import org.apache.tomcat.util.res.StringManager; /** * The default {@link JarScanner} implementation scans the WEB-INF/lib directory * followed by the provided classloader and then works up the classloader * hierarchy. This implementation is sufficient to meet the requirements of the * Servlet 3.0 specification as well as to provide a number of Tomcat specific * extensions. The extensions are: * <ul> * <li>Scanning the classloader hierarchy (enabled by default)</li> * <li>Testing all files to see if they are JARs (disabled by default)</li> * <li>Testing all directories to see if they are exploded JARs * (disabled by default)</li> * </ul> * All of the extensions may be controlled via configuration. */ public class StandardJarScanner implements JarScanner { private static final Log log = LogFactory.getLog(StandardJarScanner.class); /** * The string resources for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); /** * Controls the classpath scanning extension. */ private boolean scanClassPath = true; public boolean isScanClassPath() { return scanClassPath; } public void setScanClassPath(boolean scanClassPath) { this.scanClassPath = scanClassPath; } /** * Controls the testing all files to see of they are JAR files extension. */ private boolean scanAllFiles = false; public boolean isScanAllFiles() { return scanAllFiles; } public void setScanAllFiles(boolean scanAllFiles) { this.scanAllFiles = scanAllFiles; } /** * Controls the testing all directories to see of they are exploded JAR * files extension. */ private boolean scanAllDirectories = false; public boolean isScanAllDirectories() { return scanAllDirectories; } public void setScanAllDirectories(boolean scanAllDirectories) { this.scanAllDirectories = scanAllDirectories; } /** * Controls the testing of the bootstrap classpath which consists of the * runtime classes provided by the JVM and any installed system extensions. */ private boolean scanBootstrapClassPath = false; public boolean isScanBootstrapClassPath() { return scanBootstrapClassPath; } public void setScanBootstrapClassPath(boolean scanBootstrapClassPath) { this.scanBootstrapClassPath = scanBootstrapClassPath; } /** * Controls the filtering of the results from the scan for JARs */ private JarScanFilter jarScanFilter = new StandardJarScanFilter(); @Override public JarScanFilter getJarScanFilter() { return jarScanFilter; } @Override public void setJarScanFilter(JarScanFilter jarScanFilter) { this.jarScanFilter = jarScanFilter; } /** * Scan the provided ServletContext and class loader for JAR files. Each JAR * file found will be passed to the callback handler to be processed. * * @param scanType The type of JAR scan to perform. This is passed to * the filter which uses it to determine how to * filter the results * @param context The ServletContext - used to locate and access * WEB-INF/lib * @param callback The handler to process any JARs found */ @Override public void scan(JarScanType scanType, ServletContext context, JarScannerCallback callback) { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.webinflibStart")); } // Scan WEB-INF/lib Set<String> dirList = context.getResourcePaths(Constants.WEB_INF_LIB); if (dirList != null) { Iterator<String> it = dirList.iterator(); while (it.hasNext()) { String path = it.next(); if (path.endsWith(Constants.JAR_EXT) && jarScanFilter.check(scanType, path.substring(path.lastIndexOf('/')+1))) { // Need to scan this JAR if (log.isDebugEnabled()) { log.debug(sm.getString("jarScan.webinflibJarScan", path)); } URL url = null; try { // File URLs are always faster to work with so use them // if available. String realPath = context.getRealPath(path); if (realPath == null) { url = context.getResource(path); } else { url = (new File(realPath)).toURI().toURL(); } process(callback, url, true); } catch (IOException e) { log.warn(sm.getString("jarScan.webinflibFail", url), e); } } else { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.webinflibJarNoScan", path)); } } } } // Scan WEB-INF/classes if (scanAllDirectories) { try { URL url = context.getResource("/WEB-INF/classes/META-INF"); if (url != null) { try { callback.scanWebInfClasses(); } catch (IOException e) { log.warn(sm.getString("jarScan.webinfclassesFail"), e); } } } catch (MalformedURLException e) { // Ignore } } // Scan the classpath if (scanClassPath) { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.classloaderStart")); } ClassLoader stopLoader = null; if (!scanBootstrapClassPath) { // Stop when we reach the bootstrap class loader stopLoader = ClassLoader.getSystemClassLoader().getParent(); } ClassLoader classLoader = context.getClassLoader(); // No need to scan the web application class loader - we have // already scanned WEB-INF/lib and WEB-INF/classes classLoader = classLoader.getParent(); // JARs are treated as application provided until the common class // loader is reached. boolean isWebapp = true; while (classLoader != null && classLoader != stopLoader) { if (classLoader instanceof URLClassLoader) { if (isWebapp) { isWebapp = isWebappClassLoader(classLoader); } URL[] urls = ((URLClassLoader) classLoader).getURLs(); for (int i=0; i<urls.length; i++) { // Extract the jarName if there is one to be found String jarName = getJarName(urls[i]); // Skip JARs known not to be interesting if (jarName != null && jarScanFilter.check(scanType, jarName)) { if (log.isDebugEnabled()) { log.debug(sm.getString("jarScan.classloaderJarScan", urls[i])); } try { process(callback, urls[i], isWebapp); } catch (IOException ioe) { log.warn(sm.getString( "jarScan.classloaderFail",urls[i]), ioe); } } else { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.classloaderJarNoScan", urls[i])); } } } } classLoader = classLoader.getParent(); } } } /* * Since class loader hierarchies can get complicated, this method attempts * to apply the following rule: A class loader is a web application class * loader unless it loaded this class (StandardJarScanner) or is a parent * of the class loader that loaded this class. * * This should mean: * the webapp class loader is an application class loader * the shared class loader is an application class loader * the server class loader is not an application class loader * the common class loader is not an application class loader * the system class loader is not an application class loader * the bootstrap class loader is not an application class loader */ private boolean isWebappClassLoader(ClassLoader classLoader) { ClassLoader nonWebappLoader = StandardJarScanner.class.getClassLoader(); while (nonWebappLoader != null) { if (nonWebappLoader == classLoader) { return false; } nonWebappLoader = nonWebappLoader.getParent(); } return true; } /* * Scan a URL for JARs with the optional extensions to look at all files * and all directories. */ private void process(JarScannerCallback callback, URL url, boolean isWebapp) throws IOException { if (log.isTraceEnabled()) { log.trace(sm.getString("jarScan.jarUrlStart", url)); } URLConnection conn = url.openConnection(); if (conn instanceof JarURLConnection) { callback.scan((JarURLConnection) conn, isWebapp); } else { String urlStr = url.toString(); if (urlStr.startsWith("file:") || urlStr.startsWith("jndi:")) { if (urlStr.endsWith(Constants.JAR_EXT)) { URL jarURL = new URL("jar:" + urlStr + "!/"); callback.scan((JarURLConnection) jarURL.openConnection(), isWebapp); } else { File f; try { f = new File(url.toURI()); if (f.isFile() && scanAllFiles) { // Treat this file as a JAR URL jarURL = new URL("jar:" + urlStr + "!/"); callback.scan( (JarURLConnection) jarURL.openConnection(), isWebapp); } else if (f.isDirectory() && scanAllDirectories) { File metainf = new File(f.getAbsoluteFile() + File.separator + "META-INF"); if (metainf.isDirectory()) { callback.scan(f, isWebapp); } } } catch (URISyntaxException e) { // Wrap the exception and re-throw IOException ioe = new IOException(); ioe.initCause(e); throw ioe; } } } } } /* * Extract the JAR name, if present, from a URL */ private String getJarName(URL url) { String name = null; String path = url.getPath(); int end = path.indexOf(Constants.JAR_EXT); if (end != -1) { int start = path.lastIndexOf('/', end); name = path.substring(start + 1, end + 4); } else if (isScanAllDirectories()){ int start = path.lastIndexOf('/'); name = path.substring(start + 1); } return name; } }
55,101
Bug 55101 BasicAuthenticator parser and associated unit tests
null
resolved fixed
c4a50f5
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-20T20:36:08Z
2013-06-15T18:13:20Z
java/org/apache/catalina/authenticator/BasicAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.io.IOException; import java.security.Principal; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.connector.Request; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.codec.binary.Base64; /** * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP BASIC * Authentication, as outlined in RFC 2617: "HTTP Authentication: Basic * and Digest Access Authentication." * * @author Craig R. McClanahan * @version $Id$ */ public class BasicAuthenticator extends AuthenticatorBase { private static final Log log = LogFactory.getLog(BasicAuthenticator.class); // --------------------------------------------------------- Public Methods /** * Authenticate the user making this request, based on the specified * login configuration. Return <code>true</code> if any specified * constraint has been satisfied, or <code>false</code> if we have * created a response challenge already. * * @param request Request we are processing * @param response Response we are creating * * @exception IOException if an input/output error occurs */ @Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } // Validate any credentials already included with this request String username = null; String password = null; MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization != null) { authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (authorizationBC.startsWithIgnoreCase("basic ", 0)) { authorizationBC.setOffset(authorizationBC.getOffset() + 6); byte[] decoded = Base64.decodeBase64( authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength()); // Get username and password int colon = -1; for (int i = 0; i < decoded.length; i++) { if (decoded[i] == ':') { colon = i; break; } } if (colon < 0) { username = new String(decoded, B2CConverter.ISO_8859_1); } else { username = new String( decoded, 0, colon, B2CConverter.ISO_8859_1); password = new String( decoded, colon + 1, decoded.length - colon - 1, B2CConverter.ISO_8859_1); } authorizationBC.setOffset(authorizationBC.getOffset() - 6); } principal = context.getRealm().authenticate(username, password); if (principal != null) { register(request, response, principal, HttpServletRequest.BASIC_AUTH, username, password); return (true); } } StringBuilder value = new StringBuilder(16); value.append("Basic realm=\""); value.append(getRealmName(context)); value.append('\"'); response.setHeader(AUTH_HEADER_NAME, value.toString()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return (false); } @Override protected String getAuthMethod() { return HttpServletRequest.BASIC_AUTH; } }
55,101
Bug 55101 BasicAuthenticator parser and associated unit tests
null
resolved fixed
c4a50f5
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-20T20:36:08Z
2013-06-15T18:13:20Z
test/org/apache/catalina/authenticator/TestBasicAuthParser.java
55,101
Bug 55101 BasicAuthenticator parser and associated unit tests
null
resolved fixed
c4a50f5
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-20T20:36:08Z
2013-06-15T18:13:20Z
test/org/apache/catalina/authenticator/TestNonLoginAndBasicAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityCollection; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.session.ManagerBase; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.codec.binary.Base64; /** * Test BasicAuthenticator and NonLoginAuthenticator when a * SingleSignOn Valve is not active. * * <p> * In the absence of SSO support, these two authenticator classes * both have quite simple behaviour. By testing them together, we * can make sure they operate independently and confirm that no * SSO logic has been accidentally triggered. */ public class TestNonLoginAndBasicAuthenticator extends TomcatBaseTest { protected static final boolean USE_COOKIES = true; protected static final boolean NO_COOKIES = !USE_COOKIES; private static final String USER = "user"; private static final String PWD = "pwd"; private static final String ROLE = "role"; private static final String NICE_METHOD = "Basic"; private static final String HTTP_PREFIX = "http://localhost:"; private static final String CONTEXT_PATH_NOLOGIN = "/nologin"; private static final String CONTEXT_PATH_LOGIN = "/login"; private static final String URI_PROTECTED = "/protected"; private static final String URI_PUBLIC = "/anyoneCanAccess"; private static final int SHORT_SESSION_TIMEOUT_MINS = 1; private static final int LONG_SESSION_TIMEOUT_MINS = 2; private static final int MANAGER_SCAN_INTERVAL_SECS = 10; private static final int MANAGER_EXPIRE_SESSIONS_FAST = 1; private static final int EXTRA_DELAY_SECS = 5; private static final long TIMEOUT_DELAY_MSECS = (((SHORT_SESSION_TIMEOUT_MINS * 60) + (MANAGER_SCAN_INTERVAL_SECS * MANAGER_EXPIRE_SESSIONS_FAST) + EXTRA_DELAY_SECS) * 1000); private static final String CLIENT_AUTH_HEADER = "authorization"; private static final String SERVER_AUTH_HEADER = "WWW-Authenticate"; private static final String SERVER_COOKIE_HEADER = "Set-Cookie"; private static final String CLIENT_COOKIE_HEADER = "Cookie"; private static final BasicCredentials NO_CREDENTIALS = null; private static final BasicCredentials GOOD_CREDENTIALS = new BasicCredentials(NICE_METHOD, USER, PWD); private static final BasicCredentials STRANGE_CREDENTIALS = new BasicCredentials("bAsIc", USER, PWD); private static final BasicCredentials BAD_CREDENTIALS = new BasicCredentials(NICE_METHOD, USER, "wrong"); private static final BasicCredentials BAD_METHOD = new BasicCredentials("BadMethod", USER, PWD); private static final BasicCredentials SPACED_BASE64 = new BasicCredentials(NICE_METHOD + " ", USER, PWD); private static final BasicCredentials SPACED_USERNAME = new BasicCredentials(NICE_METHOD, " " + USER + " ", PWD); private static final BasicCredentials SPACED_PASSWORD = new BasicCredentials(NICE_METHOD, USER, " " + PWD + " "); private Tomcat tomcat; private Context basicContext; private Context nonloginContext; private List<String> cookies; /* * Try to access an unprotected resource in a webapp that * does not have a login method defined. * This should be permitted. */ @Test public void testAcceptPublicNonLogin() throws Exception { doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PUBLIC, NO_COOKIES, HttpServletResponse.SC_OK); } /* * Try to access a protected resource in a webapp that * does not have a login method defined. * This should be rejected with SC_FORBIDDEN 403 status. */ @Test public void testRejectProtectedNonLogin() throws Exception { doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, NO_COOKIES, HttpServletResponse.SC_FORBIDDEN); } /* * Try to access an unprotected resource in a webapp that * has a BASIC login method defined. * This should be permitted without a challenge. */ @Test public void testAcceptPublicBasic() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PUBLIC, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * Try to access a protected resource in a webapp that * has a BASIC login method defined. The access will be * challenged with 401 SC_UNAUTHORIZED, and then be permitted * once authenticated. */ @Test public void testAcceptProtectedBasic() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * This is the same as testAcceptProtectedBasic (above), except * using an invalid password. */ @Test public void testAuthMethodBadCredentials() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, BAD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * This is the same as testAcceptProtectedBasic (above), except * to verify the server follows RFC2617 by treating the auth-scheme * token as case-insensitive. */ @Test public void testAuthMethodCaseBasic() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, STRANGE_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * This is the same as testAcceptProtectedBasic (above), except * using an invalid authentication method. * * Note: the container ensures the Basic login method is called. * BasicAuthenticator does not find the expected authentication * header method, and so does not extract any credentials. * * The request is rejected with 401 SC_UNAUTHORIZED status. RFC2616 * says the response body should identify the auth-schemes that are * acceptable for the container. */ @Test public void testAuthMethodBadMethod() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, BAD_METHOD, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * This is the same as testAcceptProtectedBasic (above), except * using excess white space after the authentication method. * * The access will be challenged with 401 SC_UNAUTHORIZED, and then be * permitted once authenticated. * * RFC2617 does not define the separation syntax between the auth-scheme and * basic-credentials tokens. Tomcat tolerates any amount of white space * (within the limits of HTTP header sizes) and returns SC_OK. */ @Test public void testAuthMethodExtraSpace() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, SPACED_BASE64, NO_COOKIES, HttpServletResponse.SC_OK); } /* * This is the same as testAcceptProtectedBasic (above), except * using white space around the username credential. * * The request is rejected with 401 SC_UNAUTHORIZED status. * * TODO: RFC2617 does not define the separation syntax between the * auth-scheme and basic-credentials tokens. Tomcat should tolerate * any reasonable amount of white space and return SC_OK. */ @Test public void testUserExtraSpace() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, SPACED_USERNAME, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * This is the same as testAcceptProtectedBasic (above), except * using white space around the password credential. * * The request is rejected with 401 SC_UNAUTHORIZED status. * * TODO: RFC2617 does not define the separation syntax between the * auth-scheme and basic-credentials tokens. Tomcat should tolerate * any reasonable amount of white space and return SC_OK. */ @Test public void testPasswordExtraSpace() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, SPACED_PASSWORD, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); } /* * The default behaviour of BASIC authentication does NOT create * a session on the server. Verify that the client is required to * send a valid authenticate header with every request to access * protected resources. */ @Test public void testBasicLoginWithoutSession() throws Exception { // this section is identical to testAuthMethodCaseBasic doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // next, try to access the protected resource while not providing // credentials. This confirms the server has not retained any state // data which might allow it to authenticate the client. Expect // to be challenged with 401 SC_UNAUTHORIZED. doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); // finally, provide credentials to confirm the resource // can still be accessed with an authentication header. doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); } /* * Test the optional behaviour of BASIC authentication to create * a session on the server. The server will return a session cookie. * * 1. try to access a protected resource without credentials, so * get Unauthorized status. * 2. try to access a protected resource when providing credentials, * so get OK status and a server session cookie. * 3. access the protected resource once more using a session cookie. * 4. repeat using the session cookie. * * Note: The FormAuthenticator is a two-step process and is protected * from session fixation attacks by the default AuthenticatorBase * changeSessionIdOnAuthentication setting of true. However, * BasicAuthenticator is a one-step process and so the * AuthenticatorBase does not reissue the sessionId. */ @Test public void testBasicLoginSessionPersistence() throws Exception { setAlwaysUseSession(); // this section is identical to testAuthMethodCaseBasic doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // confirm the session is not recognised by the server alone doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); // now provide the harvested session cookie for authentication doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_OK); // finally, do it again with the cookie to be sure doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_OK); } /* * Verify the timeout mechanism works for BASIC sessions. This test * follows the flow of testBasicLoginSessionPersistence (above). */ @Test public void testBasicLoginSessionTimeout() throws Exception { setAlwaysUseSession(); setRapidSessionTimeout(); // this section is identical to testAuthMethodCaseBasic doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // now provide the harvested session cookie for authentication List<String> originalCookies = cookies; doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_OK); // allow the session to time out and lose authentication Thread.sleep(TIMEOUT_DELAY_MSECS); // provide the harvested session cookie for authentication // to confirm it has expired doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, USE_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); // finally, do BASIC reauthentication and get another session doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // slightly paranoid verification boolean sameCookies = originalCookies.equals(cookies); assertTrue(!sameCookies); } /* * Logon to access a protected resource in a webapp that uses * BASIC authentication. Then try to access a protected resource * in a different webapp which does not have a login method. * This should be rejected with SC_FORBIDDEN 403 status, confirming * there has been no cross-authentication between the webapps. */ @Test public void testBasicLoginRejectProtected() throws Exception { doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, NO_COOKIES, HttpServletResponse.SC_FORBIDDEN); } /* * Try to use the session cookie from the BASIC webapp to request * access to the webapp that does not have a login method. (This * is equivalent to Single Signon, but without the Valve.) * * Verify there is no cross-authentication when using similar logic * to testBasicLoginRejectProtected (above). * * This should be rejected with SC_FORBIDDEN 403 status. */ @Test public void testBasicLoginRejectProtectedWithSession() throws Exception { setAlwaysUseSession(); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, NO_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_UNAUTHORIZED); doTestBasic(CONTEXT_PATH_LOGIN + URI_PROTECTED, GOOD_CREDENTIALS, NO_COOKIES, HttpServletResponse.SC_OK); // use the session cookie harvested with the other webapp doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, USE_COOKIES, HttpServletResponse.SC_FORBIDDEN); } private void doTestNonLogin(String uri, boolean useCookie, int expectedRC) throws Exception { Map<String,List<String>> reqHeaders = new HashMap<>(); Map<String,List<String>> respHeaders = new HashMap<>(); if (useCookie && (cookies != null)) { reqHeaders.put(CLIENT_COOKIE_HEADER + ":", cookies); } ByteChunk bc = new ByteChunk(); int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders, respHeaders); if (expectedRC != HttpServletResponse.SC_OK) { assertEquals(expectedRC, rc); assertTrue(bc.getLength() > 0); } else { assertEquals("OK", bc.toString()); } } private void doTestBasic(String uri, BasicCredentials credentials, boolean useCookie, int expectedRC) throws Exception { Map<String,List<String>> reqHeaders = new HashMap<>(); Map<String,List<String>> respHeaders = new HashMap<>(); if (useCookie && (cookies != null)) { reqHeaders.put(CLIENT_COOKIE_HEADER + ":", cookies); } else { if (credentials != null) { List<String> auth = new ArrayList<>(); auth.add(credentials.getCredentials()); reqHeaders.put(CLIENT_AUTH_HEADER, auth); } } ByteChunk bc = new ByteChunk(); int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders, respHeaders); if (expectedRC != HttpServletResponse.SC_OK) { assertEquals(expectedRC, rc); assertTrue(bc.getLength() > 0); if (expectedRC == HttpServletResponse.SC_UNAUTHORIZED) { // The server should identify the acceptable method(s) boolean methodFound = false; List<String> authHeaders = respHeaders.get(SERVER_AUTH_HEADER); for (String authHeader : authHeaders) { if (authHeader.indexOf(NICE_METHOD) > -1) { methodFound = true; break; } } assertTrue(methodFound); } } else { assertEquals("OK", bc.toString()); List<String> newCookies = respHeaders.get(SERVER_COOKIE_HEADER); if (newCookies != null) { // harvest cookies whenever the server sends some new ones cookies = newCookies; } } } /* * setup two webapps for every test * * note: the super class tearDown method will stop tomcat */ @Override public void setUp() throws Exception { super.setUp(); // create a tomcat server using the default in-memory Realm tomcat = getTomcatInstance(); // add the test user and role to the Realm tomcat.addUser(USER, PWD); tomcat.addRole(USER, ROLE); // setup both NonLogin and Login webapps setUpNonLogin(); setUpLogin(); tomcat.start(); } private void setUpNonLogin() throws Exception { // Must have a real docBase for webapps - just use temp nonloginContext = tomcat.addContext(CONTEXT_PATH_NOLOGIN, System.getProperty("java.io.tmpdir")); nonloginContext.setSessionTimeout(LONG_SESSION_TIMEOUT_MINS); // Add protected servlet to the context Tomcat.addServlet(nonloginContext, "TesterServlet1", new TesterServlet()); nonloginContext.addServletMapping(URI_PROTECTED, "TesterServlet1"); SecurityCollection collection1 = new SecurityCollection(); collection1.addPattern(URI_PROTECTED); SecurityConstraint sc1 = new SecurityConstraint(); sc1.addAuthRole(ROLE); sc1.addCollection(collection1); nonloginContext.addConstraint(sc1); // Add unprotected servlet to the context Tomcat.addServlet(nonloginContext, "TesterServlet2", new TesterServlet()); nonloginContext.addServletMapping(URI_PUBLIC, "TesterServlet2"); SecurityCollection collection2 = new SecurityCollection(); collection2.addPattern(URI_PUBLIC); SecurityConstraint sc2 = new SecurityConstraint(); // do not add a role - which signals access permitted without one sc2.addCollection(collection2); nonloginContext.addConstraint(sc2); // Configure the authenticator and inherit the Realm from Engine LoginConfig lc = new LoginConfig(); lc.setAuthMethod("NONE"); nonloginContext.setLoginConfig(lc); AuthenticatorBase nonloginAuthenticator = new NonLoginAuthenticator(); nonloginContext.getPipeline().addValve(nonloginAuthenticator); } private void setUpLogin() throws Exception { // Must have a real docBase for webapps - just use temp basicContext = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir")); basicContext.setSessionTimeout(SHORT_SESSION_TIMEOUT_MINS); // Add protected servlet to the context Tomcat.addServlet(basicContext, "TesterServlet3", new TesterServlet()); basicContext.addServletMapping(URI_PROTECTED, "TesterServlet3"); SecurityCollection collection = new SecurityCollection(); collection.addPattern(URI_PROTECTED); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); basicContext.addConstraint(sc); // Add unprotected servlet to the context Tomcat.addServlet(basicContext, "TesterServlet4", new TesterServlet()); basicContext.addServletMapping(URI_PUBLIC, "TesterServlet4"); SecurityCollection collection2 = new SecurityCollection(); collection2.addPattern(URI_PUBLIC); SecurityConstraint sc2 = new SecurityConstraint(); // do not add a role - which signals access permitted without one sc2.addCollection(collection2); basicContext.addConstraint(sc2); // Configure the authenticator and inherit the Realm from Engine LoginConfig lc = new LoginConfig(); lc.setAuthMethod("BASIC"); basicContext.setLoginConfig(lc); AuthenticatorBase basicAuthenticator = new BasicAuthenticator(); basicContext.getPipeline().addValve(basicAuthenticator); } /* * Force non-default behaviour for both Authenticators */ private void setAlwaysUseSession() { ((AuthenticatorBase)basicContext.getAuthenticator()) .setAlwaysUseSession(true); ((AuthenticatorBase)nonloginContext.getAuthenticator()) .setAlwaysUseSession(true); } /* * Force rapid timeout scanning for the Basic Authentication webapp * The StandardManager default service cycle time is 10 seconds, * with a session expiry scan every 6 cycles. */ private void setRapidSessionTimeout() { ((ManagerBase) basicContext.getManager()) .setProcessExpiresFrequency(MANAGER_EXPIRE_SESSIONS_FAST); } /* * Encapsulate the logic to generate an HTTP header * for BASIC Authentication. * Note: only used internally, so no need to validate arguments. */ private static final class BasicCredentials { private final String method; private final String username; private final String password; private final String credentials; private BasicCredentials(String aMethod, String aUsername, String aPassword) { method = aMethod; username = aUsername; password = aPassword; String userCredentials = username + ":" + password; byte[] credentialsBytes = userCredentials.getBytes(B2CConverter.ISO_8859_1); String base64auth = Base64.encodeBase64String(credentialsBytes); credentials= method + " " + base64auth; } private String getCredentials() { return credentials; } } }
55,126
Bug 55126 IAE is thrown during deployment of ServerEndPoint having multiple text decoders
null
resolved fixed
366ddff
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-21T21:07:06Z
2013-06-21T18:40:00Z
java/org/apache/tomcat/websocket/pojo/PojoMethodMapping.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.pojo; import java.io.InputStream; import java.io.Reader; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.websocket.CloseReason; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.Decoder.Binary; import javax.websocket.Decoder.BinaryStream; import javax.websocket.DeploymentException; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.PongMessage; import javax.websocket.Session; import javax.websocket.server.PathParam; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.Util; /** * For a POJO class annotated with * {@link javax.websocket.server.ServerEndpoint}, an instance of this class * creates and caches the method handler, method information and parameter * information for the onXXX calls. */ public class PojoMethodMapping { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final Method onOpen; private final Method onClose; private final Method onError; private final PojoPathParam[] onOpenParams; private final PojoPathParam[] onCloseParams; private final PojoPathParam[] onErrorParams; private final Set<MessageMethod> onMessage = new HashSet<>(); private final String wsPath; public PojoMethodMapping(Class<?> clazzPojo, Class<? extends Decoder>[] decoderClazzes, String wsPath) throws DeploymentException { this.wsPath = wsPath; List<DecoderEntry> decoders = getDecoders(decoderClazzes); Method open = null; Method close = null; Method error = null; for (Method method : clazzPojo.getMethods()) { if (open == null && method.getAnnotation(OnOpen.class) != null) { open = method; } else if (close == null && method.getAnnotation(OnClose.class) != null) { close = method; } else if (error == null && method.getAnnotation(OnError.class) != null) { error = method; } else if (method.getAnnotation(OnMessage.class) != null) { onMessage.add(new MessageMethod(method, decoders)); } } this.onOpen = open; this.onClose = close; this.onError = error; onOpenParams = getPathParams(onOpen, MethodType.ON_OPEN); onCloseParams = getPathParams(onClose, MethodType.ON_CLOSE); onErrorParams = getPathParams(onError, MethodType.ON_ERROR); } public String getWsPath() { return wsPath; } public Method getOnOpen() { return onOpen; } public Object[] getOnOpenArgs(Map<String,String> pathParameters, Session session, EndpointConfig config) throws DecodeException { return buildArgs(onOpenParams, pathParameters, session, config, null, null); } public Method getOnClose() { return onClose; } public Object[] getOnCloseArgs(Map<String,String> pathParameters, Session session, CloseReason closeReason) throws DecodeException { return buildArgs(onCloseParams, pathParameters, session, null, null, closeReason); } public Method getOnError() { return onError; } public Object[] getOnErrorArgs(Map<String,String> pathParameters, Session session, Throwable throwable) throws DecodeException { return buildArgs(onErrorParams, pathParameters, session, null, throwable, null); } public Set<MessageHandler> getMessageHandlers(Object pojo, Map<String,String> pathParameters, Session session, EndpointConfig config) { Set<MessageHandler> result = new HashSet<>(); for (MessageMethod messageMethod : onMessage) { result.add(messageMethod.getMessageHandler(pojo, pathParameters, session, config)); } return result; } private static List<DecoderEntry> getDecoders( Class<? extends Decoder>[] decoderClazzes) throws DeploymentException{ List<DecoderEntry> result = new ArrayList<>(); for (Class<? extends Decoder> decoderClazz : decoderClazzes) { Decoder instance; try { instance = decoderClazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException( sm.getString("wsRemoteEndpoint.invalidEncoder", decoderClazz.getName()), e); } DecoderEntry entry = new DecoderEntry( Util.getDecoderType(decoderClazz), instance); result.add(entry); } return result; } private static PojoPathParam[] getPathParams(Method m, MethodType methodType) { if (m == null) { return new PojoPathParam[0]; } boolean foundThrowable = false; Class<?>[] types = m.getParameterTypes(); Annotation[][] paramsAnnotations = m.getParameterAnnotations(); PojoPathParam[] result = new PojoPathParam[types.length]; for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; if (type.equals(Session.class)) { result[i] = new PojoPathParam(type, null); } else if (methodType == MethodType.ON_OPEN && type.equals(EndpointConfig.class)) { result[i] = new PojoPathParam(type, null); } else if (methodType == MethodType.ON_ERROR && type.equals(Throwable.class)) { foundThrowable = true; result[i] = new PojoPathParam(type, null); } else if (methodType == MethodType.ON_CLOSE && type.equals(CloseReason.class)) { result[i] = new PojoPathParam(type, null); } else { Annotation[] paramAnnotations = paramsAnnotations[i]; for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation.annotationType().equals( PathParam.class)) { result[i] = new PojoPathParam(type, ((PathParam) paramAnnotation).value()); break; } } // Parameters without annotations are not permitted if (result[i] == null) { throw new IllegalArgumentException(); } } } if (methodType == MethodType.ON_ERROR && !foundThrowable) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.onErrorNoThrowable", m.getName(), m.getDeclaringClass().getName())); } return result; } private static Object[] buildArgs(PojoPathParam[] pathParams, Map<String,String> pathParameters, Session session, EndpointConfig config, Throwable throwable, CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coerceToType(type, value); } catch (Exception e) { throw new DecodeException(value, sm.getString( "pojoMethodMapping.decodePathParamFail", value, type), e); } } } return result; } private static class MessageMethod { private final Method m; private int indexString = -1; private int indexByteArray = -1; private int indexByteBuffer = -1; private int indexPong = -1; private int indexBoolean = -1; private int indexSession = -1; private int indexInputStream = -1; private int indexReader = -1; private int indexPrimitive = -1; private Map<Integer,PojoPathParam> indexPathParams = new HashMap<>(); private int indexPayload = -1; public MessageMethod(Method m, List<DecoderEntry> decoderEntries) { this.m = m; Class<?>[] types = m.getParameterTypes(); Annotation[][] paramsAnnotations = m.getParameterAnnotations(); for (int i = 0; i < types.length; i++) { boolean paramFound = false; Annotation[] paramAnnotations = paramsAnnotations[i]; for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation.annotationType().equals( PathParam.class)) { indexPathParams.put( Integer.valueOf(i), new PojoPathParam(types[i], ((PathParam) paramAnnotation).value())); paramFound = true; break; } } if (paramFound) { continue; } if (String.class.isAssignableFrom(types[i])) { if (indexString == -1) { indexString = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (Reader.class.isAssignableFrom(types[i])) { if (indexReader == -1) { indexReader = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (boolean.class == types[i]) { if (indexBoolean == -1) { indexBoolean = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateLastParam", m.getName(), m.getDeclaringClass().getName())); } } else if (ByteBuffer.class.isAssignableFrom(types[i])) { if (indexByteBuffer == -1) { indexByteBuffer = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (byte[].class == types[i]) { if (indexByteArray == -1) { indexByteArray = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (InputStream.class.isAssignableFrom(types[i])) { if (indexInputStream == -1) { indexInputStream = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (Util.isPrimitive(types[i])) { if (indexPrimitive == -1) { indexPrimitive = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (Session.class.isAssignableFrom(types[i])) { if (indexSession == -1) { indexSession = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateSessionParam", m.getName(), m.getDeclaringClass().getName())); } } else if (PongMessage.class.isAssignableFrom(types[i])) { if (indexPong == -1) { indexPong = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicatePongMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else { for (DecoderEntry decoderEntry : decoderEntries) { if (decoderEntry.getClazz().isAssignableFrom( types[i])) { if (Binary.class.isAssignableFrom( decoderEntry.getDecoder().getClass()) || BinaryStream.class.isAssignableFrom( decoderEntry.getDecoder().getClass())) { if (indexByteBuffer == -1) { indexByteBuffer = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } break; } else { if (indexString == -1) { indexString = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } } } } } // Additional checks required if (indexString != -1) { indexPayload = indexString; } if (indexReader != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexReader; } } if (indexByteArray != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexByteArray; } } if (indexByteBuffer != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexByteBuffer; } } if (indexInputStream != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexInputStream; } } if (indexPrimitive != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexPrimitive; } } if (indexPong != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.pongWithPayload", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexPong; } } if (indexPayload == -1 && indexPrimitive == -1 && indexBoolean != -1) { // The boolean we found is a payload, not a last flag indexPayload = indexBoolean; indexPrimitive = indexBoolean; indexBoolean = -1; } if (indexPayload == -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.noPayload", m.getName(), m.getDeclaringClass().getName())); } if (indexPong != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialPong", m.getName(), m.getDeclaringClass().getName())); } if(indexReader != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialReader", m.getName(), m.getDeclaringClass().getName())); } if(indexInputStream != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialInputStream", m.getName(), m.getDeclaringClass().getName())); } } public MessageHandler getMessageHandler(Object pojo, Map<String,String> pathParameters, Session session, EndpointConfig config) { Object[] params = new Object[m.getParameterTypes().length]; for (Map.Entry<Integer,PojoPathParam> entry : indexPathParams.entrySet()) { PojoPathParam pathParam = entry.getValue(); String valueString = pathParameters.get(pathParam.getName()); Object value = null; try { value = Util.coerceToType(pathParam.getType(), valueString); } catch (Exception e) { DecodeException de = new DecodeException(valueString, sm.getString( "pojoMethodMapping.decodePathParamFail", valueString, pathParam.getType()), e); params = new Object[] { de }; } params[entry.getKey().intValue()] = value; } MessageHandler mh = null; if (indexBoolean == -1) { // Basic if (indexString != -1) { mh = new PojoMessageHandlerWholeText(pojo, m, session, config, params, indexString, false, indexSession); } else if (indexPrimitive != -1) { mh = new PojoMessageHandlerWholeText(pojo, m, session, config, params, indexPrimitive, false, indexSession); } else if (indexByteArray != -1) { mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, params, indexByteArray, true, indexSession, false); } else if (indexByteBuffer != -1) { mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, params, indexByteBuffer, false, indexSession, false); } else if (indexInputStream != -1) { mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, params, indexInputStream, true, indexSession, true); } else if (indexReader != -1) { mh = new PojoMessageHandlerWholeText(pojo, m, session, config, params, indexReader, true, indexSession); } else { mh = new PojoMessageHandlerWholePong(pojo, m, session, params, indexPong, false, indexSession); } } else { // ASync if (indexString != -1) { mh = new PojoMessageHandlerPartialText(pojo, m, session, params, indexString, false, indexBoolean, indexSession); } else if (indexByteArray != -1) { mh = new PojoMessageHandlerPartialBinary(pojo, m, session, params, indexByteArray, true, indexBoolean, indexSession); } else { mh = new PojoMessageHandlerPartialBinary(pojo, m, session, params, indexByteBuffer, false, indexBoolean, indexSession); } } return mh; } } private static class DecoderEntry { private final Class<?> clazz; private final Decoder decoder; public DecoderEntry(Class<?> clazz, Decoder decoder) { this.clazz = clazz; this.decoder = decoder; } public Class<?> getClazz() { return clazz; } public Decoder getDecoder() { return decoder; } } private static enum MethodType { ON_OPEN, ON_CLOSE, ON_ERROR } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
java/org/apache/tomcat/websocket/WsRemoteEndpointImplBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import javax.websocket.DeploymentException; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.RemoteEndpoint; import javax.websocket.SendHandler; import javax.websocket.SendResult; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; public abstract class WsRemoteEndpointImplBase implements RemoteEndpoint { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final Log log = LogFactory.getLog(WsRemoteEndpointImplBase.class); private boolean messagePartInProgress = false; private final Queue<MessagePart> messagePartQueue = new ArrayDeque<>(); private final Object messagePartLock = new Object(); private boolean dataMessageInProgress = false; // State private boolean closed = false; private boolean fragmented = false; private boolean nextFragmented = false; private boolean text = false; private boolean nextText = false; // Max size of WebSocket header is 14 bytes private final ByteBuffer headerBuffer = ByteBuffer.allocate(14); private final ByteBuffer outputBuffer = ByteBuffer.allocate(8192); private final CharsetEncoder encoder = Charset.forName("UTF8").newEncoder(); private final ByteBuffer encoderBuffer = ByteBuffer.allocate(8192); private final AtomicBoolean batchingAllowed = new AtomicBoolean(false); private volatile long sendTimeout = -1; private WsSession wsSession; private List<EncoderEntry> encoderEntries = new ArrayList<>(); public long getSendTimeout() { return sendTimeout; } public void setSendTimeout(long timeout) { this.sendTimeout = timeout; } @Override public void setBatchingAllowed(boolean batchingAllowed) throws IOException { boolean oldValue = this.batchingAllowed.getAndSet(batchingAllowed); if (oldValue && !batchingAllowed) { flushBatch(); } } @Override public boolean getBatchingAllowed() { return batchingAllowed.get(); } @Override public void flushBatch() throws IOException { startMessageBlock(Constants.INTERNAL_OPCODE_FLUSH, null, true); } public void sendBytes(ByteBuffer data) throws IOException { startMessageBlock(Constants.OPCODE_BINARY, data, true); } public Future<Void> sendBytesByFuture(ByteBuffer data) { FutureToSendHandler f2sh = new FutureToSendHandler(); sendBytesByCompletion(data, f2sh); return f2sh; } public void sendBytesByCompletion(ByteBuffer data, SendHandler handler) { startMessage(Constants.OPCODE_BINARY, data, true, handler); } public void sendPartialBytes(ByteBuffer partialByte, boolean last) throws IOException { startMessageBlock(Constants.OPCODE_BINARY, partialByte, last); } @Override public void sendPing(ByteBuffer applicationData) throws IOException, IllegalArgumentException { startMessageBlock(Constants.OPCODE_PING, applicationData, true); } @Override public void sendPong(ByteBuffer applicationData) throws IOException, IllegalArgumentException { startMessageBlock(Constants.OPCODE_PONG, applicationData, true); } public void sendString(String text) throws IOException { sendPartialString(CharBuffer.wrap(text), true); } public Future<Void> sendStringByFuture(String text) { FutureToSendHandler f2sh = new FutureToSendHandler(); sendStringByCompletion(text, f2sh); return f2sh; } public void sendStringByCompletion(String text, SendHandler handler) { TextMessageSendHandler tmsh = new TextMessageSendHandler(handler, CharBuffer.wrap(text), true, encoder, encoderBuffer, this); tmsh.write(); } public void sendPartialString(String fragment, boolean isLast) throws IOException { sendPartialString(CharBuffer.wrap(fragment), isLast); } public OutputStream getSendStream() { return new WsOutputStream(this); } public Writer getSendWriter() { return new WsWriter(this); } void sendPartialString(CharBuffer part, boolean last) throws IOException { try { FutureToSendHandler f2sh = new FutureToSendHandler(); TextMessageSendHandler tmsh = new TextMessageSendHandler(f2sh, part, last, encoder, encoderBuffer, this); tmsh.write(); f2sh.get(); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } } void startMessageBlock(byte opCode, ByteBuffer payload, boolean last) throws IOException { FutureToSendHandler f2sh = new FutureToSendHandler(); startMessage(opCode, payload, last, f2sh); try { f2sh.get(); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } } void startMessage(byte opCode, ByteBuffer payload, boolean last, SendHandler handler) { wsSession.updateLastActive(); MessagePart mp = new MessagePart(opCode, payload, last, handler, this); synchronized (messagePartLock) { if (Constants.OPCODE_CLOSE == mp.getOpCode()) { try { setBatchingAllowed(false); } catch (IOException e) { log.warn(sm.getString( "wsRemoteEndpoint.flushOnCloseFailed"), e); } } if (messagePartInProgress) { if (!Util.isControl(opCode)) { if (dataMessageInProgress) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.inProgress")); } else { dataMessageInProgress = true; } } messagePartQueue.add(mp); } else { messagePartInProgress = true; writeMessagePart(mp); } } } void endMessage(SendHandler handler, SendResult result, boolean dataMessage) { synchronized (messagePartLock) { fragmented = nextFragmented; text = nextText; if (dataMessage) { dataMessageInProgress = false; } MessagePart mpNext = messagePartQueue.poll(); if (mpNext == null) { messagePartInProgress = false; } else { writeMessagePart(mpNext); } } wsSession.updateLastActive(); handler.onResult(result); } void writeMessagePart(MessagePart mp) { if (closed) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.closed")); } if (Constants.INTERNAL_OPCODE_FLUSH == mp.getOpCode()) { nextFragmented = fragmented; nextText = text; doWrite(mp.getHandler(), outputBuffer); return; } // Control messages may be sent in the middle of fragmented message // so they have no effect on the fragmented or text flags boolean first; if (Util.isControl(mp.getOpCode())) { nextFragmented = fragmented; nextText = text; if (mp.getOpCode() == Constants.OPCODE_CLOSE) { closed = true; } first = true; } else { boolean isText = Util.isText(mp.getOpCode()); if (fragmented) { // Currently fragmented if (text != isText) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.changeType")); } nextText = text; nextFragmented = !mp.isLast(); first = false; } else { // Wasn't fragmented. Might be now if (mp.isLast()) { nextFragmented = false; } else { nextFragmented = true; nextText = isText; } first = true; } } byte[] mask; if (isMasked()) { mask = Util.generateMask(); } else { mask = null; } headerBuffer.clear(); writeHeader(headerBuffer, mp.getOpCode(), mp.getPayload(), first, mp.isLast(), isMasked(), mask); headerBuffer.flip(); if (getBatchingAllowed() || isMasked()) { // Need to write via output buffer OutputBufferSendHandler obsh = new OutputBufferSendHandler( mp.getHandler(), headerBuffer, mp.getPayload(), mask, outputBuffer, !getBatchingAllowed(), this); obsh.write(); } else { // Can write directly doWrite(mp.getHandler(), headerBuffer, mp.getPayload()); } } private static class MessagePart { private final byte opCode; private final ByteBuffer payload; private final boolean last; private final SendHandler handler; public MessagePart(byte opCode, ByteBuffer payload, boolean last, SendHandler handler, WsRemoteEndpointImplBase endpoint) { this.opCode = opCode; this.payload = payload; this.last = last; this.handler = new EndMessageHandler( endpoint, handler, !Util.isControl(opCode)); } public byte getOpCode() { return opCode; } public ByteBuffer getPayload() { return payload; } public boolean isLast() { return last; } public SendHandler getHandler() { return handler; } } /** * Wraps the user provided handler so that the end point is notified when * the message is complete. */ private static class EndMessageHandler implements SendHandler { private final WsRemoteEndpointImplBase endpoint; private final SendHandler handler; private final boolean dataMessage; public EndMessageHandler(WsRemoteEndpointImplBase endpoint, SendHandler handler, boolean dataMessage) { this.endpoint = endpoint; this.handler = handler; this.dataMessage = dataMessage; } @Override public void onResult(SendResult result) { endpoint.endMessage(handler, result, dataMessage); } } public void sendObject(Object obj) throws IOException { Future<Void> f = sendObjectByFuture(obj); try { f.get(); } catch (InterruptedException | ExecutionException e) { throw new IOException(e); } } public Future<Void> sendObjectByFuture(Object obj) { FutureToSendHandler f2sh = new FutureToSendHandler(); sendObjectByCompletion(obj, f2sh); return f2sh; } @SuppressWarnings({"unchecked", "rawtypes"}) public void sendObjectByCompletion(Object obj, SendHandler completion) { if (Util.isPrimitive(obj.getClass())) { String msg = obj.toString(); sendStringByCompletion(msg, completion); return; } Encoder encoder = findEncoder(obj); try { if (encoder instanceof Encoder.Text) { String msg = ((Encoder.Text) encoder).encode(obj); sendStringByCompletion(msg, completion); } else if (encoder instanceof Encoder.TextStream) { try (Writer w = getSendWriter()) { ((Encoder.TextStream) encoder).encode(obj, w); } completion.onResult(new SendResult()); } else if (encoder instanceof Encoder.Binary) { ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj); sendBytesByCompletion(msg, completion); } else if (encoder instanceof Encoder.BinaryStream) { try (OutputStream os = getSendStream()) { ((Encoder.BinaryStream) encoder).encode(obj, os); } completion.onResult(new SendResult()); } else { throw new EncodeException(obj, sm.getString( "wsRemoteEndpoint.noEncoder", obj.getClass())); } } catch (EncodeException | IOException e) { SendResult sr = new SendResult(e); completion.onResult(sr); } } protected void setSession(WsSession wsSession) { this.wsSession = wsSession; } protected void setEncoders(List<Class<? extends Encoder>> encoders) throws DeploymentException { encoderEntries.clear(); for (Class<? extends Encoder> encoderClazz : encoders) { Encoder instance; try { instance = encoderClazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException( sm.getString("wsRemoteEndpoint.invalidEncoder", encoderClazz.getName()), e); } EncoderEntry entry = new EncoderEntry( Util.getEncoderType(encoderClazz), instance); encoderEntries.add(entry); } } private Encoder findEncoder(Object obj) { for (EncoderEntry entry : encoderEntries) { if (entry.getClazz().isAssignableFrom(obj.getClass())) { return entry.getEncoder(); } } return null; } protected abstract void doWrite(SendHandler handler, ByteBuffer... data); protected abstract boolean isMasked(); protected abstract void close(); private static void writeHeader(ByteBuffer headerBuffer, byte opCode, ByteBuffer payload, boolean first, boolean last, boolean masked, byte[] mask) { byte b = 0; if (last) { // Set the fin bit b = -128; } if (first) { // This is the first fragment of this message b = (byte) (b + opCode); } // If not the first fragment, it is a continuation with opCode of zero headerBuffer.put(b); if (masked) { b = (byte) 0x80; } else { b = 0; } // Next write the mask && length length if (payload.limit() < 126) { headerBuffer.put((byte) (payload.limit() | b)); } else if (payload.limit() < 65536) { headerBuffer.put((byte) (126 | b)); headerBuffer.put((byte) (payload.limit() >>> 8)); headerBuffer.put((byte) (payload.limit() & 0xFF)); } else { // Will never be more than 2^31-1 headerBuffer.put((byte) (127 | b)); headerBuffer.put((byte) 0); headerBuffer.put((byte) 0); headerBuffer.put((byte) 0); headerBuffer.put((byte) 0); headerBuffer.put((byte) (payload.limit() >>> 24)); headerBuffer.put((byte) (payload.limit() >>> 16)); headerBuffer.put((byte) (payload.limit() >>> 8)); headerBuffer.put((byte) (payload.limit() & 0xFF)); } if (masked) { headerBuffer.put(mask[0]); headerBuffer.put(mask[1]); headerBuffer.put(mask[2]); headerBuffer.put(mask[3]); } } private static class TextMessageSendHandler implements SendHandler { private final SendHandler handler; private final CharBuffer message; private final boolean isLast; private final CharsetEncoder encoder; private final ByteBuffer buffer; private final WsRemoteEndpointImplBase endpoint; private volatile boolean isDone = false; public TextMessageSendHandler(SendHandler handler, CharBuffer message, boolean isLast, CharsetEncoder encoder, ByteBuffer encoderBuffer, WsRemoteEndpointImplBase endpoint) { this.handler = handler; this.message = message; this.isLast = isLast; this.encoder = encoder.reset(); this.buffer = encoderBuffer; this.endpoint = endpoint; } public void write() { buffer.clear(); CoderResult cr = encoder.encode(message, buffer, true); if (cr.isError()) { throw new IllegalArgumentException(cr.toString()); } isDone = !cr.isOverflow(); buffer.flip(); endpoint.startMessage(Constants.OPCODE_TEXT, buffer, isDone && isLast, this); } @Override public void onResult(SendResult result) { if (isDone || !result.isOK()) { handler.onResult(result); } else { write(); } } } /** * Used to write data to the output buffer, flushing the buffer if it fills * up. */ private static class OutputBufferSendHandler implements SendHandler { private final SendHandler handler; private final ByteBuffer headerBuffer; private final ByteBuffer payload; private final byte[] mask; private final ByteBuffer outputBuffer; private final boolean flushRequired; private final WsRemoteEndpointImplBase endpoint; private int maskIndex = 0; public OutputBufferSendHandler(SendHandler completion, ByteBuffer headerBuffer, ByteBuffer payload, byte[] mask, ByteBuffer outputBuffer, boolean flushRequired, WsRemoteEndpointImplBase endpoint) { this.handler = completion; this.headerBuffer = headerBuffer; this.payload = payload; this.mask = mask; this.outputBuffer = outputBuffer; this.flushRequired = flushRequired; this.endpoint = endpoint; } public void write() { // Write the header while (headerBuffer.hasRemaining() && outputBuffer.hasRemaining()) { outputBuffer.put(headerBuffer.get()); } if (headerBuffer.hasRemaining()) { // Still more headers to write, need to flush outputBuffer.flip(); endpoint.doWrite(this, outputBuffer); return; } // Write the payload while (payload.hasRemaining() && outputBuffer.hasRemaining()) { outputBuffer.put( (byte) (payload.get() ^ (mask[maskIndex++] & 0xFF))); if (maskIndex > 3) { maskIndex = 0; } } if (payload.hasRemaining()) { // Still more headers to write, need to flush outputBuffer.flip(); endpoint.doWrite(this, outputBuffer); return; } if (flushRequired) { outputBuffer.flip(); if (outputBuffer.remaining() == 0) { handler.onResult(new SendResult()); } else { endpoint.doWrite(this, outputBuffer); } } else { handler.onResult(new SendResult()); } } // ------------------------------------------------- SendHandler methods @Override public void onResult(SendResult result) { if (result.isOK()) { if (outputBuffer.hasRemaining()) { endpoint.doWrite(this, outputBuffer); } else { outputBuffer.clear(); write(); } } else { handler.onResult(result); } } } /** * Converts a Future to a SendHandler. */ private static class FutureToSendHandler implements Future<Void>, SendHandler { private final CountDownLatch latch = new CountDownLatch(1); private volatile SendResult result = null; // --------------------------------------------------------- SendHandler @Override public void onResult(SendResult result) { this.result = result; latch.countDown(); } // -------------------------------------------------------------- Future @Override public boolean cancel(boolean mayInterruptIfRunning) { // Cancelling the task is not supported return false; } @Override public boolean isCancelled() { // Cancelling the task is not supported return false; } @Override public boolean isDone() { return latch.getCount() == 0; } @Override public Void get() throws InterruptedException, ExecutionException { latch.await(); if (result.getException() != null) { throw new ExecutionException(result.getException()); } return null; } @Override public Void get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { boolean retval = latch.await(timeout, unit); if (retval == false) { throw new TimeoutException(); } if (result.getException() != null) { throw new ExecutionException(result.getException()); } return null; } } private static class WsOutputStream extends OutputStream { private final WsRemoteEndpointImplBase endpoint; private final ByteBuffer buffer = ByteBuffer.allocate(8192); private final Object closeLock = new Object(); private volatile boolean closed = false; public WsOutputStream(WsRemoteEndpointImplBase endpoint) { this.endpoint = endpoint; } @Override public void write(int b) throws IOException { if (closed) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.closedOutputStream")); } if (buffer.remaining() == 0) { flush(); } buffer.put((byte) b); } @Override public void write(byte[] b, int off, int len) throws IOException { if (closed) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.closedOutputStream")); } if (len == 0) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (buffer.remaining() == 0) { flush(); } int remaining = buffer.remaining(); int written = 0; while (remaining < len - written) { buffer.put(b, off + written, remaining); written += remaining; flush(); remaining = buffer.remaining(); } buffer.put(b, off + written, len - written); } @Override public void flush() throws IOException { if (closed) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.closedOutputStream")); } doWrite(false); } @Override public void close() throws IOException { synchronized (closeLock) { if (closed) { return; } closed = true; } doWrite(true); } private void doWrite(boolean last) throws IOException { buffer.flip(); endpoint.sendPartialBytes(buffer, last); buffer.clear(); } } private static class WsWriter extends Writer { private final WsRemoteEndpointImplBase endpoint; private final CharBuffer buffer = CharBuffer.allocate(8192); private final Object closeLock = new Object(); private volatile boolean closed = false; public WsWriter(WsRemoteEndpointImplBase endpoint) { this.endpoint = endpoint; } @Override public void write(char[] cbuf, int off, int len) throws IOException { if (closed) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.closedWriter")); } if (len == 0) { return; } if ((off < 0) || (off > cbuf.length) || (len < 0) || ((off + len) > cbuf.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); } if (buffer.remaining() == 0) { flush(); } int remaining = buffer.remaining(); int written = 0; while (remaining < len - written) { buffer.put(cbuf, off + written, remaining); written += remaining; flush(); remaining = buffer.remaining(); } buffer.put(cbuf, off + written, len - written); } @Override public void flush() throws IOException { if (closed) { throw new IllegalStateException( sm.getString("wsRemoteEndpoint.closedWriter")); } doWrite(false); } @Override public void close() throws IOException { synchronized (closeLock) { if (closed) { return; } closed = true; } doWrite(true); } private void doWrite(boolean last) throws IOException { buffer.flip(); endpoint.sendPartialString(buffer, last); buffer.clear(); } } private static class EncoderEntry { private final Class<?> clazz; private final Encoder encoder; public EncoderEntry(Class<?> clazz, Encoder encoder) { this.clazz = clazz; this.encoder = encoder; } public Class<?> getClazz() { return clazz; } public Encoder getEncoder() { return encoder; } } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
java/org/apache/tomcat/websocket/WsRemoteEndpointImplClient.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.nio.ByteBuffer; import java.util.concurrent.TimeUnit; import javax.websocket.SendHandler; public class WsRemoteEndpointImplClient extends WsRemoteEndpointImplBase { private final AsyncChannelWrapper channel; public WsRemoteEndpointImplClient(AsyncChannelWrapper channel) { this.channel = channel; } @Override protected boolean isMasked() { return true; } @Override protected void doWrite(SendHandler handler, ByteBuffer... data) { long timeout = getSendTimeout(); if (timeout < 1) { timeout = Long.MAX_VALUE; } SendHandlerToCompletionHandler sh2ch = new SendHandlerToCompletionHandler(handler); channel.write(data, 0, data.length, timeout, TimeUnit.MILLISECONDS, null, sh2ch); } @Override protected void close() { channel.close(); } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
java/org/apache/tomcat/websocket/WsSession.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.IOException; import java.lang.reflect.Type; import java.net.URI; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.security.Principal; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.DeploymentException; import javax.websocket.Encoder; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.MessageHandler; import javax.websocket.PongMessage; import javax.websocket.RemoteEndpoint; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; public class WsSession implements Session { private static final Charset UTF8 = Charset.forName("UTF8"); private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static AtomicLong ids = new AtomicLong(0); private final Log log = LogFactory.getLog(WsSession.class); private final Endpoint localEndpoint; private final WsRemoteEndpointImplBase wsRemoteEndpoint; private final RemoteEndpoint.Async remoteEndpointAsync; private final RemoteEndpoint.Basic remoteEndpointBasic; private final ClassLoader applicationClassLoader; private final WsWebSocketContainer webSocketContainer; private final URI requestUri; private final Map<String,List<String>> requestParameterMap; private final String queryString; private final Principal userPrincipal; private final String subProtocol; private final Map<String,String> pathParameters; private final boolean secure; private final String id; private MessageHandler textMessageHandler = null; private MessageHandler binaryMessageHandler = null; private MessageHandler.Whole<PongMessage> pongMessageHandler = null; private volatile State state = State.OPEN; private final Object stateLock = new Object(); private final Map<String,Object> userProperties = new ConcurrentHashMap<>(); private volatile int maxBinaryMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private volatile int maxTextMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private volatile long maxIdleTimeout = 0; private volatile long lastActive = System.currentTimeMillis(); /** * Creates a new WebSocket session for communication between the two * provided end points. The result of {@link Thread#getContextClassLoader()} * at the time this constructor is called will be used when calling * {@link Endpoint#onClose(Session, CloseReason)}. * * @param localEndpoint * @param wsRemoteEndpoint * @throws DeploymentException */ public WsSession(Endpoint localEndpoint, WsRemoteEndpointImplBase wsRemoteEndpoint, WsWebSocketContainer wsWebSocketContainer, URI requestUri, Map<String,List<String>> requestParameterMap, String queryString, Principal userPrincipal, String subProtocol, Map<String,String> pathParameters, boolean secure, List<Class<? extends Encoder>> encoders, Map<String,Object> userProperties) throws DeploymentException { this.localEndpoint = localEndpoint; this.wsRemoteEndpoint = wsRemoteEndpoint; this.wsRemoteEndpoint.setSession(this); this.remoteEndpointAsync = new WsRemoteEndpointAsync(wsRemoteEndpoint); this.remoteEndpointBasic = new WsRemoteEndpointBasic(wsRemoteEndpoint); this.webSocketContainer = wsWebSocketContainer; applicationClassLoader = Thread.currentThread().getContextClassLoader(); wsRemoteEndpoint.setSendTimeout( wsWebSocketContainer.getDefaultAsyncSendTimeout()); this.maxBinaryMessageBufferSize = webSocketContainer.getDefaultMaxBinaryMessageBufferSize(); this.maxTextMessageBufferSize = webSocketContainer.getDefaultMaxTextMessageBufferSize(); this.maxIdleTimeout = webSocketContainer.getDefaultMaxSessionIdleTimeout(); this.requestUri = requestUri; if (requestParameterMap == null) { this.requestParameterMap = Collections.EMPTY_MAP; } else { this.requestParameterMap = requestParameterMap; } this.queryString = queryString; this.userPrincipal = userPrincipal; if (subProtocol == null) { this.subProtocol = ""; } else { this.subProtocol = subProtocol; } this.pathParameters = pathParameters; this.secure = secure; this.wsRemoteEndpoint.setEncoders(encoders); this.userProperties.putAll(userProperties); this.id = Long.toHexString(ids.getAndIncrement()); } @Override public WebSocketContainer getContainer() { checkState(); return webSocketContainer; } @SuppressWarnings("unchecked") @Override public void addMessageHandler(MessageHandler listener) { checkState(); Type t = Util.getMessageType(listener); if (String.class.isAssignableFrom((Class<?>) t)) { if (textMessageHandler != null) { throw new IllegalStateException( sm.getString("wsSession.duplicateHandlerText")); } textMessageHandler = listener; } else if (ByteBuffer.class.isAssignableFrom((Class<?>) t)) { if (binaryMessageHandler != null) { throw new IllegalStateException( sm.getString("wsSession.duplicateHandlerBinary")); } binaryMessageHandler = listener; } else if (PongMessage.class.isAssignableFrom((Class<?>) t)) { if (pongMessageHandler != null) { throw new IllegalStateException( sm.getString("wsSession.duplicateHandlerPong")); } if (listener instanceof MessageHandler.Whole<?>) { pongMessageHandler = (MessageHandler.Whole<PongMessage>) listener; } else { throw new IllegalStateException( sm.getString("wsSession.invalidHandlerTypePong")); } } else { throw new IllegalArgumentException( sm.getString("wsSession.unknownHandler", listener, t)); } } @Override public Set<MessageHandler> getMessageHandlers() { checkState(); Set<MessageHandler> result = new HashSet<>(); if (binaryMessageHandler != null) { result.add(binaryMessageHandler); } if (textMessageHandler != null) { result.add(textMessageHandler); } if (pongMessageHandler != null) { result.add(pongMessageHandler); } return result; } @Override public void removeMessageHandler(MessageHandler listener) { checkState(); if (listener == null) { return; } if (listener.equals(textMessageHandler)) { textMessageHandler = null; return; } else if (listener.equals(binaryMessageHandler)) { binaryMessageHandler = null; return; } else if (listener.equals(pongMessageHandler)) { pongMessageHandler = null; return; } // ISE for now. Could swallow this silently / log this if the ISE // becomes a problem throw new IllegalStateException( sm.getString("wsSession.removeHandlerFailed", listener)); } @Override public String getProtocolVersion() { checkState(); return Constants.WS_VERSION_HEADER_VALUE; } @Override public String getNegotiatedSubprotocol() { checkState(); return subProtocol; } @Override public List<Extension> getNegotiatedExtensions() { checkState(); return Collections.EMPTY_LIST; } @Override public boolean isSecure() { checkState(); return secure; } @Override public boolean isOpen() { return state == State.OPEN; } @Override public long getMaxIdleTimeout() { checkState(); return maxIdleTimeout; } @Override public void setMaxIdleTimeout(long timeout) { checkState(); this.maxIdleTimeout = timeout; } @Override public void setMaxBinaryMessageBufferSize(int max) { checkState(); this.maxBinaryMessageBufferSize = max; } @Override public int getMaxBinaryMessageBufferSize() { checkState(); return maxBinaryMessageBufferSize; } @Override public void setMaxTextMessageBufferSize(int max) { checkState(); this.maxTextMessageBufferSize = max; } @Override public int getMaxTextMessageBufferSize() { checkState(); return maxTextMessageBufferSize; } @Override public Set<Session> getOpenSessions() { checkState(); return webSocketContainer.getOpenSessions(localEndpoint.getClass()); } @Override public RemoteEndpoint.Async getAsyncRemote() { checkState(); return remoteEndpointAsync; } @Override public RemoteEndpoint.Basic getBasicRemote() { checkState(); return remoteEndpointBasic; } @Override public void close() throws IOException { close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "")); } @Override public void close(CloseReason closeReason) throws IOException { doClose(closeReason, closeReason); } /** * WebSocket 1.0. Section 2.1.5. * Need internal close method as spec requires that the local endpoint * receives a 1006 on timeout. */ private void doClose(CloseReason closeReasonMessage, CloseReason closeReasonLocal) { // Double-checked locking. OK because state is volatile if (state != State.OPEN) { return; } synchronized (stateLock) { if (state != State.OPEN) { return; } state = State.CLOSING; sendCloseMessage(closeReasonMessage); fireEndpointOnClose(closeReasonLocal); state = State.CLOSED; } } /** * Called when a close message is received. Should only ever happen once. * Also called after a protocol error when the ProtocolHandler needs to * force the closing of the connection. */ public void onClose(CloseReason closeReason) { synchronized (stateLock) { if (state == State.OPEN) { sendCloseMessage(closeReason); fireEndpointOnClose(closeReason); state = State.CLOSED; } // Close the socket wsRemoteEndpoint.close(); } } private void fireEndpointOnClose(CloseReason closeReason) { // Fire the onClose event Thread t = Thread.currentThread(); ClassLoader cl = t.getContextClassLoader(); t.setContextClassLoader(applicationClassLoader); try { localEndpoint.onClose(this, closeReason); } finally { t.setContextClassLoader(cl); } } private void sendCloseMessage(CloseReason closeReason) { // 125 is maximum size for the payload of a control message ByteBuffer msg = ByteBuffer.allocate(125); msg.putShort((short) closeReason.getCloseCode().getCode()); String reason = closeReason.getReasonPhrase(); if (reason != null && reason.length() > 0) { msg.put(reason.getBytes(UTF8)); } msg.flip(); try { wsRemoteEndpoint.startMessageBlock( Constants.OPCODE_CLOSE, msg, true); } catch (IOException ioe) { // Failed to send close message. Close the socket and let the caller // deal with the Exception log.error(sm.getString("wsSession.sendCloseFail"), ioe); wsRemoteEndpoint.close(); localEndpoint.onError(this, ioe); } finally { webSocketContainer.unregisterSession( localEndpoint.getClass(), this); } } @Override public URI getRequestURI() { checkState(); return requestUri; } @Override public Map<String,List<String>> getRequestParameterMap() { checkState(); return requestParameterMap; } @Override public String getQueryString() { checkState(); return queryString; } @Override public Principal getUserPrincipal() { checkState(); return userPrincipal; } @Override public Map<String,String> getPathParameters() { checkState(); return pathParameters; } @Override public String getId() { return id; } @Override public Map<String,Object> getUserProperties() { checkState(); return userProperties; } public Endpoint getLocal() { return localEndpoint; } protected MessageHandler getTextMessageHandler() { return textMessageHandler; } protected MessageHandler getBinaryMessageHandler() { return binaryMessageHandler; } protected MessageHandler.Whole<PongMessage> getPongMessageHandler() { return pongMessageHandler; } protected void updateLastActive() { lastActive = System.currentTimeMillis(); } protected void expire() { long timeout = maxIdleTimeout; if (timeout < 1) { return; } if (System.currentTimeMillis() - lastActive > timeout) { String msg = sm.getString("wsSession.timeout"); doClose(new CloseReason(CloseCodes.GOING_AWAY, msg), new CloseReason(CloseCodes.CLOSED_ABNORMALLY, msg)); } } private void checkState() { if (state == State.CLOSED) { throw new IllegalStateException(sm.getString("wsSession.closed")); } } private static enum State { OPEN, CLOSING, CLOSED } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
java/org/apache/tomcat/websocket/WsWebSocketContainer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousSocketChannel; import java.nio.charset.Charset; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; import javax.websocket.ClientEndpoint; import javax.websocket.ClientEndpointConfig; import javax.websocket.ClientEndpointConfig.Builder; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.HandshakeResponse; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.codec.binary.Base64; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.util.threads.ThreadPoolExecutor; import org.apache.tomcat.websocket.pojo.PojoEndpointClient; public class WsWebSocketContainer implements WebSocketContainer, BackgroundProcess { /** * Property name to set to configure the value that is passed to * {@link SSLEngine#setEnabledProtocols(String[])}. The value should be a * comma separated string. */ public static final String SSL_PROTOCOLS_PROPERTY = "org.apache.tomcat.websocket.SSL_PROTOCOLS"; public static final String SSL_TRUSTSTORE_PROPERTY = "org.apache.tomcat.websocket.SSL_TRUSTSTORE"; public static final String SSL_TRUSTSTORE_PWD_PROPERTY = "org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD"; public static final String SSL_TRUSTSTORE_PWD_DEFAULT = "changeit"; private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final Random random = new Random(); private static final Charset iso88591 = Charset.forName("ISO-8859-1"); private static final byte[] crlf = new byte[] {13, 10}; private static final AsynchronousChannelGroup asynchronousChannelGroup; static { AsynchronousChannelGroup result = null; // Need to do this with the right thread context class loader else the // first web app to call this will trigger a leak ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( AsyncIOThreadFactory.class.getClassLoader()); // These are the same settings as the default // AsynchronousChannelGroup int initialSize = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new AsyncIOThreadFactory()); try { result = AsynchronousChannelGroup.withCachedThreadPool( executorService, initialSize); } catch (IOException e) { // No good reason for this to happen. throw new IllegalStateException(sm.getString( "wsWebSocketContainer.asynchronousChannelGroupFail")); } } finally { Thread.currentThread().setContextClassLoader(original); } asynchronousChannelGroup = result; } private final Log log = LogFactory.getLog(WsWebSocketContainer.class); private final Map<Class<?>, Set<WsSession>> endpointSessionMap = new HashMap<>(); private final Map<WsSession,WsSession> sessions = new ConcurrentHashMap<>(); private final Object endPointSessionMapLock = new Object(); private long defaultAsyncTimeout = -1; private int maxBinaryMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private int maxTextMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private volatile long defaultMaxSessionIdleTimeout = 0; private int backgroundProcessCount = 0; private int processPeriod = 10; @Override public Session connectToServer(Object pojo, URI path) throws DeploymentException { ClientEndpoint annotation = pojo.getClass().getAnnotation(ClientEndpoint.class); if (annotation == null) { throw new DeploymentException( sm.getString("wsWebSocketContainer.missingAnnotation", pojo.getClass().getName())); } Endpoint ep = new PojoEndpointClient(pojo, annotation.decoders()); Class<? extends ClientEndpointConfig.Configurator> configuratorClazz = pojo.getClass().getAnnotation( ClientEndpoint.class).configurator(); ClientEndpointConfig.Configurator configurator = null; if (!ClientEndpointConfig.Configurator.class.equals( configuratorClazz)) { try { configurator = configuratorClazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.defaultConfiguratorFail"), e); } } ClientEndpointConfig config = ClientEndpointConfig.Builder.create(). configurator(configurator). decoders(Arrays.asList(annotation.decoders())). encoders(Arrays.asList(annotation.encoders())). build(); return connectToServer(ep, config, path); } @SuppressWarnings("unchecked") @Override public Session connectToServer(Class<?> annotatedEndpointClass, URI path) throws DeploymentException { // TODO: Remove this before release /* * This is a temporary hack to allow the WebSocket EA TCK to work. This * has been confirmed as non-compliant with the EG lead so the TCK will * have to change. For now, we need the TCK to work. */ if (Endpoint.class.isAssignableFrom(annotatedEndpointClass)) { return connectToServer( (Class<? extends Endpoint>) annotatedEndpointClass, Builder.create().build(), path); } // End of TCK hack Object pojo; try { pojo = annotatedEndpointClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", annotatedEndpointClass.getName()), e); } return connectToServer(pojo, path); } @Override public Session connectToServer(Class<? extends Endpoint> clazz, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { Endpoint endpoint; try { endpoint = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", clazz.getName()), e); } return connectToServer(endpoint, clientEndpointConfiguration, path); } @Override public Session connectToServer(Endpoint endpoint, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { boolean secure = false; String scheme = path.getScheme(); if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme))) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.pathWrongScheme", scheme)); } String host = path.getHost(); if (host == null) { throw new DeploymentException( sm.getString("wsWebSocketContainer.pathNoHost")); } int port = path.getPort(); Map<String,List<String>> reqHeaders = createRequestHeaders(host, port, clientEndpointConfiguration.getPreferredSubprotocols()); clientEndpointConfiguration.getConfigurator(). beforeRequest(reqHeaders); ByteBuffer request = createRequest(path, reqHeaders); SocketAddress sa; if (port == -1) { if ("ws".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 80); } else if ("wss".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 443); secure = true; } else { throw new DeploymentException( sm.getString("wsWebSocketContainer.invalidScheme")); } } else { if ("wss".equalsIgnoreCase(scheme)) { secure = true; } sa = new InetSocketAddress(host, port); } AsynchronousSocketChannel socketChannel; try { socketChannel = AsynchronousSocketChannel.open(asynchronousChannelGroup); } catch (IOException ioe) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.asynchronousSocketChannelFail"), ioe); } Future<Void> fConnect = socketChannel.connect(sa); AsyncChannelWrapper channel; if (secure) { SSLEngine sslEngine = createSSLEngine( clientEndpointConfiguration.getUserProperties()); channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine); } else { channel = new AsyncChannelWrapperNonSecure(socketChannel); } ByteBuffer response; String subProtocol; try { fConnect.get(); Future<Void> fHandshake = channel.handshake(); fHandshake.get(); int toWrite = request.limit(); Future<Integer> fWrite = channel.write(request); Integer thisWrite = fWrite.get(); toWrite -= thisWrite.intValue(); while (toWrite > 0) { fWrite = channel.write(request); thisWrite = fWrite.get(); toWrite -= thisWrite.intValue(); } // Same size as the WsFrame input buffer response = ByteBuffer.allocate(maxBinaryMessageBufferSize); HandshakeResponse handshakeResponse = processResponse(response, channel); clientEndpointConfiguration.getConfigurator(). afterResponse(handshakeResponse); // Sub-protocol List<String> values = handshakeResponse.getHeaders().get( Constants.WS_PROTOCOL_HEADER_NAME); if (values == null || values.size() == 0) { subProtocol = null; } else if (values.size() == 1) { subProtocol = values.get(0); } else { throw new DeploymentException( sm.getString("Sec-WebSocket-Protocol")); } } catch (ExecutionException | InterruptedException | SSLException | EOFException e) { throw new DeploymentException( sm.getString("wsWebSocketContainer.httpRequestFailed"), e); } // Switch to WebSocket WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel); WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient, this, null, null, null, null, subProtocol, Collections.EMPTY_MAP, false, clientEndpointConfiguration.getEncoders(), clientEndpointConfiguration.getUserProperties()); endpoint.onOpen(wsSession, clientEndpointConfiguration); registerSession(endpoint.getClass(), wsSession); // Object creation will trigger input processing @SuppressWarnings("unused") WsFrameClient wsFrameClient = new WsFrameClient(response, channel, wsSession); return wsSession; } protected void registerSession(Class<?> endpoint, WsSession wsSession) { if (!wsSession.isOpen()) { // The session was closed during onOpen. No need to register it. return; } synchronized (endPointSessionMapLock) { if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().register(this); } Set<WsSession> wsSessions = endpointSessionMap.get(endpoint); if (wsSessions == null) { wsSessions = new HashSet<>(); endpointSessionMap.put(endpoint, wsSessions); } wsSessions.add(wsSession); } sessions.put(wsSession, wsSession); } protected void unregisterSession(Class<?> endpoint, WsSession wsSession) { synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpoint); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpoint); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); } Set<Session> getOpenSessions(Class<?> endpoint) { HashSet<Session> result = new HashSet<>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; } private Map<String,List<String>> createRequestHeaders(String host, int port, List<String> subProtocols) { Map<String,List<String>> headers = new HashMap<>(); // Host header List<String> hostValues = new ArrayList<>(1); if (port == -1) { hostValues.add(host); } else { hostValues.add(host + ':' + port); } headers.put(Constants.HOST_HEADER_NAME, hostValues); // Upgrade header List<String> upgradeValues = new ArrayList<>(1); upgradeValues.add(Constants.UPGRADE_HEADER_VALUE); headers.put(Constants.UPGRADE_HEADER_NAME, upgradeValues); // Connection header List<String> connectionValues = new ArrayList<>(1); connectionValues.add(Constants.CONNECTION_HEADER_VALUE); headers.put(Constants.CONNECTION_HEADER_NAME, connectionValues); // WebSocket version header List<String> wsVersionValues = new ArrayList<>(1); wsVersionValues.add(Constants.WS_VERSION_HEADER_VALUE); headers.put(Constants.WS_VERSION_HEADER_NAME, wsVersionValues); // WebSocket key List<String> wsKeyValues = new ArrayList<>(1); wsKeyValues.add(generateWsKeyValue()); headers.put(Constants.WS_KEY_HEADER_NAME, wsKeyValues); // WebSocket sub-protocols if (subProtocols != null && subProtocols.size() > 0) { headers.put(Constants.WS_PROTOCOL_HEADER_NAME, subProtocols); } return headers; } private String generateWsKeyValue() { byte[] keyBytes = new byte[16]; random.nextBytes(keyBytes); return Base64.encodeBase64String(keyBytes); } private ByteBuffer createRequest(URI uri, Map<String,List<String>> reqHeaders) { ByteBuffer result = ByteBuffer.allocate(4 * 1024); // Request line result.put("GET ".getBytes(iso88591)); result.put(uri.getRawPath().getBytes(iso88591)); String query = uri.getRawQuery(); if (query != null) { result.put((byte) '?'); result.put(query.getBytes(iso88591)); } result.put(" HTTP/1.1\r\n".getBytes(iso88591)); // Headers Iterator<Entry<String,List<String>>> iter = reqHeaders.entrySet().iterator(); while (iter.hasNext()) { Entry<String,List<String>> entry = iter.next(); addHeader(result, entry.getKey(), entry.getValue()); } // Terminating CRLF result.put(crlf); result.flip(); return result; } private void addHeader(ByteBuffer result, String key, List<String> values) { StringBuilder sb = new StringBuilder(); Iterator<String> iter = values.iterator(); if (!iter.hasNext()) { return; } sb.append(iter.next()); while (iter.hasNext()) { sb.append(','); sb.append(iter.next()); } result.put(key.getBytes(iso88591)); result.put(": ".getBytes(iso88591)); result.put(sb.toString().getBytes(iso88591)); result.put(crlf); } /** * Process response, blocking until HTTP response has been fully received. * @throws ExecutionException * @throws InterruptedException * @throws DeploymentException */ private HandshakeResponse processResponse(ByteBuffer response, AsyncChannelWrapper channel) throws InterruptedException, ExecutionException, DeploymentException, EOFException { Map<String,List<String>> headers = new HashMap<>(); boolean readStatus = false; boolean readHeaders = false; String line = null; while (!readHeaders) { // Blocking read Future<Integer> read = channel.read(response); Integer bytesRead = read.get(); if (bytesRead.intValue() == -1) { throw new EOFException(); } response.flip(); while (response.hasRemaining() && !readHeaders) { if (line == null) { line = readLine(response); } else { line += readLine(response); } if ("\r\n".equals(line)) { readHeaders = true; } else if (line.endsWith("\r\n")) { if (readStatus) { parseHeaders(line, headers); } else { parseStatus(line); readStatus = true; } line = null; } } } return new WsHandshakeResponse(headers); } private void parseStatus(String line) throws DeploymentException { // This client only understands HTTP 1.1 // RFC2616 is case specific if (!line.startsWith("HTTP/1.1 101")) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus", line)); } } private void parseHeaders(String line, Map<String,List<String>> headers) { // Treat headers as single values by default. int index = line.indexOf(':'); if (index == -1) { log.warn(sm.getString("wsWebSocketContainer.invalidHeader", line)); return; } String headerName = line.substring(0, index).trim().toLowerCase(); // TODO handle known multi-value headers String headerValue = line.substring(index + 1).trim(); List<String> values = headers.get(headerName); if (values == null) { values = new ArrayList<>(1); headers.put(headerName, values); } values.add(headerValue); } private String readLine(ByteBuffer response) { // All ISO-8859-1 StringBuilder sb = new StringBuilder(); char c = 0; while (response.hasRemaining()) { c = (char) response.get(); sb.append(c); if (c == 10) { break; } } return sb.toString(); } private SSLEngine createSSLEngine(Map<String,Object> userProperties) throws DeploymentException { try { // Create the SSL Context SSLContext sslContext = SSLContext.getInstance("TLS"); // Trust store String sslTrustStoreValue = (String) userProperties.get(SSL_TRUSTSTORE_PROPERTY); if (sslTrustStoreValue != null) { String sslTrustStorePwdValue = (String) userProperties.get( SSL_TRUSTSTORE_PWD_PROPERTY); if (sslTrustStorePwdValue == null) { sslTrustStorePwdValue = SSL_TRUSTSTORE_PWD_DEFAULT; } File keyStoreFile = new File(sslTrustStoreValue); KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream is = new FileInputStream(keyStoreFile)) { ks.load(is, sslTrustStorePwdValue.toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(), null); } else { sslContext.init(null, null, null); } SSLEngine engine = sslContext.createSSLEngine(); String sslProtocolsValue = (String) userProperties.get(SSL_PROTOCOLS_PROPERTY); if (sslProtocolsValue != null) { engine.setEnabledProtocols(sslProtocolsValue.split(",")); } engine.setUseClientMode(true); return engine; } catch (Exception e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.sslEngineFail"), e); } } @Override public long getDefaultMaxSessionIdleTimeout() { return defaultMaxSessionIdleTimeout; } @Override public void setDefaultMaxSessionIdleTimeout(long timeout) { this.defaultMaxSessionIdleTimeout = timeout; } @Override public int getDefaultMaxBinaryMessageBufferSize() { return maxBinaryMessageBufferSize; } @Override public void setDefaultMaxBinaryMessageBufferSize(int max) { maxBinaryMessageBufferSize = max; } @Override public int getDefaultMaxTextMessageBufferSize() { return maxTextMessageBufferSize; } @Override public void setDefaultMaxTextMessageBufferSize(int max) { maxTextMessageBufferSize = max; } /** * {@inheritDoc} * * Currently, this implementation does not support any extensions. */ @Override public Set<Extension> getInstalledExtensions() { return Collections.EMPTY_SET; } /** * {@inheritDoc} * * The default value for this implementation is -1. */ @Override public long getDefaultAsyncSendTimeout() { return defaultAsyncTimeout; } /** * {@inheritDoc} * * The default value for this implementation is -1. */ @Override public void setAsyncSendTimeout(long timeout) { this.defaultAsyncTimeout = timeout; } // ----------------------------------------------- BackgroundProcess methods @Override public void backgroundProcess() { // This method gets called once a second. backgroundProcessCount ++; if (backgroundProcessCount >= processPeriod) { backgroundProcessCount = 0; for (WsSession wsSession : sessions.keySet()) { wsSession.expire(); } } } @Override public void setProcessPeriod(int period) { this.processPeriod = period; } /** * {@inheritDoc} * * The default value is 10 which means session expirations are processed * every 10 seconds. */ @Override public int getProcessPeriod() { return processPeriod; } /** * Create threads for AsyncIO that have the right context class loader to * prevent memory leaks. */ private static class AsyncIOThreadFactory implements ThreadFactory { private AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("WebSocketClient-AsyncIO-" + count.incrementAndGet()); t.setContextClassLoader(this.getClass().getClassLoader()); t.setDaemon(true); return t; } } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
java/org/apache/tomcat/websocket/server/WsHttpUpgradeHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.server; import java.io.EOFException; import java.io.IOException; import java.util.Map; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.WsIOException; import org.apache.tomcat.websocket.WsSession; /** * Servlet 3.1 HTTP upgrade handler for WebSocket connections. */ public class WsHttpUpgradeHandler implements HttpUpgradeHandler { private static final Log log = LogFactory.getLog(WsHttpUpgradeHandler.class); private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final ClassLoader applicationClassLoader; private Endpoint ep; private EndpointConfig endpointConfig; private WsServerContainer webSocketContainer; private WsHandshakeRequest handshakeRequest; private String subProtocol; private Map<String,String> pathParameters; private boolean secure; private WebConnection connection; private WsSession wsSession; public WsHttpUpgradeHandler() { applicationClassLoader = Thread.currentThread().getContextClassLoader(); } public void preInit(Endpoint ep, EndpointConfig endpointConfig, WsServerContainer wsc, WsHandshakeRequest handshakeRequest, String subProtocol, Map<String,String> pathParameters, boolean secure) { this.ep = ep; this.endpointConfig = endpointConfig; this.webSocketContainer = wsc; this.handshakeRequest = handshakeRequest; this.subProtocol = subProtocol; this.pathParameters = pathParameters; this.secure = secure; } @Override public void init(WebConnection connection) { if (ep == null) { throw new IllegalStateException( sm.getString("wsHttpUpgradeHandler.noPreInit")); } this.connection = connection; ServletInputStream sis; ServletOutputStream sos; try { sis = connection.getInputStream(); sos = connection.getOutputStream(); } catch (IOException e) { throw new IllegalStateException(e); } // Need to call onOpen using the web application's class loader // Create the frame using the application's class loader so it can pick // up application specific config from the ServerContainerImpl Thread t = Thread.currentThread(); ClassLoader cl = t.getContextClassLoader(); t.setContextClassLoader(applicationClassLoader); try { WsRemoteEndpointImplServer wsRemoteEndpointServer = new WsRemoteEndpointImplServer(sos, webSocketContainer); wsSession = new WsSession(ep, wsRemoteEndpointServer, webSocketContainer, handshakeRequest.getRequestURI(), handshakeRequest.getParameterMap(), handshakeRequest.getQueryString(), handshakeRequest.getUserPrincipal(), subProtocol, pathParameters, secure, endpointConfig.getEncoders(), endpointConfig.getUserProperties()); WsFrameServer wsFrame = new WsFrameServer( sis, wsSession); sis.setReadListener(new WsReadListener(this, wsFrame)); sos.setWriteListener( new WsWriteListener(this, wsRemoteEndpointServer)); ep.onOpen(wsSession, endpointConfig); webSocketContainer.registerSession(ep.getClass(), wsSession); } catch (DeploymentException e) { throw new IllegalArgumentException(e); } finally { t.setContextClassLoader(cl); } } @Override public void destroy() { try { connection.close(); } catch (Exception e) { log.error(sm.getString("wsHttpUpgradeHandler.destroyFailed"), e); } } private void onError(Throwable throwable) { // Need to call onError using the web application's class loader Thread t = Thread.currentThread(); ClassLoader cl = t.getContextClassLoader(); t.setContextClassLoader(applicationClassLoader); try { ep.onError(wsSession, throwable); } finally { t.setContextClassLoader(cl); } } private void close(CloseReason cr) { /* * Any call to this method is a result of a problem reading from the * client. At this point that state of the connection is unknown. * Attempt to send a close frame to the client and then close the socket * immediately. There is no point in waiting for a close frame from the * client because there is no guarantee that we can recover from * whatever messed up state the client put the connection into. */ wsSession.onClose(cr); } private static class WsReadListener implements ReadListener { private final WsHttpUpgradeHandler wsProtocolHandler; private final WsFrameServer wsFrame; private WsReadListener(WsHttpUpgradeHandler wsProtocolHandler, WsFrameServer wsFrame) { this.wsProtocolHandler = wsProtocolHandler; this.wsFrame = wsFrame; } @Override public void onDataAvailable() { try { wsFrame.onDataAvailable(); } catch (WsIOException ws) { wsProtocolHandler.close(ws.getCloseReason()); } catch (EOFException eof) { CloseReason cr = new CloseReason( CloseCodes.CLOSED_ABNORMALLY, eof.getMessage()); wsProtocolHandler.close(cr); } catch (IOException ioe) { onError(ioe); } } @Override public void onAllDataRead() { // Will never happen with WebSocket throw new IllegalStateException(); } @Override public void onError(Throwable throwable) { wsProtocolHandler.onError(throwable); } } private static class WsWriteListener implements WriteListener { private final WsHttpUpgradeHandler wsProtocolHandler; private final WsRemoteEndpointImplServer wsRemoteEndpointServer; private WsWriteListener(WsHttpUpgradeHandler wsProtocolHandler, WsRemoteEndpointImplServer wsRemoteEndpointServer) { this.wsProtocolHandler = wsProtocolHandler; this.wsRemoteEndpointServer = wsRemoteEndpointServer; } @Override public void onWritePossible() { wsRemoteEndpointServer.onWritePossible(); } @Override public void onError(Throwable throwable) { wsProtocolHandler.onError(throwable); } } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
java/org/apache/tomcat/websocket/server/WsRemoteEndpointImplServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.server; import java.io.IOException; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import javax.servlet.ServletOutputStream; import javax.websocket.SendHandler; import javax.websocket.SendResult; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.WsRemoteEndpointImplBase; /** * This is the server side {@link javax.websocket.RemoteEndpoint} implementation * - i.e. what the server uses to send data to the client. Communication is over * a {@link ServletOutputStream}. */ public class WsRemoteEndpointImplServer extends WsRemoteEndpointImplBase { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final Log log = LogFactory.getLog(WsHttpUpgradeHandler.class); private final ServletOutputStream sos; private final WsWriteTimeout wsWriteTimeout; private volatile SendHandler handler = null; private volatile ByteBuffer[] buffers = null; private volatile long timeoutExpiry = -1; private volatile boolean close; public WsRemoteEndpointImplServer(ServletOutputStream sos, WsServerContainer serverContainer) { this.sos = sos; this.wsWriteTimeout = serverContainer.getTimeout(); } @Override protected final boolean isMasked() { return false; } @Override protected void doWrite(SendHandler handler, ByteBuffer... buffers) { this.handler = handler; this.buffers = buffers; onWritePossible(); } public void onWritePossible() { boolean complete = true; try { // If this is false there will be a call back when it is true while (sos.isReady()) { complete = true; for (ByteBuffer buffer : buffers) { if (buffer.hasRemaining()) { complete = false; sos.write(buffer.array(), buffer.arrayOffset(), buffer.limit()); buffer.position(buffer.limit()); break; } } if (complete) { wsWriteTimeout.unregister(this); if (close) { close(); } // Setting the result marks this (partial) message as // complete which means the next one may be sent which // could update the value of the handler. Therefore, keep a // local copy before signalling the end of the (partial) // message. SendHandler sh = handler; handler = null; sh.onResult(new SendResult()); break; } } } catch (IOException ioe) { wsWriteTimeout.unregister(this); close(); SendHandler sh = handler; handler = null; sh.onResult(new SendResult(ioe)); } if (!complete) { // Async write is in progress long timeout = getSendTimeout(); if (timeout > 0) { // Register with timeout thread timeoutExpiry = timeout + System.currentTimeMillis(); wsWriteTimeout.register(this); } } } @Override protected void close() { try { sos.close(); } catch (IOException e) { if (log.isInfoEnabled()) { log.info(sm.getString("wsRemoteEndpointServer.closeFailed"), e); } } wsWriteTimeout.unregister(this); } protected long getTimeoutExpiry() { return timeoutExpiry; } protected void onTimeout() { close(); handler.onResult(new SendResult(new SocketTimeoutException())); handler = null; } }
55,127
Bug 55127 Encoders init and destroy methods are never called
null
resolved fixed
93bcdde
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-22T14:09:34Z
2013-06-22T11:20:00Z
test/org/apache/tomcat/websocket/pojo/TestEncodingDecoding.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.pojo; import java.net.URI; import java.nio.ByteBuffer; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.EndpointConfig; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.websocket.server.ServerEndpoint; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.deploy.ApplicationListener; import org.apache.catalina.servlets.DefaultServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.websocket.pojo.Util.ServerConfigListener; import org.apache.tomcat.websocket.pojo.Util.SingletonConfigurator; public class TestEncodingDecoding extends TomcatBaseTest { private static final String MESSAGE_ONE = "message-one"; @Test public void test() throws Exception { // Set up utility classes Server server = new Server(); SingletonConfigurator.setInstance(server); ServerConfigListener.setPojoClazz(Server.class); Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( ServerConfigListener.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Client client = new Client(); URI uri = new URI("ws://localhost:" + getPort() + "/"); Session session = wsContainer.connectToServer(client, uri); MsgString msg1 = new MsgString(); msg1.setData(MESSAGE_ONE); session.getBasicRemote().sendObject(msg1); // Should not take very long int i = 0; while (i < 20) { if (server.received.size() > 0 && client.received.size() > 0) { break; } Thread.sleep(100); } // Check messages were received Assert.assertEquals(1, server.received.size()); Assert.assertEquals(1, client.received.size()); // Check correct messages were received Assert.assertEquals(MESSAGE_ONE, ((MsgString) server.received.peek()).getData()); Assert.assertEquals(MESSAGE_ONE, ((MsgString) client.received.peek()).getData()); } @ClientEndpoint(decoders={MsgStringDecoder.class, MsgByteDecoder.class}, encoders={MsgStringEncoder.class, MsgByteEncoder.class}) public static class Client { private Queue<Object> received = new ConcurrentLinkedQueue<>(); @OnMessage public void rx(MsgString in) { received.add(in); } @OnMessage public void rx(MsgByte in) { received.add(in); } } @ServerEndpoint(value="/", decoders={MsgStringDecoder.class, MsgByteDecoder.class}, encoders={MsgStringEncoder.class, MsgByteEncoder.class}, configurator=SingletonConfigurator.class) public static class Server { private Queue<Object> received = new ConcurrentLinkedQueue<>(); @OnMessage public MsgString rx(MsgString in) { received.add(in); // Echo the message back return in; } @OnMessage public MsgByte rx(MsgByte in) { received.add(in); // Echo the message back return in; } } public static class MsgString { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } } public static class MsgStringEncoder implements Encoder.Text<MsgString> { @Override public void init(EndpointConfig endpointConfig) { // NO-OP } @Override public void destroy() { // NO-OP } @Override public String encode(MsgString msg) throws EncodeException { return "MsgString:" + msg.getData(); } } public static class MsgStringDecoder implements Decoder.Text<MsgString> { @Override public void init(EndpointConfig endpointConfig) { // NO-OP } @Override public void destroy() { // NO-OP } @Override public MsgString decode(String s) throws DecodeException { MsgString result = new MsgString(); result.setData(s.substring(10)); return result; } @Override public boolean willDecode(String s) { return s.startsWith("MsgString:"); } } public static class MsgByte { private byte[] data; public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } } public static class MsgByteEncoder implements Encoder.Binary<MsgByte> { @Override public void init(EndpointConfig endpointConfig) { // NO-OP } @Override public void destroy() { // NO-OP } @Override public ByteBuffer encode(MsgByte msg) throws EncodeException { byte[] data = msg.getData(); ByteBuffer reply = ByteBuffer.allocate(2 + data.length); reply.put((byte) 0x12); reply.put((byte) 0x34); reply.put(data); return reply; } } public static class MsgByteDecoder implements Decoder.Binary<MsgByte> { @Override public void init(EndpointConfig endpointConfig) { // NO-OP } @Override public void destroy() { // NO-OP } @Override public MsgByte decode(ByteBuffer bb) throws DecodeException { MsgByte result = new MsgByte(); bb.position(bb.position() + 2); byte[] data = new byte[bb.limit() - bb.position()]; bb.get(data); result.setData(data); return result; } @Override public boolean willDecode(ByteBuffer bb) { bb.mark(); if (bb.get() == 0x12 && bb.get() == 0x34) { return true; } bb.reset(); return false; } } }
55,125
Bug 55125 Tomcat does not shut down if LifecycleListener throws an exception
null
resolved fixed
3a36a8f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-23T19:47:39Z
2013-06-21T15:53:20Z
java/org/apache/catalina/core/StandardService.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.util.ArrayList; import javax.management.ObjectName; import org.apache.catalina.Container; import org.apache.catalina.Engine; import org.apache.catalina.Executor; import org.apache.catalina.JmxEnabled; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Server; import org.apache.catalina.Service; import org.apache.catalina.connector.Connector; import org.apache.catalina.mapper.Mapper; import org.apache.catalina.mapper.MapperListener; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * Standard implementation of the <code>Service</code> interface. The * associated Container is generally an instance of Engine, but this is * not required. * * @author Craig R. McClanahan */ public class StandardService extends LifecycleMBeanBase implements Service { private static final Log log = LogFactory.getLog(StandardService.class); // ----------------------------------------------------- Instance Variables /** * The name of this service. */ private String name = null; /** * The string manager for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); /** * The <code>Server</code> that owns this Service, if any. */ private Server server = null; /** * The property change support for this component. */ protected final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * The set of Connectors associated with this Service. */ protected Connector connectors[] = new Connector[0]; private final Object connectorsLock = new Object(); /** * */ protected final ArrayList<Executor> executors = new ArrayList<>(); /** * The Container associated with this Service. */ protected Container container = null; private ClassLoader parentClassLoader = null; /** * Mapper. */ protected final Mapper mapper = new Mapper(); /** * Mapper listener. */ protected final MapperListener mapperListener = new MapperListener(mapper, this); // ------------------------------------------------------------- Properties @Override public Mapper getMapper() { return mapper; } /** * Return the <code>Container</code> that handles requests for all * <code>Connectors</code> associated with this Service. */ @Override public Container getContainer() { return (this.container); } /** * Set the <code>Container</code> that handles requests for all * <code>Connectors</code> associated with this Service. * * @param container The new Container */ @Override public void setContainer(Container container) { Container oldContainer = this.container; if ((oldContainer != null) && (oldContainer instanceof Engine)) ((Engine) oldContainer).setService(null); this.container = container; if ((this.container != null) && (this.container instanceof Engine)) ((Engine) this.container).setService(this); if (getState().isAvailable() && (this.container != null)) { try { this.container.start(); } catch (LifecycleException e) { // Ignore } } if (getState().isAvailable() && (oldContainer != null)) { try { oldContainer.stop(); } catch (LifecycleException e) { // Ignore } } // Report this property change to interested listeners support.firePropertyChange("container", oldContainer, this.container); } /** * Return the name of this Service. */ @Override public String getName() { return (this.name); } /** * Set the name of this Service. * * @param name The new service name */ @Override public void setName(String name) { this.name = name; } /** * Return the <code>Server</code> with which we are associated (if any). */ @Override public Server getServer() { return (this.server); } /** * Set the <code>Server</code> with which we are associated (if any). * * @param server The server that owns this Service */ @Override public void setServer(Server server) { this.server = server; } // --------------------------------------------------------- Public Methods /** * Add a new Connector to the set of defined Connectors, and associate it * with this Service's Container. * * @param connector The Connector to be added */ @Override public void addConnector(Connector connector) { synchronized (connectorsLock) { connector.setService(this); Connector results[] = new Connector[connectors.length + 1]; System.arraycopy(connectors, 0, results, 0, connectors.length); results[connectors.length] = connector; connectors = results; if (getState().isAvailable()) { try { connector.start(); } catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); } } // Report this property change to interested listeners support.firePropertyChange("connector", null, connector); } } public ObjectName[] getConnectorNames() { ObjectName results[] = new ObjectName[connectors.length]; for (int i=0; i<results.length; i++) { results[i] = connectors[i].getObjectName(); } return results; } /** * Add a property change listener to this component. * * @param listener The listener to add */ public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } /** * Find and return the set of Connectors associated with this Service. */ @Override public Connector[] findConnectors() { return connectors; } /** * Remove the specified Connector from the set associated from this * Service. The removed Connector will also be disassociated from our * Container. * * @param connector The Connector to be removed */ @Override public void removeConnector(Connector connector) { synchronized (connectorsLock) { int j = -1; for (int i = 0; i < connectors.length; i++) { if (connector == connectors[i]) { j = i; break; } } if (j < 0) return; if (connectors[j].getState().isAvailable()) { try { connectors[j].stop(); } catch (LifecycleException e) { log.error(sm.getString( "standardService.connector.stopFailed", connectors[j]), e); } } connector.setService(null); int k = 0; Connector results[] = new Connector[connectors.length - 1]; for (int i = 0; i < connectors.length; i++) { if (i != j) results[k++] = connectors[i]; } connectors = results; // Report this property change to interested listeners support.firePropertyChange("connector", connector, null); } } /** * Remove a property change listener from this component. * * @param listener The listener to remove */ public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } /** * Return a String representation of this component. */ @Override public String toString() { StringBuilder sb = new StringBuilder("StandardService["); sb.append(getName()); sb.append("]"); return (sb.toString()); } /** * Adds a named executor to the service * @param ex Executor */ @Override public void addExecutor(Executor ex) { synchronized (executors) { if (!executors.contains(ex)) { executors.add(ex); if (getState().isAvailable()) try { ex.start(); } catch (LifecycleException x) { log.error("Executor.start", x); } } } } /** * Retrieves all executors * @return Executor[] */ @Override public Executor[] findExecutors() { synchronized (executors) { Executor[] arr = new Executor[executors.size()]; executors.toArray(arr); return arr; } } /** * Retrieves executor by name, null if not found * @param executorName String * @return Executor */ @Override public Executor getExecutor(String executorName) { synchronized (executors) { for (Executor executor: executors) { if (executorName.equals(executor.getName())) return executor; } } return null; } /** * Removes an executor from the service * @param ex Executor */ @Override public void removeExecutor(Executor ex) { synchronized (executors) { if ( executors.remove(ex) && getState().isAvailable() ) { try { ex.stop(); } catch (LifecycleException e) { log.error("Executor.stop", e); } } } } /** * Start nested components ({@link Executor}s, {@link Connector}s and * {@link Container}s) and implement the requirements of * {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected void startInternal() throws LifecycleException { if(log.isInfoEnabled()) log.info(sm.getString("standardService.start.name", this.name)); setState(LifecycleState.STARTING); // Start our defined Container first if (container != null) { synchronized (container) { container.start(); } } synchronized (executors) { for (Executor executor: executors) { executor.start(); } } mapperListener.start(); // Start our defined Connectors second synchronized (connectorsLock) { for (Connector connector: connectors) { try { // If it has already failed, don't try and start it if (connector.getState() != LifecycleState.FAILED) { connector.start(); } } catch (Exception e) { log.error(sm.getString( "standardService.connector.startFailed", connector), e); } } } } /** * Stop nested components ({@link Executor}s, {@link Connector}s and * {@link Container}s) and implement the requirements of * {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that needs to be reported */ @Override protected void stopInternal() throws LifecycleException { // Pause connectors first synchronized (connectorsLock) { for (Connector connector: connectors) { try { connector.pause(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.pauseFailed", connector), e); } } } if(log.isInfoEnabled()) log.info(sm.getString("standardService.stop.name", this.name)); setState(LifecycleState.STOPPING); // Stop our defined Container second if (container != null) { synchronized (container) { container.stop(); } } // Now stop the connectors synchronized (connectorsLock) { for (Connector connector: connectors) { if (!LifecycleState.STARTED.equals( connector.getState())) { // Connectors only need stopping if they are currently // started. They may have failed to start or may have been // stopped (e.g. via a JMX call) continue; } try { connector.stop(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.stopFailed", connector), e); } } } mapperListener.stop(); synchronized (executors) { for (Executor executor: executors) { executor.stop(); } } } /** * Invoke a pre-startup initialization. This is used to allow connectors * to bind to restricted ports under Unix operating environments. */ @Override protected void initInternal() throws LifecycleException { super.initInternal(); if (container != null) { container.init(); } // Initialize any Executors for (Executor executor : findExecutors()) { if (executor instanceof JmxEnabled) { ((JmxEnabled) executor).setDomain(getDomain()); } executor.init(); } // Initialize mapper listener mapperListener.init(); // Initialize our defined Connectors synchronized (connectorsLock) { for (Connector connector : connectors) { try { connector.init(); } catch (Exception e) { String message = sm.getString( "standardService.connector.initFailed", connector); log.error(message, e); if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) throw new LifecycleException(message); } } } } @Override protected void destroyInternal() throws LifecycleException { mapperListener.destroy(); // Destroy our defined Connectors synchronized (connectorsLock) { for (Connector connector : connectors) { try { connector.destroy(); } catch (Exception e) { log.error(sm.getString( "standardService.connector.destroyfailed", connector), e); } } } // Destroy any Executors for (Executor executor : findExecutors()) { executor.destroy(); } if (container != null) { container.destroy(); } super.destroyInternal(); } /** * Return the parent class loader for this component. */ @Override public ClassLoader getParentClassLoader() { if (parentClassLoader != null) return (parentClassLoader); if (server != null) { return (server.getParentClassLoader()); } return (ClassLoader.getSystemClassLoader()); } /** * Set the parent class loader for this server. * * @param parent The new parent class loader */ @Override public void setParentClassLoader(ClassLoader parent) { ClassLoader oldParentClassLoader = this.parentClassLoader; this.parentClassLoader = parent; support.firePropertyChange("parentClassLoader", oldParentClassLoader, this.parentClassLoader); } @Override protected String getDomainInternal() { String domain = null; Container engine = getContainer(); // Use the engine name first if (engine != null) { domain = engine.getName(); } // No engine or no engine name, use the service name if (domain == null) { domain = getName(); } // No service name, return null which will trigger the use of the // default return domain; } @Override public final String getObjectNameKeyProperties() { return "type=Service"; } }
55,125
Bug 55125 Tomcat does not shut down if LifecycleListener throws an exception
null
resolved fixed
3a36a8f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-23T19:47:39Z
2013-06-21T15:53:20Z
java/org/apache/catalina/startup/Catalina.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.startup; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.net.ConnectException; import java.net.Socket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.logging.LogManager; import org.apache.catalina.Container; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Server; import org.apache.catalina.core.StandardServer; import org.apache.catalina.security.SecurityConfig; import org.apache.juli.ClassLoaderLogManager; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.digester.Digester; import org.apache.tomcat.util.digester.Rule; import org.apache.tomcat.util.digester.RuleSet; import org.apache.tomcat.util.log.SystemLogHandler; import org.apache.tomcat.util.res.StringManager; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; /** * Startup/Shutdown shell program for Catalina. The following command line * options are recognized: * <ul> * <li><b>-config {pathname}</b> - Set the pathname of the configuration file * to be processed. If a relative path is specified, it will be * interpreted as relative to the directory pathname specified by the * "catalina.base" system property. [conf/server.xml] * <li><b>-help</b> - Display usage information. * <li><b>-nonaming</b> - Disable naming support. * <li><b>configtest</b> - Try to test the config * <li><b>start</b> - Start an instance of Catalina. * <li><b>stop</b> - Stop the currently running instance of Catalina. * </u> * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class Catalina { /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------- Instance Variables /** * Use await. */ protected boolean await = false; /** * Pathname to the server configuration file. */ protected String configFile = "conf/server.xml"; // XXX Should be moved to embedded /** * The shared extensions class loader for this server. */ protected ClassLoader parentClassLoader = Catalina.class.getClassLoader(); /** * The server component we are starting or stopping. */ protected Server server = null; /** * Use shutdown hook flag. */ protected boolean useShutdownHook = true; /** * Shutdown hook. */ protected Thread shutdownHook = null; /** * Is naming enabled ? */ protected boolean useNaming = true; // ----------------------------------------------------------- Constructors public Catalina() { setSecurityProtection(); } // ------------------------------------------------------------- Properties public void setConfigFile(String file) { configFile = file; } public String getConfigFile() { return configFile; } public void setUseShutdownHook(boolean useShutdownHook) { this.useShutdownHook = useShutdownHook; } public boolean getUseShutdownHook() { return useShutdownHook; } /** * Set the shared extensions class loader. * * @param parentClassLoader The shared extensions class loader. */ public void setParentClassLoader(ClassLoader parentClassLoader) { this.parentClassLoader = parentClassLoader; } public ClassLoader getParentClassLoader() { if (parentClassLoader != null) { return (parentClassLoader); } return ClassLoader.getSystemClassLoader(); } public void setServer(Server server) { this.server = server; } public Server getServer() { return server; } /** * Return true if naming is enabled. */ public boolean isUseNaming() { return (this.useNaming); } /** * Enables or disables naming support. * * @param useNaming The new use naming value */ public void setUseNaming(boolean useNaming) { this.useNaming = useNaming; } public void setAwait(boolean b) { await = b; } public boolean isAwait() { return await; } // ------------------------------------------------------ Protected Methods /** * Process the specified command line arguments, and return * <code>true</code> if we should continue processing; otherwise * return <code>false</code>. * * @param args Command line arguments to process */ protected boolean arguments(String args[]) { boolean isConfig = false; if (args.length < 1) { usage(); return false; } for (int i = 0; i < args.length; i++) { if (isConfig) { configFile = args[i]; isConfig = false; } else if (args[i].equals("-config")) { isConfig = true; } else if (args[i].equals("-nonaming")) { setUseNaming(false); } else if (args[i].equals("-help")) { usage(); return false; } else if (args[i].equals("start")) { // NOOP } else if (args[i].equals("configtest")) { // NOOP } else if (args[i].equals("stop")) { // NOOP } else { usage(); return false; } } return true; } /** * Return a File object representing our configuration file. */ protected File configFile() { File file = new File(configFile); if (!file.isAbsolute()) { file = new File(Bootstrap.getCatalinaBase(), configFile); } return (file); } /** * Create and configure the Digester we will be using for startup. */ protected Digester createStartDigester() { long t1=System.currentTimeMillis(); // Initialize the digester Digester digester = new Digester(); digester.setValidating(false); digester.setRulesValidation(true); HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>(); ArrayList<String> attrs = new ArrayList<>(); attrs.add("className"); fakeAttributes.put(Object.class, attrs); digester.setFakeAttributes(fakeAttributes); digester.setClassLoader(StandardServer.class.getClassLoader()); // Configure the actions we will be using digester.addObjectCreate("Server", "org.apache.catalina.core.StandardServer", "className"); digester.addSetProperties("Server"); digester.addSetNext("Server", "setServer", "org.apache.catalina.Server"); digester.addObjectCreate("Server/GlobalNamingResources", "org.apache.catalina.deploy.NamingResources"); digester.addSetProperties("Server/GlobalNamingResources"); digester.addSetNext("Server/GlobalNamingResources", "setGlobalNamingResources", "org.apache.catalina.deploy.NamingResources"); digester.addObjectCreate("Server/Listener", null, // MUST be specified in the element "className"); digester.addSetProperties("Server/Listener"); digester.addSetNext("Server/Listener", "addLifecycleListener", "org.apache.catalina.LifecycleListener"); digester.addObjectCreate("Server/Service", "org.apache.catalina.core.StandardService", "className"); digester.addSetProperties("Server/Service"); digester.addSetNext("Server/Service", "addService", "org.apache.catalina.Service"); digester.addObjectCreate("Server/Service/Listener", null, // MUST be specified in the element "className"); digester.addSetProperties("Server/Service/Listener"); digester.addSetNext("Server/Service/Listener", "addLifecycleListener", "org.apache.catalina.LifecycleListener"); //Executor digester.addObjectCreate("Server/Service/Executor", "org.apache.catalina.core.StandardThreadExecutor", "className"); digester.addSetProperties("Server/Service/Executor"); digester.addSetNext("Server/Service/Executor", "addExecutor", "org.apache.catalina.Executor"); digester.addRule("Server/Service/Connector", new ConnectorCreateRule()); digester.addRule("Server/Service/Connector", new SetAllPropertiesRule(new String[]{"executor"})); digester.addSetNext("Server/Service/Connector", "addConnector", "org.apache.catalina.connector.Connector"); digester.addObjectCreate("Server/Service/Connector/Listener", null, // MUST be specified in the element "className"); digester.addSetProperties("Server/Service/Connector/Listener"); digester.addSetNext("Server/Service/Connector/Listener", "addLifecycleListener", "org.apache.catalina.LifecycleListener"); // Add RuleSets for nested elements digester.addRuleSet(new NamingRuleSet("Server/GlobalNamingResources/")); digester.addRuleSet(new EngineRuleSet("Server/Service/")); digester.addRuleSet(new HostRuleSet("Server/Service/Engine/")); digester.addRuleSet(new ContextRuleSet("Server/Service/Engine/Host/")); addClusterRuleSet(digester, "Server/Service/Engine/Host/Cluster/"); digester.addRuleSet(new NamingRuleSet("Server/Service/Engine/Host/Context/")); // When the 'engine' is found, set the parentClassLoader. digester.addRule("Server/Service/Engine", new SetParentClassLoaderRule(parentClassLoader)); addClusterRuleSet(digester, "Server/Service/Engine/Cluster/"); long t2=System.currentTimeMillis(); if (log.isDebugEnabled()) { log.debug("Digester for server.xml created " + ( t2-t1 )); } return (digester); } /** * Cluster support is optional. The JARs may have been removed. */ private void addClusterRuleSet(Digester digester, String prefix) { Class<?> clazz = null; Constructor<?> constructor = null; try { clazz = Class.forName("org.apache.catalina.ha.ClusterRuleSet"); constructor = clazz.getConstructor(String.class); RuleSet ruleSet = (RuleSet) constructor.newInstance(prefix); digester.addRuleSet(ruleSet); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage()), e); } else if (log.isInfoEnabled()) { log.info(sm.getString("catalina.noCluster", e.getClass().getName() + ": " + e.getMessage())); } } } /** * Create and configure the Digester we will be using for shutdown. */ protected Digester createStopDigester() { // Initialize the digester Digester digester = new Digester(); // Configure the rules we need for shutting down digester.addObjectCreate("Server", "org.apache.catalina.core.StandardServer", "className"); digester.addSetProperties("Server"); digester.addSetNext("Server", "setServer", "org.apache.catalina.Server"); return (digester); } public void stopServer() { stopServer(null); } public void stopServer(String[] arguments) { if (arguments != null) { arguments(arguments); } Server s = getServer(); if( s == null ) { // Create and execute our Digester Digester digester = createStopDigester(); digester.setClassLoader(Thread.currentThread().getContextClassLoader()); File file = configFile(); FileInputStream fis = null; try { InputSource is = new InputSource(file.toURI().toURL().toString()); fis = new FileInputStream(file); is.setByteStream(fis); digester.push(this); digester.parse(is); } catch (Exception e) { log.error("Catalina.stop: ", e); System.exit(1); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { // Ignore } } } } else { // Server object already present. Must be running as a service try { s.stop(); } catch (LifecycleException e) { log.error("Catalina.stop: ", e); } return; } // Stop the existing server s = getServer(); if (s.getPort()>0) { Socket socket = null; OutputStream stream = null; try { socket = new Socket(s.getAddress(), s.getPort()); stream = socket.getOutputStream(); String shutdown = s.getShutdown(); for (int i = 0; i < shutdown.length(); i++) { stream.write(shutdown.charAt(i)); } stream.flush(); } catch (ConnectException ce) { log.error(sm.getString("catalina.stopServer.connectException", s.getAddress(), String.valueOf(s.getPort()))); log.error("Catalina.stop: ", ce); System.exit(1); } catch (IOException e) { log.error("Catalina.stop: ", e); System.exit(1); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } if (socket != null) { try { socket.close(); } catch (IOException e) { // Ignore } } } } else { log.error(sm.getString("catalina.stopServer")); System.exit(1); } } /** * Start a new server instance. */ public void load() { long t1 = System.nanoTime(); initDirs(); // Before digester - it may be needed initNaming(); // Create and execute our Digester Digester digester = createStartDigester(); InputSource inputSource = null; InputStream inputStream = null; File file = null; try { file = configFile(); inputStream = new FileInputStream(file); inputSource = new InputSource(file.toURI().toURL().toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", file), e); } } if (inputStream == null) { try { inputStream = getClass().getClassLoader() .getResourceAsStream(getConfigFile()); inputSource = new InputSource (getClass().getClassLoader() .getResource(getConfigFile()).toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", getConfigFile()), e); } } } // This should be included in catalina.jar // Alternative: don't bother with xml, just create it manually. if( inputStream==null ) { try { inputStream = getClass().getClassLoader() .getResourceAsStream("server-embed.xml"); inputSource = new InputSource (getClass().getClassLoader() .getResource("server-embed.xml").toString()); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString("catalina.configFail", "server-embed.xml"), e); } } } if (inputStream == null || inputSource == null) { if (file == null) { log.warn(sm.getString("catalina.configFail", getConfigFile() + "] or [server-embed.xml]")); } else { log.warn(sm.getString("catalina.configFail", file.getAbsolutePath())); if (file.exists() && !file.canRead()) { log.warn("Permissions incorrect, read permission is not allowed on the file."); } } return; } try { inputSource.setByteStream(inputStream); digester.push(this); digester.parse(inputSource); } catch (SAXParseException spe) { log.warn("Catalina.start using " + getConfigFile() + ": " + spe.getMessage()); return; } catch (Exception e) { log.warn("Catalina.start using " + getConfigFile() + ": " , e); return; } finally { try { inputStream.close(); } catch (IOException e) { // Ignore } } getServer().setCatalina(this); getServer().setCatalinaHome(Bootstrap.getCatalinaHomeFile()); getServer().setCatalinaBase(Bootstrap.getCatalinaBaseFile()); // Stream redirection initStreams(); // Start the new server try { getServer().init(); } catch (LifecycleException e) { if (Boolean.getBoolean("org.apache.catalina.startup.EXIT_ON_INIT_FAILURE")) { throw new java.lang.Error(e); } else { log.error("Catalina.start", e); } } long t2 = System.nanoTime(); if(log.isInfoEnabled()) { log.info("Initialization processed in " + ((t2 - t1) / 1000000) + " ms"); } } /* * Load using arguments */ public void load(String args[]) { try { if (arguments(args)) { load(); } } catch (Exception e) { e.printStackTrace(System.out); } } /** * Start a new server instance. */ public void start() { if (getServer() == null) { load(); } if (getServer() == null) { log.fatal("Cannot start server. Server instance is not configured."); return; } long t1 = System.nanoTime(); // Start the new server try { getServer().start(); } catch (LifecycleException e) { log.error("Catalina.start: ", e); } long t2 = System.nanoTime(); if(log.isInfoEnabled()) { log.info("Server startup in " + ((t2 - t1) / 1000000) + " ms"); } // Register shutdown hook if (useShutdownHook) { if (shutdownHook == null) { shutdownHook = new CatalinaShutdownHook(); } Runtime.getRuntime().addShutdownHook(shutdownHook); // If JULI is being used, disable JULI's shutdown hook since // shutdown hooks run in parallel and log messages may be lost // if JULI's hook completes before the CatalinaShutdownHook() LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).setUseShutdownHook( false); } } if (await) { await(); stop(); } } /** * Stop an existing server instance. */ public void stop() { try { // Remove the ShutdownHook first so that server.stop() // doesn't get invoked twice if (useShutdownHook) { Runtime.getRuntime().removeShutdownHook(shutdownHook); // If JULI is being used, re-enable JULI's shutdown to ensure // log messages are not lost LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).setUseShutdownHook( true); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This will fail on JDK 1.2. Ignoring, as Tomcat can run // fine without the shutdown hook. } // Shut down the server try { Server s = getServer(); LifecycleState state = s.getState(); if (LifecycleState.STOPPING_PREP.compareTo(state) <= 0 && LifecycleState.DESTROYED.compareTo(state) >= 0) { // Nothing to do. stop() was already called } else { s.stop(); s.destroy(); } } catch (LifecycleException e) { log.error("Catalina.stop", e); } } /** * Await and shutdown. */ public void await() { getServer().await(); } /** * Print usage information for this application. */ protected void usage() { System.out.println ("usage: java org.apache.catalina.startup.Catalina" + " [ -config {pathname} ]" + " [ -nonaming ] " + " { -help | start | stop }"); } protected void initDirs() { String temp = System.getProperty("java.io.tmpdir"); if (temp == null || (!(new File(temp)).exists()) || (!(new File(temp)).isDirectory())) { log.error(sm.getString("embedded.notmp", temp)); } } protected void initStreams() { // Replace System.out and System.err with a custom PrintStream System.setOut(new SystemLogHandler(System.out)); System.setErr(new SystemLogHandler(System.err)); } protected void initNaming() { // Setting additional variables if (!useNaming) { log.info( "Catalina naming disabled"); System.setProperty("catalina.useNaming", "false"); } else { System.setProperty("catalina.useNaming", "true"); String value = "org.apache.naming"; String oldValue = System.getProperty(javax.naming.Context.URL_PKG_PREFIXES); if (oldValue != null) { value = value + ":" + oldValue; } System.setProperty(javax.naming.Context.URL_PKG_PREFIXES, value); if( log.isDebugEnabled() ) { log.debug("Setting naming prefix=" + value); } value = System.getProperty (javax.naming.Context.INITIAL_CONTEXT_FACTORY); if (value == null) { System.setProperty (javax.naming.Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory"); } else { log.debug( "INITIAL_CONTEXT_FACTORY alread set " + value ); } } } /** * Set the security package access/protection. */ protected void setSecurityProtection(){ SecurityConfig securityConfig = SecurityConfig.newInstance(); securityConfig.setPackageDefinition(); securityConfig.setPackageAccess(); } // --------------------------------------- CatalinaShutdownHook Inner Class // XXX Should be moved to embedded ! /** * Shutdown hook which will perform a clean shutdown of Catalina if needed. */ protected class CatalinaShutdownHook extends Thread { @Override public void run() { try { if (getServer() != null) { Catalina.this.stop(); } } catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error(sm.getString("catalina.shutdownHookFail"), ex); } finally { // If JULI is used, shut JULI down *after* the server shuts down // so log messages aren't lost LogManager logManager = LogManager.getLogManager(); if (logManager instanceof ClassLoaderLogManager) { ((ClassLoaderLogManager) logManager).shutdown(); } } } } private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog( Catalina.class ); } // ------------------------------------------------------------ Private Classes /** * Rule that sets the parent class loader for the top object on the stack, * which must be a <code>Container</code>. */ final class SetParentClassLoaderRule extends Rule { public SetParentClassLoaderRule(ClassLoader parentClassLoader) { this.parentClassLoader = parentClassLoader; } ClassLoader parentClassLoader = null; @Override public void begin(String namespace, String name, Attributes attributes) throws Exception { if (digester.getLogger().isDebugEnabled()) { digester.getLogger().debug("Setting parent class loader"); } Container top = (Container) digester.peek(); top.setParentClassLoader(parentClassLoader); } }
55,102
Bug 55102 Add ability to report time taken to prepare response
null
closed fixed
7aea9cb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-23T20:22:25Z
2013-06-15T21:00:00Z
java/org/apache/catalina/valves/AccessLogValve.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.valves; import java.io.BufferedWriter; import java.io.CharArrayWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.net.InetAddress; import java.nio.charset.Charset; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.catalina.AccessLog; import org.apache.catalina.Globals; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Session; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.coyote.RequestInfo; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.collections.SynchronizedStack; /** * <p>Implementation of the <b>Valve</b> interface that generates a web server * access log with the detailed line contents matching a configurable pattern. * The syntax of the available patterns is similar to that supported by the * <a href="http://httpd.apache.org/">Apache HTTP Server</a> * <code>mod_log_config</code> module. As an additional feature, * automatic rollover of log files when the date changes is also supported.</p> * * <p>Patterns for the logged message may include constant text or any of the * following replacement strings, for which the corresponding information * from the specified Response is substituted:</p> * <ul> * <li><b>%a</b> - Remote IP address * <li><b>%A</b> - Local IP address * <li><b>%b</b> - Bytes sent, excluding HTTP headers, or '-' if no bytes * were sent * <li><b>%B</b> - Bytes sent, excluding HTTP headers * <li><b>%h</b> - Remote host name (or IP address if * <code>enableLookups</code> for the connector is false) * <li><b>%H</b> - Request protocol * <li><b>%l</b> - Remote logical username from identd (always returns '-') * <li><b>%m</b> - Request method * <li><b>%p</b> - Local port * <li><b>%q</b> - Query string (prepended with a '?' if it exists, otherwise * an empty string * <li><b>%r</b> - First line of the request * <li><b>%s</b> - HTTP status code of the response * <li><b>%S</b> - User session ID * <li><b>%t</b> - Date and time, in Common Log Format format * <li><b>%t{format}</b> - Date and time, in any format supported by SimpleDateFormat * <li><b>%u</b> - Remote user that was authenticated * <li><b>%U</b> - Requested URL path * <li><b>%v</b> - Local server name * <li><b>%D</b> - Time taken to process the request, in millis * <li><b>%T</b> - Time taken to process the request, in seconds * <li><b>%I</b> - current Request thread name (can compare later with stacktraces) * </ul> * <p>In addition, the caller can specify one of the following aliases for * commonly utilized patterns:</p> * <ul> * <li><b>common</b> - <code>%h %l %u %t "%r" %s %b</code> * <li><b>combined</b> - * <code>%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"</code> * </ul> * * <p> * There is also support to write information from the cookie, incoming * header, the Session or something else in the ServletRequest.<br> * It is modeled after the * <a href="http://httpd.apache.org/">Apache HTTP Server</a> log configuration * syntax:</p> * <ul> * <li><code>%{xxx}i</code> for incoming headers * <li><code>%{xxx}o</code> for outgoing response headers * <li><code>%{xxx}c</code> for a specific cookie * <li><code>%{xxx}r</code> xxx is an attribute in the ServletRequest * <li><code>%{xxx}s</code> xxx is an attribute in the HttpSession * <li><code>%{xxx}t</code> xxx is an enhanced SimpleDateFormat pattern * (see Configuration Reference document for details on supported time patterns) * </ul> * * <p> * Log rotation can be on or off. This is dictated by the * <code>rotatable</code> property. * </p> * * <p> * For UNIX users, another field called <code>checkExists</code> is also * available. If set to true, the log file's existence will be checked before * each logging. This way an external log rotator can move the file * somewhere and Tomcat will start with a new file. * </p> * * <p> * For JMX junkies, a public method called <code>rotate</code> has * been made available to allow you to tell this instance to move * the existing log file to somewhere else and start writing a new log file. * </p> * * <p> * Conditional logging is also supported. This can be done with the * <code>conditionUnless</code> and <code>conditionIf</code> properties. * If the value returned from ServletRequest.getAttribute(conditionUnless) * yields a non-null value, the logging will be skipped. * If the value returned from ServletRequest.getAttribute(conditionIf) * yields the null value, the logging will be skipped. * The <code>condition</code> attribute is synonym for * <code>conditionUnless</code> and is provided for backwards compatibility. * </p> * * <p> * For extended attributes coming from a getAttribute() call, * it is you responsibility to ensure there are no newline or * control characters. * </p> * * @author Craig R. McClanahan * @author Jason Brittain * @author Remy Maucherat * @author Takayuki Kaneko * @author Peter Rossbach * * @version $Id$ */ public class AccessLogValve extends ValveBase implements AccessLog { private static final Log log = LogFactory.getLog(AccessLogValve.class); //------------------------------------------------------ Constructor public AccessLogValve() { super(true); } // ----------------------------------------------------- Instance Variables /** * The as-of date for the currently open log file, or a zero-length * string if there is no open log file. */ private volatile String dateStamp = ""; /** * The directory in which log files are created. */ private String directory = "logs"; /** * enabled this component */ protected boolean enabled = true; /** * The pattern used to format our access log lines. */ protected String pattern = null; /** * The prefix that is added to log file filenames. */ protected String prefix = "access_log"; /** * Should we rotate our log file? Default is true (like old behavior) */ protected boolean rotatable = true; /** * Should we defer inclusion of the date stamp in the file * name until rotate time? Default is false. */ protected boolean renameOnRotate = false; /** * Buffered logging. */ private boolean buffered = true; /** * The suffix that is added to log file filenames. */ protected String suffix = ""; /** * The PrintWriter to which we are currently logging, if any. */ protected PrintWriter writer = null; /** * A date formatter to format a Date using the format * given by <code>fileDateFormat</code>. */ protected SimpleDateFormat fileDateFormatter = null; /** * The size of our global date format cache */ private static final int globalCacheSize = 300; /** * The size of our thread local date format cache */ private static final int localCacheSize = 60; /** * The current log file we are writing to. Helpful when checkExists * is true. */ protected File currentLogFile = null; /** * <p>Cache structure for formatted timestamps based on seconds.</p> * * <p>The cache consists of entries for a consecutive range of * seconds. The length of the range is configurable. It is * implemented based on a cyclic buffer. New entries shift the range.</p> * * <p>There is one cache for the CLF format (the access log standard * format) and a HashMap of caches for additional formats used by * SimpleDateFormat.</p> * * <p>Although the cache supports specifying a locale when retrieving a * formatted timestamp, each format will always use the locale given * when the format was first used. New locales can only be used for new formats. * The CLF format will always be formatted using the locale * <code>en_US</code>.</p> * * <p>The cache is not threadsafe. It can be used without synchronization * via thread local instances, or with synchronization as a global cache.</p> * * <p>The cache can be created with a parent cache to build a cache hierarchy. * Access to the parent cache is threadsafe.</p> * * <p>This class uses a small thread local first level cache and a bigger * synchronized global second level cache.</p> */ protected static class DateFormatCache { protected class Cache { /* CLF log format */ private static final String cLFFormat = "dd/MMM/yyyy:HH:mm:ss Z"; /* Second used to retrieve CLF format in most recent invocation */ private long previousSeconds = Long.MIN_VALUE; /* Value of CLF format retrieved in most recent invocation */ private String previousFormat = ""; /* First second contained in cache */ private long first = Long.MIN_VALUE; /* Last second contained in cache */ private long last = Long.MIN_VALUE; /* Index of "first" in the cyclic cache */ private int offset = 0; /* Helper object to be able to call SimpleDateFormat.format(). */ private final Date currentDate = new Date(); protected final String cache[]; private SimpleDateFormat formatter; private boolean isCLF = false; private Cache parent = null; private Cache(Cache parent) { this(null, parent); } private Cache(String format, Cache parent) { this(format, null, parent); } private Cache(String format, Locale loc, Cache parent) { cache = new String[cacheSize]; for (int i = 0; i < cacheSize; i++) { cache[i] = null; } if (loc == null) { loc = cacheDefaultLocale; } if (format == null) { isCLF = true; format = cLFFormat; formatter = new SimpleDateFormat(format, Locale.US); } else { formatter = new SimpleDateFormat(format, loc); } formatter.setTimeZone(TimeZone.getDefault()); this.parent = parent; } private String getFormatInternal(long time) { long seconds = time / 1000; /* First step: if we have seen this timestamp during the previous call, and we need CLF, return the previous value. */ if (seconds == previousSeconds) { return previousFormat; } /* Second step: Try to locate in cache */ previousSeconds = seconds; int index = (offset + (int)(seconds - first)) % cacheSize; if (index < 0) { index += cacheSize; } if (seconds >= first && seconds <= last) { if (cache[index] != null) { /* Found, so remember for next call and return.*/ previousFormat = cache[index]; return previousFormat; } /* Third step: not found in cache, adjust cache and add item */ } else if (seconds >= last + cacheSize || seconds <= first - cacheSize) { first = seconds; last = first + cacheSize - 1; index = 0; offset = 0; for (int i = 1; i < cacheSize; i++) { cache[i] = null; } } else if (seconds > last) { for (int i = 1; i < seconds - last; i++) { cache[(index + cacheSize - i) % cacheSize] = null; } first = seconds - (cacheSize - 1); last = seconds; offset = (index + 1) % cacheSize; } else if (seconds < first) { for (int i = 1; i < first - seconds; i++) { cache[(index + i) % cacheSize] = null; } first = seconds; last = seconds + (cacheSize - 1); offset = index; } /* Last step: format new timestamp either using * parent cache or locally. */ if (parent != null) { synchronized(parent) { previousFormat = parent.getFormatInternal(time); } } else { currentDate.setTime(time); previousFormat = formatter.format(currentDate); if (isCLF) { StringBuilder current = new StringBuilder(32); current.append('['); current.append(previousFormat); current.append(']'); previousFormat = current.toString(); } } cache[index] = previousFormat; return previousFormat; } } /* Number of cached entries */ private int cacheSize = 0; private final Locale cacheDefaultLocale; private final DateFormatCache parent; protected final Cache cLFCache; private final HashMap<String, Cache> formatCache = new HashMap<>(); protected DateFormatCache(int size, Locale loc, DateFormatCache parent) { cacheSize = size; cacheDefaultLocale = loc; this.parent = parent; Cache parentCache = null; if (parent != null) { synchronized(parent) { parentCache = parent.getCache(null, null); } } cLFCache = new Cache(parentCache); } private Cache getCache(String format, Locale loc) { Cache cache; if (format == null) { cache = cLFCache; } else { cache = formatCache.get(format); if (cache == null) { Cache parentCache = null; if (parent != null) { synchronized(parent) { parentCache = parent.getCache(format, loc); } } cache = new Cache(format, loc, parentCache); formatCache.put(format, cache); } } return cache; } public String getFormat(long time) { return cLFCache.getFormatInternal(time); } public String getFormat(String format, Locale loc, long time) { return getCache(format, loc).getFormatInternal(time); } } /** * Global date format cache. */ private static final DateFormatCache globalDateCache = new DateFormatCache(globalCacheSize, Locale.getDefault(), null); /** * Thread local date format cache. */ private static final ThreadLocal<DateFormatCache> localDateCache = new ThreadLocal<DateFormatCache>() { @Override protected DateFormatCache initialValue() { return new DateFormatCache(localCacheSize, Locale.getDefault(), globalDateCache); } }; /** * The system time when we last updated the Date that this valve * uses for log lines. */ private static final ThreadLocal<Date> localDate = new ThreadLocal<Date>() { @Override protected Date initialValue() { return new Date(); } }; /** * The list of our format types. */ private static enum FormatType { CLF, SEC, MSEC, MSEC_FRAC, SDF } /** * Instant when the log daily rotation was last checked. */ private volatile long rotationLastChecked = 0L; /** * Do we check for log file existence? Helpful if an external * agent renames the log file so we can automagically recreate it. */ private boolean checkExists = false; /** * Are we doing conditional logging. default null. * It is the value of <code>conditionUnless</code> property. */ protected String condition = null; /** * Are we doing conditional logging. default null. * It is the value of <code>conditionIf</code> property. */ protected String conditionIf = null; /** * Date format to place in log file name. */ protected String fileDateFormat = ".yyyy-MM-dd"; /** * Name of locale used to format timestamps in log entries and in * log file name suffix. */ protected String localeName = Locale.getDefault().toString(); /** * Locale used to format timestamps in log entries and in * log file name suffix. */ protected Locale locale = Locale.getDefault(); /** * Character set used by the log file. If it is <code>null</code>, the * system default character set will be used. An empty string will be * treated as <code>null</code> when this property is assigned. */ protected String encoding = null; /** * Array of AccessLogElement, they will be used to make log message. */ protected AccessLogElement[] logElements = null; /** * @see #setRequestAttributesEnabled(boolean) */ protected boolean requestAttributesEnabled = false; /** * Buffer pool used for log message generation. Pool used to reduce garbage * generation. */ private SynchronizedStack<CharArrayWriter> charArrayWriters = new SynchronizedStack<>(); /** * Log message buffers are usually recycled and re-used. To prevent * excessive memory usage, if a buffer grows beyond this size it will be * discarded. The default is 256 characters. This should be set to larger * than the typical access log message size. */ private int maxLogMessageBufferSize = 256; // ------------------------------------------------------------- Properties public int getMaxLogMessageBufferSize() { return maxLogMessageBufferSize; } public void setMaxLogMessageBufferSize(int maxLogMessageBufferSize) { this.maxLogMessageBufferSize = maxLogMessageBufferSize; } /** * {@inheritDoc} */ @Override public void setRequestAttributesEnabled(boolean requestAttributesEnabled) { this.requestAttributesEnabled = requestAttributesEnabled; } /** * {@inheritDoc} */ @Override public boolean getRequestAttributesEnabled() { return requestAttributesEnabled; } /** * @return Returns the enabled. */ public boolean getEnabled() { return enabled; } /** * @param enabled * The enabled to set. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Return the directory in which we create log files. */ public String getDirectory() { return (directory); } /** * Set the directory in which we create log files. * * @param directory The new log file directory */ public void setDirectory(String directory) { this.directory = directory; } /** * Return the format pattern. */ public String getPattern() { return (this.pattern); } /** * Set the format pattern, first translating any recognized alias. * * @param pattern The new pattern */ public void setPattern(String pattern) { if (pattern == null) { this.pattern = ""; } else if (pattern.equals(Constants.AccessLog.COMMON_ALIAS)) { this.pattern = Constants.AccessLog.COMMON_PATTERN; } else if (pattern.equals(Constants.AccessLog.COMBINED_ALIAS)) { this.pattern = Constants.AccessLog.COMBINED_PATTERN; } else { this.pattern = pattern; } logElements = createLogElements(); } /** * Check for file existence before logging. */ public boolean isCheckExists() { return checkExists; } /** * Set whether to check for log file existence before logging. * * @param checkExists true meaning to check for file existence. */ public void setCheckExists(boolean checkExists) { this.checkExists = checkExists; } /** * Return the log file prefix. */ public String getPrefix() { return (prefix); } /** * Set the log file prefix. * * @param prefix The new log file prefix */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Should we rotate the logs */ public boolean isRotatable() { return rotatable; } /** * Set the value is we should we rotate the logs * * @param rotatable true is we should rotate. */ public void setRotatable(boolean rotatable) { this.rotatable = rotatable; } /** * Should we defer inclusion of the date stamp in the file * name until rotate time */ public boolean isRenameOnRotate() { return renameOnRotate; } /** * Set the value if we should defer inclusion of the date * stamp in the file name until rotate time * * @param renameOnRotate true if defer inclusion of date stamp */ public void setRenameOnRotate(boolean renameOnRotate) { this.renameOnRotate = renameOnRotate; } /** * Is the logging buffered */ public boolean isBuffered() { return buffered; } /** * Set the value if the logging should be buffered * * @param buffered true if buffered. */ public void setBuffered(boolean buffered) { this.buffered = buffered; } /** * Return the log file suffix. */ public String getSuffix() { return (suffix); } /** * Set the log file suffix. * * @param suffix The new log file suffix */ public void setSuffix(String suffix) { this.suffix = suffix; } /** * Return whether the attribute name to look for when * performing conditional logging. If null, every * request is logged. */ public String getCondition() { return condition; } /** * Set the ServletRequest.attribute to look for to perform * conditional logging. Set to null to log everything. * * @param condition Set to null to log everything */ public void setCondition(String condition) { this.condition = condition; } /** * Return whether the attribute name to look for when * performing conditional logging. If null, every * request is logged. */ public String getConditionUnless() { return getCondition(); } /** * Set the ServletRequest.attribute to look for to perform * conditional logging. Set to null to log everything. * * @param condition Set to null to log everything */ public void setConditionUnless(String condition) { setCondition(condition); } /** * Return whether the attribute name to look for when * performing conditional logging. If null, every * request is logged. */ public String getConditionIf() { return conditionIf; } /** * Set the ServletRequest.attribute to look for to perform * conditional logging. Set to null to log everything. * * @param condition Set to null to log everything */ public void setConditionIf(String condition) { this.conditionIf = condition; } /** * Return the date format date based log rotation. */ public String getFileDateFormat() { return fileDateFormat; } /** * Set the date format date based log rotation. */ public void setFileDateFormat(String fileDateFormat) { String newFormat; if (fileDateFormat == null) { newFormat = ""; } else { newFormat = fileDateFormat; } this.fileDateFormat = newFormat; synchronized (this) { fileDateFormatter = new SimpleDateFormat(newFormat, Locale.US); fileDateFormatter.setTimeZone(TimeZone.getDefault()); } } /** * Return the locale used to format timestamps in log entries and in * log file name suffix. */ public String getLocale() { return localeName; } /** * Set the locale used to format timestamps in log entries and in * log file name suffix. Changing the locale is only supported * as long as the AccessLogValve has not logged anything. Changing * the locale later can lead to inconsistent formatting. * * @param localeName The locale to use. */ public void setLocale(String localeName) { this.localeName = localeName; locale = findLocale(localeName, locale); } /** * Return the character set name that is used to write the log file. * * @return Character set name, or <code>null</code> if the system default * character set is used. */ public String getEncoding() { return encoding; } /** * Set the character set that is used to write the log file. * * @param encoding The name of the character set. */ public void setEncoding(String encoding) { if (encoding != null && encoding.length() > 0) { this.encoding = encoding; } else { this.encoding = null; } } // --------------------------------------------------------- Public Methods /** * Execute a periodic task, such as reloading, etc. This method will be * invoked inside the classloading context of this container. Unexpected * throwables will be caught and logged. */ @Override public synchronized void backgroundProcess() { if (getState().isAvailable() && getEnabled() && writer != null && buffered) { writer.flush(); } } /** * Log a message summarizing the specified request and response, according * to the format specified by the <code>pattern</code> property. * * @param request Request being processed * @param response Response being processed * * @exception IOException if an input/output error has occurred * @exception ServletException if a servlet error has occurred */ @Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); } @Override public void log(Request request, Response response, long time) { if (!getState().isAvailable() || !getEnabled() || logElements == null || condition != null && null != request.getRequest().getAttribute(condition) || conditionIf != null && null == request.getRequest().getAttribute(conditionIf)) { return; } /** * XXX This is a bit silly, but we want to have start and stop time and * duration consistent. It would be better to keep start and stop * simply in the request and/or response object and remove time * (duration) from the interface. */ long start = request.getCoyoteRequest().getStartTime(); Date date = getDate(start + time); CharArrayWriter result = charArrayWriters.pop(); if (result == null) { result = new CharArrayWriter(128); } for (int i = 0; i < logElements.length; i++) { logElements[i].addElement(result, date, request, response, time); } log(result); if (result.size() <= maxLogMessageBufferSize) { result.reset(); charArrayWriters.push(result); } } /** * Rotate the log file if necessary. */ public void rotate() { if (rotatable) { // Only do a logfile switch check once a second, max. long systime = System.currentTimeMillis(); if ((systime - rotationLastChecked) > 1000) { synchronized(this) { if ((systime - rotationLastChecked) > 1000) { rotationLastChecked = systime; String tsDate; // Check for a change of date tsDate = fileDateFormatter.format(new Date(systime)); // If the date has changed, switch log files if (!dateStamp.equals(tsDate)) { close(true); dateStamp = tsDate; open(); } } } } } } /** * Rename the existing log file to something else. Then open the * old log file name up once again. Intended to be called by a JMX * agent. * * * @param newFileName The file name to move the log file entry to * @return true if a file was rotated with no error */ public synchronized boolean rotate(String newFileName) { if (currentLogFile != null) { File holder = currentLogFile; close(false); try { holder.renameTo(new File(newFileName)); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); } /* Make sure date is correct */ dateStamp = fileDateFormatter.format( new Date(System.currentTimeMillis())); open(); return true; } else { return false; } } // -------------------------------------------------------- Private Methods /** * Create a File object based on the current log file name. * Directories are created as needed but the underlying file * is not created or opened. * * @param useDateStamp include the timestamp in the file name. * @return the log file object */ private File getLogFile(boolean useDateStamp) { // Create the directory if necessary File dir = new File(directory); if (!dir.isAbsolute()) { dir = new File(getContainer().getCatalinaBase(), directory); } if (!dir.mkdirs() && !dir.isDirectory()) { log.error(sm.getString("accessLogValve.openDirFail", dir)); } // Calculate the current log file name File pathname; if (useDateStamp) { pathname = new File(dir.getAbsoluteFile(), prefix + dateStamp + suffix); } else { pathname = new File(dir.getAbsoluteFile(), prefix + suffix); } File parent = pathname.getParentFile(); if (!parent.mkdirs() && !parent.isDirectory()) { log.error(sm.getString("accessLogValve.openDirFail", parent)); } return pathname; } /** * Move a current but rotated log file back to the unrotated * one. Needed if date stamp inclusion is deferred to rotation * time. */ private void restore() { File newLogFile = getLogFile(false); File rotatedLogFile = getLogFile(true); if (rotatedLogFile.exists() && !newLogFile.exists() && !rotatedLogFile.equals(newLogFile)) { try { if (!rotatedLogFile.renameTo(newLogFile)) { log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile)); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile), e); } } } /** * Close the currently open log file (if any) * * @param rename Rename file to final name after closing */ private synchronized void close(boolean rename) { if (writer == null) { return; } writer.flush(); writer.close(); if (rename && renameOnRotate) { File newLogFile = getLogFile(true); if (!newLogFile.exists()) { try { if (!currentLogFile.renameTo(newLogFile)) { log.error(sm.getString("accessLogValve.renameFail", currentLogFile, newLogFile)); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.renameFail", currentLogFile, newLogFile), e); } } else { log.error(sm.getString("accessLogValve.alreadyExists", currentLogFile, newLogFile)); } } writer = null; dateStamp = ""; currentLogFile = null; } /** * Log the specified message to the log file, switching files if the date * has changed since the previous log call. * * @param message Message to be logged */ public void log(CharArrayWriter message) { rotate(); /* In case something external rotated the file instead */ if (checkExists) { synchronized (this) { if (currentLogFile != null && !currentLogFile.exists()) { try { close(false); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); } /* Make sure date is correct */ dateStamp = fileDateFormatter.format( new Date(System.currentTimeMillis())); open(); } } } // Log this message try { synchronized(this) { if (writer != null) { message.writeTo(writer); writer.println(""); if (!buffered) { writer.flush(); } } } } catch (IOException ioe) { log.warn(sm.getString( "accessLogValve.writeFail", message.toString()), ioe); } } /** * Open the new log file for the date specified by <code>dateStamp</code>. */ protected synchronized void open() { // Open the current log file // If no rotate - no need for dateStamp in fileName File pathname = getLogFile(rotatable && !renameOnRotate); Charset charset = null; if (encoding != null) { try { charset = B2CConverter.getCharset(encoding); } catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); } } if (charset == null) { charset = B2CConverter.ISO_8859_1; } try { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( new FileOutputStream(pathname, true), charset), 128000), false); currentLogFile = pathname; } catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); } } /** * This method returns a Date object that is accurate to within one second. * If a thread calls this method to get a Date and it's been less than 1 * second since a new Date was created, this method simply gives out the * same Date again so that the system doesn't spend time creating Date * objects unnecessarily. * * @return Date */ private static Date getDate(long systime) { Date date = localDate.get(); date.setTime(systime); return date; } /** * Find a locale by name */ protected static Locale findLocale(String name, Locale fallback) { if (name == null || name.isEmpty()) { return Locale.getDefault(); } else { for (Locale l: Locale.getAvailableLocales()) { if (name.equals(l.toString())) { return(l); } } } log.error(sm.getString("accessLogValve.invalidLocale", name)); return fallback; } /** * Start this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void startInternal() throws LifecycleException { // Initialize the Date formatters String format = getFileDateFormat(); fileDateFormatter = new SimpleDateFormat(format, Locale.US); fileDateFormatter.setTimeZone(TimeZone.getDefault()); dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis())); if (rotatable && renameOnRotate) { restore(); } open(); setState(LifecycleState.STARTING); } /** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); close(false); } /** * AccessLogElement writes the partial message into the buffer. */ protected interface AccessLogElement { public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time); } /** * write thread name - %I */ protected static class ThreadNameElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { RequestInfo info = request.getCoyoteRequest().getRequestProcessor(); if(info != null) { buf.append(info.getWorkerThreadName()); } else { buf.append("-"); } } } /** * write local IP address - %A */ protected static class LocalAddrElement implements AccessLogElement { private static final String LOCAL_ADDR_VALUE; static { String init; try { init = InetAddress.getLocalHost().getHostAddress(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); init = "127.0.0.1"; } LOCAL_ADDR_VALUE = init; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { buf.append(LOCAL_ADDR_VALUE); } } /** * write remote IP address - %a */ protected class RemoteAddrElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (requestAttributesEnabled) { Object addr = request.getAttribute(REMOTE_ADDR_ATTRIBUTE); if (addr == null) { buf.append(request.getRemoteAddr()); } else { buf.append(addr.toString()); } } else { buf.append(request.getRemoteAddr()); } } } /** * write remote host name - %h */ protected class HostElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { String value = null; if (requestAttributesEnabled) { Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE); if (host != null) { value = host.toString(); } } if (value == null || value.length() == 0) { value = request.getRemoteHost(); } if (value == null || value.length() == 0) { value = "-"; } buf.append(value); } } /** * write remote logical username from identd (always returns '-') - %l */ protected static class LogicalUserNameElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { buf.append('-'); } } /** * write request protocol - %H */ protected class ProtocolElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (requestAttributesEnabled) { Object proto = request.getAttribute(PROTOCOL_ATTRIBUTE); if (proto == null) { buf.append(request.getProtocol()); } else { buf.append(proto.toString()); } } else { buf.append(request.getProtocol()); } } } /** * write remote user that was authenticated (if any), else '-' - %u */ protected static class UserElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { String value = request.getRemoteUser(); if (value != null) { buf.append(value); } else { buf.append('-'); } } else { buf.append('-'); } } } /** * write date and time, in configurable format (default CLF) - %t or %t{format} */ protected class DateAndTimeElement implements AccessLogElement { /** * Format prefix specifying request start time */ private static final String requestStartPrefix = "begin"; /** * Format prefix specifying response end time */ private static final String responseEndPrefix = "end"; /** * Separator between optional prefix and rest of format */ private static final String prefixSeparator = ":"; /** * Special format for seconds since epoch */ private static final String secFormat = "sec"; /** * Special format for milliseconds since epoch */ private static final String msecFormat = "msec"; /** * Special format for millisecond part of timestamp */ private static final String msecFractionFormat = "msec_frac"; /** * The patterns we use to replace "S" and "SSS" millisecond * formatting of SimpleDateFormat by our own handling */ private static final String msecPattern = "{#}"; private static final String trippleMsecPattern = msecPattern + msecPattern + msecPattern; /* Our format description string, null if CLF */ private final String format; /* Whether to use begin of request or end of response as the timestamp */ private final boolean usesBegin; /* The format type */ private final FormatType type; /* Whether we need to postprocess by adding milliseconds */ private boolean usesMsecs = false; protected DateAndTimeElement() { this(null); } /** * Replace the millisecond formatting character 'S' by * some dummy characters in order to make the resulting * formatted time stamps cacheable. We replace the dummy * chars later with the actual milliseconds because that's * relatively cheap. */ private String tidyFormat(String format) { boolean escape = false; StringBuilder result = new StringBuilder(); int len = format.length(); char x; for (int i = 0; i < len; i++) { x = format.charAt(i); if (escape || x != 'S') { result.append(x); } else { result.append(msecPattern); usesMsecs = true; } if (x == '\'') { escape = !escape; } } return result.toString(); } protected DateAndTimeElement(String header) { String format = header; boolean usesBegin = false; FormatType type = FormatType.CLF; if (format != null) { if (format.equals(requestStartPrefix)) { usesBegin = true; format = ""; } else if (format.startsWith(requestStartPrefix + prefixSeparator)) { usesBegin = true; format = format.substring(6); } else if (format.equals(responseEndPrefix)) { usesBegin = false; format = ""; } else if (format.startsWith(responseEndPrefix + prefixSeparator)) { usesBegin = false; format = format.substring(4); } if (format.length() == 0) { type = FormatType.CLF; } else if (format.equals(secFormat)) { type = FormatType.SEC; } else if (format.equals(msecFormat)) { type = FormatType.MSEC; } else if (format.equals(msecFractionFormat)) { type = FormatType.MSEC_FRAC; } else { type = FormatType.SDF; format = tidyFormat(format); } } this.format = format; this.usesBegin = usesBegin; this.type = type; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { long timestamp = date.getTime(); long frac; if (usesBegin) { timestamp -= time; } switch (type) { case CLF: buf.append(localDateCache.get().getFormat(timestamp)); break; case SEC: buf.append(Long.toString(timestamp / 1000)); break; case MSEC: buf.append(Long.toString(timestamp)); break; case MSEC_FRAC: frac = timestamp % 1000; if (frac < 100) { if (frac < 10) { buf.append('0'); buf.append('0'); } else { buf.append('0'); } } buf.append(Long.toString(frac)); break; case SDF: String temp = localDateCache.get().getFormat(format, locale, timestamp); if (usesMsecs) { frac = timestamp % 1000; StringBuilder trippleMsec = new StringBuilder(4); if (frac < 100) { if (frac < 10) { trippleMsec.append('0'); trippleMsec.append('0'); } else { trippleMsec.append('0'); } } trippleMsec.append(frac); temp = temp.replace(trippleMsecPattern, trippleMsec); temp = temp.replace(msecPattern, Long.toString(frac)); } buf.append(temp); break; } } } /** * write first line of the request (method and request URI) - %r */ protected static class RequestElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { String method = request.getMethod(); if (method == null) { // No method means no request line buf.append('-'); } else { buf.append(request.getMethod()); buf.append(' '); buf.append(request.getRequestURI()); if (request.getQueryString() != null) { buf.append('?'); buf.append(request.getQueryString()); } buf.append(' '); buf.append(request.getProtocol()); } } else { buf.append('-'); } } } /** * write HTTP status code of the response - %s */ protected static class HttpStatusCodeElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (response != null) { // This approach is used to reduce GC from toString conversion int status = response.getStatus(); if (100 <= status && status < 1000) { buf.append((char) ('0' + (status / 100))) .append((char) ('0' + ((status / 10) % 10))) .append((char) ('0' + (status % 10))); } else { buf.append(Integer.toString(status)); } } else { buf.append('-'); } } } /** * write local port on which this request was received - %p */ protected class LocalPortElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (requestAttributesEnabled) { Object port = request.getAttribute(SERVER_PORT_ATTRIBUTE); if (port == null) { buf.append(Integer.toString(request.getServerPort())); } else { buf.append(port.toString()); } } else { buf.append(Integer.toString(request.getServerPort())); } } } /** * write bytes sent, excluding HTTP headers - %b, %B */ protected static class ByteSentElement implements AccessLogElement { private final boolean conversion; /** * if conversion is true, write '-' instead of 0 - %b */ public ByteSentElement(boolean conversion) { this.conversion = conversion; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { // Don't need to flush since trigger for log message is after the // response has been committed long length = response.getBytesWritten(false); if (length <= 0) { // Protect against nulls and unexpected types as these values // may be set by untrusted applications Object start = request.getAttribute( Globals.SENDFILE_FILE_START_ATTR); if (start instanceof Long) { Object end = request.getAttribute( Globals.SENDFILE_FILE_END_ATTR); if (end instanceof Long) { length = ((Long) end).longValue() - ((Long) start).longValue(); } } } if (length <= 0 && conversion) { buf.append('-'); } else { buf.append(Long.toString(length)); } } } /** * write request method (GET, POST, etc.) - %m */ protected static class MethodElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { buf.append(request.getMethod()); } } } /** * write time taken to process the request - %D, %T */ protected static class ElapsedTimeElement implements AccessLogElement { private final boolean millis; /** * if millis is true, write time in millis - %D * if millis is false, write time in seconds - %T */ public ElapsedTimeElement(boolean millis) { this.millis = millis; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (millis) { buf.append(Long.toString(time)); } else { // second buf.append(Long.toString(time / 1000)); buf.append('.'); int remains = (int) (time % 1000); buf.append(Long.toString(remains / 100)); remains = remains % 100; buf.append(Long.toString(remains / 10)); buf.append(Long.toString(remains % 10)); } } } /** * write Query string (prepended with a '?' if it exists) - %q */ protected static class QueryElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { String query = null; if (request != null) { query = request.getQueryString(); } if (query != null) { buf.append('?'); buf.append(query); } } } /** * write user session ID - %S */ protected static class SessionIdElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request == null) { buf.append('-'); } else { Session session = request.getSessionInternal(false); if (session == null) { buf.append('-'); } else { buf.append(session.getIdInternal()); } } } } /** * write requested URL path - %U */ protected static class RequestURIElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { buf.append(request.getRequestURI()); } else { buf.append('-'); } } } /** * write local server name - %v */ protected static class LocalServerNameElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { buf.append(request.getServerName()); } } /** * write any string */ protected static class StringElement implements AccessLogElement { private final String str; public StringElement(String str) { this.str = str; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { buf.append(str); } } /** * write incoming headers - %{xxx}i */ protected static class HeaderElement implements AccessLogElement { private final String header; public HeaderElement(String header) { this.header = header; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { Enumeration<String> iter = request.getHeaders(header); if (iter.hasMoreElements()) { buf.append(iter.nextElement()); while (iter.hasMoreElements()) { buf.append(',').append(iter.nextElement()); } return; } buf.append('-'); } } /** * write a specific cookie - %{xxx}c */ protected static class CookieElement implements AccessLogElement { private final String header; public CookieElement(String header) { this.header = header; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { String value = "-"; Cookie[] c = request.getCookies(); if (c != null) { for (int i = 0; i < c.length; i++) { if (header.equals(c[i].getName())) { value = c[i].getValue(); break; } } } buf.append(value); } } /** * write a specific response header - %{xxx}o */ protected static class ResponseHeaderElement implements AccessLogElement { private final String header; public ResponseHeaderElement(String header) { this.header = header; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (null != response) { Iterator<String> iter = response.getHeaders(header).iterator(); if (iter.hasNext()) { buf.append(iter.next()); while (iter.hasNext()) { buf.append(',').append(iter.next()); } return; } } buf.append('-'); } } /** * write an attribute in the ServletRequest - %{xxx}r */ protected static class RequestAttributeElement implements AccessLogElement { private final String header; public RequestAttributeElement(String header) { this.header = header; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { Object value = null; if (request != null) { value = request.getAttribute(header); } else { value = "??"; } if (value != null) { if (value instanceof String) { buf.append((String) value); } else { buf.append(value.toString()); } } else { buf.append('-'); } } } /** * write an attribute in the HttpSession - %{xxx}s */ protected static class SessionAttributeElement implements AccessLogElement { private final String header; public SessionAttributeElement(String header) { this.header = header; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { Object value = null; if (null != request) { HttpSession sess = request.getSession(false); if (null != sess) { value = sess.getAttribute(header); } } else { value = "??"; } if (value != null) { if (value instanceof String) { buf.append((String) value); } else { buf.append(value.toString()); } } else { buf.append('-'); } } } /** * parse pattern string and create the array of AccessLogElement */ protected AccessLogElement[] createLogElements() { List<AccessLogElement> list = new ArrayList<>(); boolean replace = false; StringBuilder buf = new StringBuilder(); for (int i = 0; i < pattern.length(); i++) { char ch = pattern.charAt(i); if (replace) { /* * For code that processes {, the behavior will be ... if I do * not encounter a closing } - then I ignore the { */ if ('{' == ch) { StringBuilder name = new StringBuilder(); int j = i + 1; for (; j < pattern.length() && '}' != pattern.charAt(j); j++) { name.append(pattern.charAt(j)); } if (j + 1 < pattern.length()) { /* the +1 was to account for } which we increment now */ j++; list.add(createAccessLogElement(name.toString(), pattern.charAt(j))); i = j; /* Since we walked more than one character */ } else { // D'oh - end of string - pretend we never did this // and do processing the "old way" list.add(createAccessLogElement(ch)); } } else { list.add(createAccessLogElement(ch)); } replace = false; } else if (ch == '%') { replace = true; list.add(new StringElement(buf.toString())); buf = new StringBuilder(); } else { buf.append(ch); } } if (buf.length() > 0) { list.add(new StringElement(buf.toString())); } return list.toArray(new AccessLogElement[0]); } /** * create an AccessLogElement implementation which needs header string */ protected AccessLogElement createAccessLogElement(String header, char pattern) { switch (pattern) { case 'i': return new HeaderElement(header); case 'c': return new CookieElement(header); case 'o': return new ResponseHeaderElement(header); case 'r': return new RequestAttributeElement(header); case 's': return new SessionAttributeElement(header); case 't': return new DateAndTimeElement(header); default: return new StringElement("???"); } } /** * create an AccessLogElement implementation */ protected AccessLogElement createAccessLogElement(char pattern) { switch (pattern) { case 'a': return new RemoteAddrElement(); case 'A': return new LocalAddrElement(); case 'b': return new ByteSentElement(true); case 'B': return new ByteSentElement(false); case 'D': return new ElapsedTimeElement(true); case 'h': return new HostElement(); case 'H': return new ProtocolElement(); case 'l': return new LogicalUserNameElement(); case 'm': return new MethodElement(); case 'p': return new LocalPortElement(); case 'q': return new QueryElement(); case 'r': return new RequestElement(); case 's': return new HttpStatusCodeElement(); case 'S': return new SessionIdElement(); case 't': return new DateAndTimeElement(); case 'T': return new ElapsedTimeElement(false); case 'u': return new UserElement(); case 'U': return new RequestURIElement(); case 'v': return new LocalServerNameElement(); case 'I': return new ThreadNameElement(); default: return new StringElement("???" + pattern + "???"); } } }
55,102
Bug 55102 Add ability to report time taken to prepare response
null
closed fixed
7aea9cb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-23T20:22:25Z
2013-06-15T21:00:00Z
java/org/apache/coyote/Response.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.io.StringReader; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.WriteListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.HttpParser; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] * @author Harish Prabandham * @author Hans Bergsten <hans@gefionsoftware.com> * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ protected int status = 200; /** * Status message. */ protected String message = null; /** * Response headers. */ protected final MimeHeaders headers = new MimeHeaders(); /** * Associated output buffer. */ protected OutputBuffer outputBuffer; /** * Notes. */ protected final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ protected boolean commited = false; /** * Action hook. */ public ActionHook hook; /** * HTTP specific fields. */ protected String contentType = null; protected String contentLanguage = null; protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; protected long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General informations private long contentWritten = 0; /** * Holds request error exception. */ protected Exception errorException = null; /** * Has the charset been explicitly set. */ protected boolean charsetSet = false; protected Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public OutputBuffer getOutputBuffer() { return outputBuffer; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } public ActionHook getHook() { return hook; } public void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if( param==null ) hook.action(actionCode, this); else hook.action(actionCode, param); } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status */ public void setStatus( int status ) { this.status = status; } /** * Get the status message. */ public String getMessage() { return message; } /** * Set the status message. */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return commited; } public void setCommitted(boolean v) { this.commited = v; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during * request processing. */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during request * processing. */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return ( errorException != null ); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); } public void finish() { action(ActionCode.CLOSE, this); } public void acknowledge() { action(ActionCode.ACK, this); } // -------------------- Headers -------------------- /** * Warning: This method always returns <code>false<code> for Content-Type * and Content-Length. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.addValue(name).setString( value ); } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); commited = true; } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and * the default encoding */ public void setLocale(Locale locale) { if (locale == null) { return; // throw an exception? } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.getLanguage(); if ((contentLanguage != null) && (contentLanguage.length() > 0)) { String country = locale.getCountry(); StringBuilder value = new StringBuilder(contentLanguage); if ((country != null) && (country.length() > 0)) { value.append('-'); value.append(country); } contentLanguage = value.toString(); } } /** * Return the content language. */ public String getContentLanguage() { return contentLanguage; } /* * Overrides the name of the character encoding used in the body * of the response. This method must be called prior to writing output * using getWriter(). * * @param charset String containing the name of the character encoding. */ public void setCharacterEncoding(String charset) { if (isCommitted()) return; if (charset == null) return; characterEncoding = charset; charsetSet=true; } public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = HttpParser.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset().trim(); if (charsetValue != null && charsetValue.length() > 0) { charsetSet = true; this.characterEncoding = charsetValue; } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && characterEncoding != null && charsetSet) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(int contentLength) { this.contentLength = contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. */ public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/) throws IOException { outputBuffer.doWrite(chunk, this); contentWritten+=chunk.getLength(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; charsetSet = false; contentLength = -1; status = 200; message = null; commited = false; errorException = null; headers.clear(); listener = null; // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ protected volatile WriteListener listener; private boolean fireListener = false; private boolean registeredForWrite = false; private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; } public boolean isReady() { if (listener == null) { // TODO i18n throw new IllegalStateException("not in non blocking mode."); } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(false); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite(boolean internal) { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite || internal) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
55,151
Bug 55151 Fix in MsgByte encoder and decoder TestEncodingDecoding websocket test
null
resolved fixed
d71136a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-06-27T20:10:40Z
2013-06-27T21:53:20Z
test/org/apache/tomcat/websocket/pojo/TestEncodingDecoding.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.pojo; import java.io.IOException; import java.net.URI; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.servlet.ServletContextEvent; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.DeploymentException; import javax.websocket.EncodeException; import javax.websocket.Encoder; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.Extension; import javax.websocket.MessageHandler; import javax.websocket.OnMessage; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.websocket.server.ServerContainer; import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.deploy.ApplicationListener; import org.apache.catalina.servlets.DefaultServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.websocket.pojo.TesterUtil.ServerConfigListener; import org.apache.tomcat.websocket.pojo.TesterUtil.SingletonConfigurator; import org.apache.tomcat.websocket.server.WsListener; public class TestEncodingDecoding extends TomcatBaseTest { private static final String MESSAGE_ONE = "message-one"; private static final String PATH_PROGRAMMATIC_EP = "/echoProgrammaticEP"; private static final String PATH_ANNOTATED_EP = "/echoAnnotatedEP"; @Test public void testProgrammaticEndPoints() throws Exception{ Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( ProgramaticServerEndpointConfig.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Client client = new Client(); URI uri = new URI("ws://localhost:" + getPort() + PATH_PROGRAMMATIC_EP); Session session = wsContainer.connectToServer(client, uri); MsgString msg1 = new MsgString(); msg1.setData(MESSAGE_ONE); session.getBasicRemote().sendObject(msg1); // Should not take very long int i = 0; while (i < 20) { if (MsgStringMessageHandler.received.size() > 0 && client.received.size() > 0) { break; } Thread.sleep(100); i++; } // Check messages were received Assert.assertEquals(1, MsgStringMessageHandler.received.size()); Assert.assertEquals(1, client.received.size()); // Check correct messages were received Assert.assertEquals(MESSAGE_ONE, ((MsgString) MsgStringMessageHandler.received.peek()).getData()); Assert.assertEquals(MESSAGE_ONE, ((MsgString) client.received.peek()).getData()); session.close(); } @Test public void testAnnotatedEndPoints() throws Exception { // Set up utility classes Server server = new Server(); SingletonConfigurator.setInstance(server); ServerConfigListener.setPojoClazz(Server.class); Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(new ApplicationListener( ServerConfigListener.class.getName(), false)); Tomcat.addServlet(ctx, "default", new DefaultServlet()); ctx.addServletMapping("/", "default"); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Client client = new Client(); URI uri = new URI("ws://localhost:" + getPort() + PATH_ANNOTATED_EP); Session session = wsContainer.connectToServer(client, uri); MsgString msg1 = new MsgString(); msg1.setData(MESSAGE_ONE); session.getBasicRemote().sendObject(msg1); // Should not take very long int i = 0; while (i < 20) { if (server.received.size() > 0 && client.received.size() > 0) { break; } Thread.sleep(100); } // Check messages were received Assert.assertEquals(1, server.received.size()); Assert.assertEquals(1, client.received.size()); // Check correct messages were received Assert.assertEquals(MESSAGE_ONE, ((MsgString) server.received.peek()).getData()); Assert.assertEquals(MESSAGE_ONE, ((MsgString) client.received.peek()).getData()); session.close(); Thread.sleep(100); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgStringEncoder.class.getName()+":init")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgStringDecoder.class.getName()+":init")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgByteEncoder.class.getName()+":init")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgByteDecoder.class.getName()+":init")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgStringEncoder.class.getName()+":destroy")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgStringDecoder.class.getName()+":destroy")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgByteEncoder.class.getName()+":destroy")); Assert.assertTrue(Server.isLifeCycleEventCalled( MsgByteDecoder.class.getName()+":destroy")); } @ClientEndpoint(decoders={MsgStringDecoder.class, MsgByteDecoder.class}, encoders={MsgStringEncoder.class, MsgByteEncoder.class}) public static class Client { private Queue<Object> received = new ConcurrentLinkedQueue<>(); @OnMessage public void rx(MsgString in) { received.add(in); } @OnMessage public void rx(MsgByte in) { received.add(in); } } @ServerEndpoint(value=PATH_ANNOTATED_EP, decoders={MsgStringDecoder.class, MsgByteDecoder.class}, encoders={MsgStringEncoder.class, MsgByteEncoder.class}, configurator=SingletonConfigurator.class) public static class Server { private Queue<Object> received = new ConcurrentLinkedQueue<>(); static HashMap<String, Boolean> lifeCyclesCalled = new HashMap<>(8); @OnMessage public MsgString rx(MsgString in) { received.add(in); // Echo the message back return in; } @OnMessage public MsgByte rx(MsgByte in) { received.add(in); // Echo the message back return in; } public static void addLifeCycleEvent(String event){ lifeCyclesCalled.put(event, Boolean.TRUE); } public static boolean isLifeCycleEventCalled(String event){ Boolean called = lifeCyclesCalled.get(event); return called == null ? false : called.booleanValue(); } } public static class MsgByteMessageHandler implements MessageHandler.Whole<MsgByte> { public static Queue<Object> received = new ConcurrentLinkedQueue<>(); private final Session session; public MsgByteMessageHandler(Session session) { this.session = session; } @Override public void onMessage(MsgByte in) { System.out.println(getClass() + " received"); received.add(in); try { MsgByte msg = new MsgByte(); msg.setData("got it".getBytes()); session.getBasicRemote().sendObject(msg); } catch (IOException | EncodeException e) { throw new IllegalStateException(e); } } } public static class MsgStringMessageHandler implements MessageHandler.Whole<MsgString>{ public static Queue<Object> received = new ConcurrentLinkedQueue<>(); private final Session session; public MsgStringMessageHandler(Session session) { this.session = session; } @Override public void onMessage(MsgString in) { received.add(in); try { MsgString msg = new MsgString(); msg.setData(MESSAGE_ONE); session.getBasicRemote().sendObject(msg); } catch (IOException | EncodeException e) { e.printStackTrace(); } } } public static class ProgrammaticEndpoint extends Endpoint { @Override public void onOpen(Session session, EndpointConfig config) { session.addMessageHandler(new MsgStringMessageHandler(session)); } } public static class MsgString { private String data; public String getData() { return data; } public void setData(String data) { this.data = data; } } public static class MsgStringEncoder implements Encoder.Text<MsgString> { @Override public void init(EndpointConfig endpointConfig) { Server.addLifeCycleEvent(getClass().getName() + ":init"); } @Override public void destroy() { Server.addLifeCycleEvent(getClass().getName() + ":destroy"); } @Override public String encode(MsgString msg) throws EncodeException { return "MsgString:" + msg.getData(); } } public static class MsgStringDecoder implements Decoder.Text<MsgString> { @Override public void init(EndpointConfig endpointConfig) { Server.addLifeCycleEvent(getClass().getName() + ":init"); } @Override public void destroy() { Server.addLifeCycleEvent(getClass().getName() + ":destroy"); } @Override public MsgString decode(String s) throws DecodeException { MsgString result = new MsgString(); result.setData(s.substring(10)); return result; } @Override public boolean willDecode(String s) { return s.startsWith("MsgString:"); } } public static class MsgByte { private byte[] data; public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } } public static class MsgByteEncoder implements Encoder.Binary<MsgByte> { @Override public void init(EndpointConfig endpointConfig) { Server.addLifeCycleEvent(getClass().getName() + ":init"); } @Override public void destroy() { Server.addLifeCycleEvent(getClass().getName() + ":destroy"); } @Override public ByteBuffer encode(MsgByte msg) throws EncodeException { byte[] data = msg.getData(); ByteBuffer reply = ByteBuffer.allocate(2 + data.length); reply.put((byte) 0x12); reply.put((byte) 0x34); reply.put(data); return reply; } } public static class MsgByteDecoder implements Decoder.Binary<MsgByte> { @Override public void init(EndpointConfig endpointConfig) { Server.addLifeCycleEvent(getClass().getName() + ":init"); } @Override public void destroy() { Server.addLifeCycleEvent(getClass().getName() + ":destroy"); } @Override public MsgByte decode(ByteBuffer bb) throws DecodeException { MsgByte result = new MsgByte(); bb.position(bb.position() + 2); byte[] data = new byte[bb.limit() - bb.position()]; bb.get(data); result.setData(data); return result; } @Override public boolean willDecode(ByteBuffer bb) { bb.mark(); if (bb.get() == 0x12 && bb.get() == 0x34) { return true; } bb.reset(); return false; } } public static class ProgramaticServerEndpointConfig extends WsListener { @Override public void contextInitialized(ServletContextEvent sce) { super.contextInitialized(sce); ServerContainer sc = (ServerContainer) sce.getServletContext().getAttribute( org.apache.tomcat.websocket.server.Constants. SERVER_CONTAINER_SERVLET_CONTEXT_ATTRIBUTE); try { sc.addEndpoint(new ServerEndpointConfig() { @Override public Map<String, Object> getUserProperties() { return Collections.emptyMap(); } @Override public List<Class<? extends Encoder>> getEncoders() { List<Class<? extends Encoder>> encoders = new ArrayList<>(2); encoders.add(MsgStringEncoder.class); encoders.add(MsgByteEncoder.class); return encoders; } @Override public List<Class<? extends Decoder>> getDecoders() { List<Class<? extends Decoder>> decoders = new ArrayList<>(2); decoders.add(MsgStringDecoder.class); decoders.add(MsgByteDecoder.class); return decoders; } @Override public List<String> getSubprotocols() { return Collections.emptyList(); } @Override public String getPath() { return PATH_PROGRAMMATIC_EP; } @Override public List<Extension> getExtensions() { return Collections.emptyList(); } @Override public Class<?> getEndpointClass() { return ProgrammaticEndpoint.class; } @Override public Configurator getConfigurator() { return new ServerEndpointConfig.Configurator() { }; } }); } catch (DeploymentException e) { throw new IllegalStateException(e); } } } }
55,017
Bug 55017 Ability to configure RMI bind address
null
resolved fixed
45f59bb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T09:50:38Z
2013-05-24T18:26:40Z
java/org/apache/catalina/mbeans/JmxRemoteLifecycleListener.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.mbeans; import java.io.IOException; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.net.MalformedURLException; import java.net.Socket; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.RMIClientSocketFactory; import java.rmi.server.RMIServerSocketFactory; import java.util.HashMap; import javax.management.MBeanServer; import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; import javax.management.remote.rmi.RMIConnectorServer; import javax.rmi.ssl.SslRMIClientSocketFactory; import javax.rmi.ssl.SslRMIServerSocketFactory; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * This listener fixes the port used by JMX/RMI Server making things much * simpler if you need to connect jconsole or similar to a remote Tomcat * instance that is running behind a firewall. Only the ports are configured via * the listener. The remainder of the configuration is via the standard system * properties for configuring JMX. */ public class JmxRemoteLifecycleListener implements LifecycleListener { private static final Log log = LogFactory.getLog(JmxRemoteLifecycleListener.class); /** * The string resources for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); protected int rmiRegistryPortPlatform = -1; protected int rmiServerPortPlatform = -1; protected boolean rmiSSL = true; protected String ciphers[] = null; protected String protocols[] = null; protected boolean clientAuth = true; protected boolean authenticate = true; protected String passwordFile = null; protected String loginModuleName = null; protected String accessFile = null; protected boolean useLocalPorts = false; protected JMXConnectorServer csPlatform = null; /** * Get the port on which the Platform RMI server is exported. This is the * port that is normally chosen by the RMI stack. * @return The port number */ public int getRmiServerPortPlatform() { return rmiServerPortPlatform; } /** * Set the port on which the Platform RMI server is exported. This is the * port that is normally chosen by the RMI stack. * @param theRmiServerPortPlatform The port number */ public void setRmiServerPortPlatform(int theRmiServerPortPlatform) { rmiServerPortPlatform = theRmiServerPortPlatform; } /** * Get the port on which the Platform RMI registry is exported. * @return The port number */ public int getRmiRegistryPortPlatform() { return rmiRegistryPortPlatform; } /** * Set the port on which the Platform RMI registry is exported. * @param theRmiRegistryPortPlatform The port number */ public void setRmiRegistryPortPlatform(int theRmiRegistryPortPlatform) { rmiRegistryPortPlatform = theRmiRegistryPortPlatform; } /** * Get the flag that indicates that local ports should be used for all * connections. If using SSH tunnels, or similar, this should be set to * true to ensure the RMI client uses the tunnel. * @return <code>true</code> if local ports should be used */ public boolean getUseLocalPorts() { return useLocalPorts; } /** * Set the flag that indicates that local ports should be used for all * connections. If using SSH tunnels, or similar, this should be set to * true to ensure the RMI client uses the tunnel. * @param useLocalPorts Set to <code>true</code> if local ports should be * used */ public void setUseLocalPorts(boolean useLocalPorts) { this.useLocalPorts = useLocalPorts; } private void init() { // Get all the other parameters required from the standard system // properties. Only need to get the parameters that affect the creation // of the server port. String rmiSSLValue = System.getProperty( "com.sun.management.jmxremote.ssl", "true"); rmiSSL = Boolean.parseBoolean(rmiSSLValue); String protocolsValue = System.getProperty( "com.sun.management.jmxremote.ssl.enabled.protocols"); if (protocolsValue != null) { protocols = protocolsValue.split(","); } String ciphersValue = System.getProperty( "com.sun.management.jmxremote.ssl.enabled.cipher.suites"); if (ciphersValue != null) { ciphers = ciphersValue.split(","); } String clientAuthValue = System.getProperty( "com.sun.management.jmxremote.ssl.need.client.auth", "true"); clientAuth = Boolean.parseBoolean(clientAuthValue); String authenticateValue = System.getProperty( "com.sun.management.jmxremote.authenticate", "true"); authenticate = Boolean.parseBoolean(authenticateValue); passwordFile = System.getProperty( "com.sun.management.jmxremote.password.file", "jmxremote.password"); accessFile = System.getProperty( "com.sun.management.jmxremote.access.file", "jmxremote.access"); loginModuleName = System.getProperty( "com.sun.management.jmxremote.login.config"); } @Override public void lifecycleEvent(LifecycleEvent event) { // When the server starts, configure JMX/RMI if (Lifecycle.START_EVENT == event.getType()) { // Configure using standard jmx system properties init(); // Prevent an attacker guessing the RMI object ID System.setProperty("java.rmi.server.randomIDs", "true"); // Create the environment HashMap<String,Object> env = new HashMap<>(); RMIClientSocketFactory csf = null; RMIServerSocketFactory ssf = null; // Configure SSL for RMI connection if required if (rmiSSL) { csf = new SslRMIClientSocketFactory(); ssf = new SslRMIServerSocketFactory(ciphers, protocols, clientAuth); } // Force the use of local ports if required if (useLocalPorts) { csf = new RmiClientLocalhostSocketFactory(csf); } // Populate the env properties used to create the server if (csf != null) { env.put(RMIConnectorServer.RMI_CLIENT_SOCKET_FACTORY_ATTRIBUTE, csf); } if (ssf != null) { env.put(RMIConnectorServer.RMI_SERVER_SOCKET_FACTORY_ATTRIBUTE, ssf); } // Configure authentication if (authenticate) { env.put("jmx.remote.x.password.file", passwordFile); env.put("jmx.remote.x.access.file", accessFile); env.put("jmx.remote.x.login.config", loginModuleName); } // Create the Platform server csPlatform = createServer("Platform", rmiRegistryPortPlatform, rmiServerPortPlatform, env, ManagementFactory.getPlatformMBeanServer()); } else if (Lifecycle.STOP_EVENT == event.getType()) { destroyServer("Platform", csPlatform); } } private JMXConnectorServer createServer(String serverName, int theRmiRegistryPort, int theRmiServerPort, HashMap<String,Object> theEnv, MBeanServer theMBeanServer) { // Create the RMI registry try { LocateRegistry.createRegistry(theRmiRegistryPort); } catch (RemoteException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createRegistryFailed", serverName, Integer.toString(theRmiRegistryPort)), e); return null; } // Build the connection string with fixed ports StringBuilder url = new StringBuilder(); url.append("service:jmx:rmi://localhost:"); url.append(theRmiServerPort); url.append("/jndi/rmi://localhost:"); url.append(theRmiRegistryPort); url.append("/jmxrmi"); JMXServiceURL serviceUrl; try { serviceUrl = new JMXServiceURL(url.toString()); } catch (MalformedURLException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.invalidURL", serverName, url.toString()), e); return null; } // Start the JMX server with the connection string JMXConnectorServer cs = null; try { cs = JMXConnectorServerFactory.newJMXConnectorServer( serviceUrl, theEnv, theMBeanServer); cs.start(); log.info(sm.getString("jmxRemoteLifecycleListener.start", Integer.toString(theRmiRegistryPort), Integer.toString(theRmiServerPort), serverName)); } catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.createServerFailed", serverName), e); } return cs; } private void destroyServer(String serverName, JMXConnectorServer theConnectorServer) { if (theConnectorServer != null) { try { theConnectorServer.stop(); } catch (IOException e) { log.error(sm.getString( "jmxRemoteLifecycleListener.destroyServerFailed", serverName),e); } } } public static class RmiClientLocalhostSocketFactory implements RMIClientSocketFactory, Serializable { private static final long serialVersionUID = 1L; private static final String FORCED_HOST = "localhost"; private final RMIClientSocketFactory factory; public RmiClientLocalhostSocketFactory(RMIClientSocketFactory theFactory) { factory = theFactory; } @Override public Socket createSocket(String host, int port) throws IOException { if (factory == null) { return new Socket(FORCED_HOST, port); } else { return factory.createSocket(FORCED_HOST, port); } } } }
55,159
Bug 55159 Wasted work in ErrorReportValve.getPartialServletStackTrace
null
resolved fixed
b7cad6b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T11:01:38Z
2013-06-29T23:53:20Z
java/org/apache/catalina/valves/ErrorReportValve.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.valves; import java.io.IOException; import java.io.Writer; import java.util.Scanner; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.util.RequestUtil; import org.apache.catalina.util.ServerInfo; import org.apache.tomcat.util.ExceptionUtils; /** * <p>Implementation of a Valve that outputs HTML error pages.</p> * * <p>This Valve should be attached at the Host level, although it will work * if attached to a Context.</p> * * <p>HTML code from the Cocoon 2 project.</p> * * @author Remy Maucherat * @author Craig R. McClanahan * @author <a href="mailto:nicolaken@supereva.it">Nicola Ken Barozzi</a> Aisa * @author <a href="mailto:stefano@apache.org">Stefano Mazzocchi</a> * @author Yoav Shapira * @version $Id$ */ public class ErrorReportValve extends ValveBase { //------------------------------------------------------ Constructor public ErrorReportValve() { super(true); } // --------------------------------------------------------- Public Methods /** * Invoke the next Valve in the sequence. When the invoke returns, check * the response state, and output an error report is necessary. * * @param request The servlet request to be processed * @param response The servlet response to be created * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet error occurs */ @Override public void invoke(Request request, Response response) throws IOException, ServletException { // Perform the request getNext().invoke(request, response); if (response.isCommitted()) { return; } Throwable throwable = (Throwable) request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); if (request.isAsyncStarted() && response.getStatus() < 400 && throwable == null) { return; } if (throwable != null) { // The response is an error response.setError(); // Reset the response (if possible) try { response.reset(); } catch (IllegalStateException e) { // Ignore } response.sendError (HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } response.setSuspended(false); try { report(request, response, throwable); } catch (Throwable tt) { ExceptionUtils.handleThrowable(tt); } if (request.isAsyncStarted()) { request.getAsyncContext().complete(); } } // ------------------------------------------------------ Protected Methods /** * Prints out an error report. * * @param request The request being processed * @param response The response being generated * @param throwable The exception that occurred (which possibly wraps * a root cause exception */ protected void report(Request request, Response response, Throwable throwable) { // Do nothing on non-HTTP responses int statusCode = response.getStatus(); // Do nothing on a 1xx, 2xx and 3xx status // Do nothing if anything has been written already if (statusCode < 400 || response.getContentWritten() > 0 || !response.isError()) { return; } String message = RequestUtil.filter(response.getMessage()); if (message == null) { if (throwable != null) { String exceptionMessage = throwable.getMessage(); if (exceptionMessage != null && exceptionMessage.length() > 0) { message = RequestUtil.filter( (new Scanner(exceptionMessage)).nextLine()); } } if (message == null) { message = ""; } } // Do nothing if there is no report for the specified status code and // no error message provided String report = null; try { report = sm.getString("http." + statusCode); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } if (report == null) { if (message.length() == 0) { return; } else { report = sm.getString("errorReportValve.noDescription"); } } StringBuilder sb = new StringBuilder(); sb.append("<html><head><title>"); sb.append(ServerInfo.getServerInfo()).append(" - "); sb.append(sm.getString("errorReportValve.errorReport")); sb.append("</title>"); sb.append("<style><!--"); sb.append(org.apache.catalina.util.TomcatCSS.TOMCAT_CSS); sb.append("--></style> "); sb.append("</head><body>"); sb.append("<h1>"); sb.append(sm.getString("errorReportValve.statusHeader", "" + statusCode, message)).append("</h1>"); sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<p><b>type</b> "); if (throwable != null) { sb.append(sm.getString("errorReportValve.exceptionReport")); } else { sb.append(sm.getString("errorReportValve.statusReport")); } sb.append("</p>"); sb.append("<p><b>"); sb.append(sm.getString("errorReportValve.message")); sb.append("</b> <u>"); sb.append(message).append("</u></p>"); sb.append("<p><b>"); sb.append(sm.getString("errorReportValve.description")); sb.append("</b> <u>"); sb.append(report); sb.append("</u></p>"); if (throwable != null) { String stackTrace = getPartialServletStackTrace(throwable); sb.append("<p><b>"); sb.append(sm.getString("errorReportValve.exception")); sb.append("</b> <pre>"); sb.append(RequestUtil.filter(stackTrace)); sb.append("</pre></p>"); int loops = 0; Throwable rootCause = throwable.getCause(); while (rootCause != null && (loops < 10)) { stackTrace = getPartialServletStackTrace(rootCause); sb.append("<p><b>"); sb.append(sm.getString("errorReportValve.rootCause")); sb.append("</b> <pre>"); sb.append(RequestUtil.filter(stackTrace)); sb.append("</pre></p>"); // In case root cause is somehow heavily nested rootCause = rootCause.getCause(); loops++; } sb.append("<p><b>"); sb.append(sm.getString("errorReportValve.note")); sb.append("</b> <u>"); sb.append(sm.getString("errorReportValve.rootCauseInLogs", ServerInfo.getServerInfo())); sb.append("</u></p>"); } sb.append("<HR size=\"1\" noshade=\"noshade\">"); sb.append("<h3>").append(ServerInfo.getServerInfo()).append("</h3>"); sb.append("</body></html>"); try { try { response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (container.getLogger().isDebugEnabled()) { container.getLogger().debug("status.setContentType", t); } } Writer writer = response.getReporter(); if (writer != null) { // If writer is null, it's an indication that the response has // been hard committed already, which should never happen writer.write(sb.toString()); } } catch (IOException e) { // Ignore } catch (IllegalStateException e) { // Ignore } } /** * Print out a partial servlet stack trace (truncating at the last * occurrence of javax.servlet.). */ protected String getPartialServletStackTrace(Throwable t) { StringBuilder trace = new StringBuilder(); trace.append(t.toString()).append('\n'); StackTraceElement[] elements = t.getStackTrace(); int pos = elements.length; for (int i = 0; i < elements.length; i++) { if ((elements[i].getClassName().startsWith ("org.apache.catalina.core.ApplicationFilterChain")) && (elements[i].getMethodName().equals("internalDoFilter"))) { pos = i; } } for (int i = 0; i < pos; i++) { if (!(elements[i].getClassName().startsWith ("org.apache.catalina.core."))) { trace.append('\t').append(elements[i].toString()).append('\n'); } } return trace.toString(); } }
55,158
Bug 55158 Wasted work in AttributeNamesEnumerator constructor
null
resolved fixed
ca956bd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T12:26:02Z
2013-06-29T23:53:20Z
java/org/apache/catalina/core/ApplicationHttpRequest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpSession; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Manager; import org.apache.catalina.Session; import org.apache.catalina.util.RequestUtil; /** * Wrapper around a <code>javax.servlet.http.HttpServletRequest</code> * that transforms an application request object (which might be the original * one passed to a servlet, or might be based on the 2.3 * <code>javax.servlet.http.HttpServletRequestWrapper</code> class) * back into an internal <code>org.apache.catalina.HttpRequest</code>. * <p> * <strong>WARNING</strong>: Due to Java's lack of support for multiple * inheritance, all of the logic in <code>ApplicationRequest</code> is * duplicated in <code>ApplicationHttpRequest</code>. Make sure that you * keep these two classes in synchronization when making changes! * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ class ApplicationHttpRequest extends HttpServletRequestWrapper { // ------------------------------------------------------- Static Variables /** * The set of attribute names that are special for request dispatchers. */ protected static final String specials[] = { RequestDispatcher.INCLUDE_REQUEST_URI, RequestDispatcher.INCLUDE_CONTEXT_PATH, RequestDispatcher.INCLUDE_SERVLET_PATH, RequestDispatcher.INCLUDE_PATH_INFO, RequestDispatcher.INCLUDE_QUERY_STRING, RequestDispatcher.FORWARD_REQUEST_URI, RequestDispatcher.FORWARD_CONTEXT_PATH, RequestDispatcher.FORWARD_SERVLET_PATH, RequestDispatcher.FORWARD_PATH_INFO, RequestDispatcher.FORWARD_QUERY_STRING }; // ----------------------------------------------------------- Constructors /** * Construct a new wrapped request around the specified servlet request. * * @param request The servlet request being wrapped */ public ApplicationHttpRequest(HttpServletRequest request, Context context, boolean crossContext) { super(request); this.context = context; this.crossContext = crossContext; setRequest(request); } // ----------------------------------------------------- Instance Variables /** * The context for this request. */ protected final Context context; /** * The context path for this request. */ protected String contextPath = null; /** * If this request is cross context, since this changes session access * behavior. */ protected final boolean crossContext; /** * The current dispatcher type. */ protected DispatcherType dispatcherType = null; /** * The request parameters for this request. This is initialized from the * wrapped request, but updates are allowed. */ protected Map<String, String[]> parameters = null; /** * Have the parameters for this request already been parsed? */ private boolean parsedParams = false; /** * The path information for this request. */ protected String pathInfo = null; /** * The query parameters for the current request. */ private String queryParamString = null; /** * The query string for this request. */ protected String queryString = null; /** * The current request dispatcher path. */ protected Object requestDispatcherPath = null; /** * The request URI for this request. */ protected String requestURI = null; /** * The servlet path for this request. */ protected String servletPath = null; /** * The currently active session for this request. */ protected Session session = null; /** * Special attributes. */ protected final Object[] specialAttributes = new Object[specials.length]; // ------------------------------------------------- ServletRequest Methods /** * Override the <code>getAttribute()</code> method of the wrapped request. * * @param name Name of the attribute to retrieve */ @Override public Object getAttribute(String name) { if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) { return dispatcherType; } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { if ( requestDispatcherPath != null ){ return requestDispatcherPath.toString(); } else { return null; } } int pos = getSpecial(name); if (pos == -1) { return getRequest().getAttribute(name); } else { if ((specialAttributes[pos] == null) && (specialAttributes[5] == null) && (pos >= 5)) { // If it's a forward special attribute, and null, it means this // is an include, so we check the wrapped request since // the request could have been forwarded before the include return getRequest().getAttribute(name); } else { return specialAttributes[pos]; } } } /** * Override the <code>getAttributeNames()</code> method of the wrapped * request. */ @Override public Enumeration<String> getAttributeNames() { return (new AttributeNamesEnumerator()); } /** * Override the <code>removeAttribute()</code> method of the * wrapped request. * * @param name Name of the attribute to remove */ @Override public void removeAttribute(String name) { if (!removeSpecial(name)) getRequest().removeAttribute(name); } /** * Override the <code>setAttribute()</code> method of the * wrapped request. * * @param name Name of the attribute to set * @param value Value of the attribute to set */ @Override public void setAttribute(String name, Object value) { if (name.equals(Globals.DISPATCHER_TYPE_ATTR)) { dispatcherType = (DispatcherType)value; return; } else if (name.equals(Globals.DISPATCHER_REQUEST_PATH_ATTR)) { requestDispatcherPath = value; return; } if (!setSpecial(name, value)) { getRequest().setAttribute(name, value); } } /** * Return a RequestDispatcher that wraps the resource at the specified * path, which may be interpreted as relative to the current request path. * * @param path Path of the resource to be wrapped */ @Override public RequestDispatcher getRequestDispatcher(String path) { if (context == null) return (null); // If the path is already context-relative, just pass it through if (path == null) return (null); else if (path.startsWith("/")) return (context.getServletContext().getRequestDispatcher(path)); // Convert a request-relative path to a context-relative one String servletPath = (String) getAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); if (servletPath == null) servletPath = getServletPath(); // Add the path info, if there is any String pathInfo = getPathInfo(); String requestPath = null; if (pathInfo == null) { requestPath = servletPath; } else { requestPath = servletPath + pathInfo; } int pos = requestPath.lastIndexOf('/'); String relative = null; if (pos >= 0) { relative = requestPath.substring(0, pos + 1) + path; } else { relative = requestPath + path; } return (context.getServletContext().getRequestDispatcher(relative)); } /** * Override the getDispatcherType() method of the wrapped request. * */ @Override public DispatcherType getDispatcherType() { return dispatcherType; } // --------------------------------------------- HttpServletRequest Methods /** * Override the <code>getContextPath()</code> method of the wrapped * request. */ @Override public String getContextPath() { return (this.contextPath); } /** * Override the <code>getParameter()</code> method of the wrapped request. * * @param name Name of the requested parameter */ @Override public String getParameter(String name) { parseParameters(); Object value = parameters.get(name); if (value == null) return (null); else if (value instanceof String[]) return (((String[]) value)[0]); else if (value instanceof String) return ((String) value); else return (value.toString()); } /** * Override the <code>getParameterMap()</code> method of the * wrapped request. */ @Override public Map<String, String[]> getParameterMap() { parseParameters(); return (parameters); } /** * Override the <code>getParameterNames()</code> method of the * wrapped request. */ @Override public Enumeration<String> getParameterNames() { parseParameters(); return Collections.enumeration(parameters.keySet()); } /** * Override the <code>getParameterValues()</code> method of the * wrapped request. * * @param name Name of the requested parameter */ @Override public String[] getParameterValues(String name) { parseParameters(); Object value = parameters.get(name); if (value == null) return null; else if (value instanceof String[]) return ((String[]) value); else if (value instanceof String) { String values[] = new String[1]; values[0] = (String) value; return (values); } else { String values[] = new String[1]; values[0] = value.toString(); return (values); } } /** * Override the <code>getPathInfo()</code> method of the wrapped request. */ @Override public String getPathInfo() { return (this.pathInfo); } /** * Override the <code>getQueryString()</code> method of the wrapped * request. */ @Override public String getQueryString() { return (this.queryString); } /** * Override the <code>getRequestURI()</code> method of the wrapped * request. */ @Override public String getRequestURI() { return (this.requestURI); } /** * Override the <code>getRequestURL()</code> method of the wrapped * request. */ @Override public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); String scheme = getScheme(); int port = getServerPort(); if (port < 0) port = 80; // Work around java.net.URL bug url.append(scheme); url.append("://"); url.append(getServerName()); if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) { url.append(':'); url.append(port); } url.append(getRequestURI()); return (url); } /** * Override the <code>getServletPath()</code> method of the wrapped * request. */ @Override public String getServletPath() { return (this.servletPath); } /** * Return the session associated with this Request, creating one * if necessary. */ @Override public HttpSession getSession() { return (getSession(true)); } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ @Override public HttpSession getSession(boolean create) { if (crossContext) { // There cannot be a session if no context has been assigned yet if (context == null) return (null); // Return the current session if it exists and is valid if (session != null && session.isValid()) { return (session.getSession()); } HttpSession other = super.getSession(false); if (create && (other == null)) { // First create a session in the first context: the problem is // that the top level request is the only one which can // create the cookie safely other = super.getSession(true); } if (other != null) { Session localSession = null; try { localSession = context.getManager().findSession(other.getId()); if (localSession != null && !localSession.isValid()) { localSession = null; } } catch (IOException e) { // Ignore } if (localSession == null && create) { localSession = context.getManager().createSession(other.getId()); } if (localSession != null) { localSession.access(); session = localSession; return session.getSession(); } } return null; } else { return super.getSession(create); } } /** * Returns true if the request specifies a JSESSIONID that is valid within * the context of this ApplicationHttpRequest, false otherwise. * * @return true if the request specifies a JSESSIONID that is valid within * the context of this ApplicationHttpRequest, false otherwise. */ @Override public boolean isRequestedSessionIdValid() { if (crossContext) { String requestedSessionId = getRequestedSessionId(); if (requestedSessionId == null) return (false); if (context == null) return (false); Manager manager = context.getManager(); if (manager == null) return (false); Session session = null; try { session = manager.findSession(requestedSessionId); } catch (IOException e) { // Ignore } if ((session != null) && session.isValid()) { return (true); } else { return (false); } } else { return super.isRequestedSessionIdValid(); } } // -------------------------------------------------------- Package Methods /** * Recycle this request */ public void recycle() { if (session != null) { session.endAccess(); } } /** * Perform a shallow copy of the specified Map, and return the result. * * @param orig Origin Map to be copied */ Map<String, String[]> copyMap(Map<String, String[]> orig) { if (orig == null) { return (new HashMap<>()); } HashMap<String, String[]> dest = new HashMap<>(); for (Map.Entry<String, String[]> entry : orig.entrySet()) { dest.put(entry.getKey(), entry.getValue()); } return (dest); } /** * Set the context path for this request. * * @param contextPath The new context path */ void setContextPath(String contextPath) { this.contextPath = contextPath; } /** * Set the path information for this request. * * @param pathInfo The new path info */ void setPathInfo(String pathInfo) { this.pathInfo = pathInfo; } /** * Set the query string for this request. * * @param queryString The new query string */ void setQueryString(String queryString) { this.queryString = queryString; } /** * Set the request that we are wrapping. * * @param request The new wrapped request */ void setRequest(HttpServletRequest request) { super.setRequest(request); // Initialize the attributes for this request dispatcherType = (DispatcherType)request.getAttribute(Globals.DISPATCHER_TYPE_ATTR); requestDispatcherPath = request.getAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR); // Initialize the path elements for this request contextPath = request.getContextPath(); pathInfo = request.getPathInfo(); queryString = request.getQueryString(); requestURI = request.getRequestURI(); servletPath = request.getServletPath(); } /** * Set the request URI for this request. * * @param requestURI The new request URI */ void setRequestURI(String requestURI) { this.requestURI = requestURI; } /** * Set the servlet path for this request. * * @param servletPath The new servlet path */ void setServletPath(String servletPath) { this.servletPath = servletPath; } /** * Parses the parameters of this request. * * If parameters are present in both the query string and the request * content, they are merged. */ void parseParameters() { if (parsedParams) { return; } parameters = new HashMap<>(); parameters = copyMap(getRequest().getParameterMap()); mergeParameters(); parsedParams = true; } /** * Save query parameters for this request. * * @param queryString The query string containing parameters for this * request */ void setQueryParams(String queryString) { this.queryParamString = queryString; } // ------------------------------------------------------ Protected Methods /** * Is this attribute name one of the special ones that is added only for * included servlets? * * @param name Attribute name to be tested */ protected boolean isSpecial(String name) { for (int i = 0; i < specials.length; i++) { if (specials[i].equals(name)) return (true); } return (false); } /** * Get a special attribute. * * @return the special attribute pos, or -1 if it is not a special * attribute */ protected int getSpecial(String name) { for (int i = 0; i < specials.length; i++) { if (specials[i].equals(name)) { return (i); } } return (-1); } /** * Set a special attribute. * * @return true if the attribute was a special attribute, false otherwise */ protected boolean setSpecial(String name, Object value) { for (int i = 0; i < specials.length; i++) { if (specials[i].equals(name)) { specialAttributes[i] = value; return (true); } } return (false); } /** * Remove a special attribute. * * @return true if the attribute was a special attribute, false otherwise */ protected boolean removeSpecial(String name) { for (int i = 0; i < specials.length; i++) { if (specials[i].equals(name)) { specialAttributes[i] = null; return (true); } } return (false); } /** * Merge the two sets of parameter values into a single String array. * * @param values1 First set of values * @param values2 Second set of values */ protected String[] mergeValues(Object values1, Object values2) { ArrayList<Object> results = new ArrayList<>(); if (values1 == null) { // Skip - nothing to merge } else if (values1 instanceof String) results.add(values1); else if (values1 instanceof String[]) { String values[] = (String[]) values1; for (int i = 0; i < values.length; i++) results.add(values[i]); } else results.add(values1.toString()); if (values2 == null) { // Skip - nothing to merge } else if (values2 instanceof String) results.add(values2); else if (values2 instanceof String[]) { String values[] = (String[]) values2; for (int i = 0; i < values.length; i++) results.add(values[i]); } else results.add(values2.toString()); String values[] = new String[results.size()]; return results.toArray(values); } // ------------------------------------------------------ Private Methods /** * Merge the parameters from the saved query parameter string (if any), and * the parameters already present on this request (if any), such that the * parameter values from the query string show up first if there are * duplicate parameter names. */ private void mergeParameters() { if ((queryParamString == null) || (queryParamString.length() < 1)) return; HashMap<String, String[]> queryParameters = new HashMap<>(); String encoding = getCharacterEncoding(); if (encoding == null) encoding = "ISO-8859-1"; RequestUtil.parseParameters(queryParameters, queryParamString, encoding); Iterator<String> keys = parameters.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); Object value = queryParameters.get(key); if (value == null) { queryParameters.put(key, parameters.get(key)); continue; } queryParameters.put (key, mergeValues(value, parameters.get(key))); } parameters = queryParameters; } // ----------------------------------- AttributeNamesEnumerator Inner Class /** * Utility class used to expose the special attributes as being available * as request attributes. */ protected class AttributeNamesEnumerator implements Enumeration<String> { protected int pos = -1; protected final int last; protected final Enumeration<String> parentEnumeration; protected String next = null; public AttributeNamesEnumerator() { int last = -1; parentEnumeration = getRequest().getAttributeNames(); for (int i = 0; i < specialAttributes.length; i++) { if (getAttribute(specials[i]) != null) { last = i; } } this.last = last; } @Override public boolean hasMoreElements() { return ((pos != last) || (next != null) || ((next = findNext()) != null)); } @Override public String nextElement() { if (pos != last) { for (int i = pos + 1; i <= last; i++) { if (getAttribute(specials[i]) != null) { pos = i; return (specials[i]); } } } String result = next; if (next != null) { next = findNext(); } else { throw new NoSuchElementException(); } return result; } protected String findNext() { String result = null; while ((result == null) && (parentEnumeration.hasMoreElements())) { String current = parentEnumeration.nextElement(); if (!isSpecial(current)) { result = current; } } return result; } } }
55,160
Bug 55160 NIO connectionUploadTimeout can't work
when i configure disableUploadTimeout="false" and connectionTimeout="20000" ,connectionUploadTimeout="30000" . I found the connectionUploadTimeout doesn't work, because the code in internalNioInputBuffer.readSocket(): ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ att.getTimeout() is the connectionTimeout ,not the connectionUploadTimeout. so , in NioBlockingSelector.read(), the readTimeout is connectionTimeout
resolved fixed
9a01f2d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T14:26:13Z
2013-06-30T02:40:00Z
java/org/apache/coyote/http11/InternalNioInputBuffer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.EOFException; import java.io.IOException; import java.nio.channels.Selector; import java.nio.charset.Charset; import org.apache.coyote.InputBuffer; import org.apache.coyote.Request; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.NioChannel; import org.apache.tomcat.util.net.NioEndpoint; import org.apache.tomcat.util.net.NioSelectorPool; import org.apache.tomcat.util.net.SocketWrapper; /** * Implementation of InputBuffer which provides HTTP request header parsing as * well as transfer decoding. * * @author <a href="mailto:remm@apache.org">Remy Maucherat</a> * @author Filip Hanik */ public class InternalNioInputBuffer extends AbstractInputBuffer<NioChannel> { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(InternalNioInputBuffer.class); private static final Charset DEFAULT_CHARSET = Charset.forName("ISO-8859-1"); // -------------------------------------------------------------- Constants enum HeaderParseStatus { DONE, HAVE_MORE_HEADERS, NEED_MORE_DATA } enum HeaderParsePosition { /** * 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. */ 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. */ 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. */ 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). */ HEADER_MULTI_LINE, /** * Reading all bytes until the next CRLF. The line is being ignored. */ HEADER_SKIPLINE } // ----------------------------------------------------------- Constructors /** * Alternate constructor. */ public InternalNioInputBuffer(Request request, int headerBufferSize) { this.request = request; headers = request.getMimeHeaders(); this.headerBufferSize = headerBufferSize; inputStreamInputBuffer = new SocketInputBuffer(); filterLibrary = new InputFilter[0]; activeFilters = new InputFilter[0]; lastActiveFilter = -1; parsingHeader = true; parsingRequestLine = true; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; parsingRequestLineQPos = -1; headerParsePos = HeaderParsePosition.HEADER_START; headerData.recycle(); swallowInput = true; } /** * Parsing state - used for non blocking parsing so that * when more data arrives, we can pick up where we left off. */ private boolean parsingRequestLine; private int parsingRequestLinePhase = 0; private boolean parsingRequestLineEol = false; private int parsingRequestLineStart = 0; private int parsingRequestLineQPos = -1; private HeaderParsePosition headerParsePos; /** * Underlying socket. */ private NioChannel socket; /** * Selector pool, for blocking reads and blocking writes */ private NioSelectorPool pool; /** * Maximum allowed size of the HTTP request line plus headers plus any * leading blank lines. */ private final int headerBufferSize; /** * Known size of the NioChannel read buffer. */ private int socketReadBufferSize; // --------------------------------------------------------- Public Methods @Override public int available() { int available = super.available(); if (available>0) { return available; } available = Math.max(lastValid - pos, 0); if (available>0) { return available; } try { available = nbRead(); }catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug(sm.getString("iib.available.readFail"), ioe); } // Not ideal. This will indicate that data is available which should // trigger a read which in turn will trigger another IOException and // that one can be thrown. available = 1; } return available; } @Override public int nbRead() throws IOException { return readSocket(true,false); } /** * Recycle the input buffer. This should be called when closing the * connection. */ @Override public void recycle() { super.recycle(); socket = null; headerParsePos = HeaderParsePosition.HEADER_START; parsingRequestLine = true; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; parsingRequestLineQPos = -1; headerData.recycle(); } /** * 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. */ @Override public void nextRequest() { super.nextRequest(); headerParsePos = HeaderParsePosition.HEADER_START; parsingRequestLine = true; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; parsingRequestLineQPos = -1; headerData.recycle(); } /** * 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. * @return true if data is properly fed; false if no data is available * immediately and thread should be freed */ @Override public boolean parseRequestLine(boolean useAvailableDataOnly) throws IOException { //check state if ( !parsingRequestLine ) return true; // // Skipping blank lines // if ( parsingRequestLinePhase == 0 ) { byte chr = 0; do { // Read new bytes if needed if (pos >= lastValid) { if (useAvailableDataOnly) { return false; } // Do a simple read with a short timeout if (!fill(true, false)) { return false; } } chr = buf[pos++]; } while ((chr == Constants.CR) || (chr == Constants.LF)); pos--; parsingRequestLineStart = pos; parsingRequestLinePhase = 2; if (log.isDebugEnabled()) { log.debug("Received [" + new String(buf, pos, lastValid - pos, DEFAULT_CHARSET) + "]"); } } if ( parsingRequestLinePhase == 2 ) { // // Reading the method name // Method name is always US-ASCII // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } // Spec says no CR or LF in method name if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { throw new IllegalArgumentException( sm.getString("iib.invalidmethod")); } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; request.method().setBytes(buf, parsingRequestLineStart, pos - parsingRequestLineStart); } pos++; } parsingRequestLinePhase = 3; } if ( parsingRequestLinePhase == 3 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 4; } if (parsingRequestLinePhase == 4) { // Mark the current buffer position int end = 0; // // Reading the URI // boolean space = false; while (!space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { space = true; end = pos; } else if ((buf[pos] == Constants.CR) || (buf[pos] == Constants.LF)) { // HTTP/0.9 style request parsingRequestLineEol = true; space = true; end = pos; } else if ((buf[pos] == Constants.QUESTION) && (parsingRequestLineQPos == -1)) { parsingRequestLineQPos = pos; } pos++; } request.unparsedURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); if (parsingRequestLineQPos >= 0) { request.queryString().setBytes(buf, parsingRequestLineQPos + 1, end - parsingRequestLineQPos - 1); request.requestURI().setBytes(buf, parsingRequestLineStart, parsingRequestLineQPos - parsingRequestLineStart); } else { request.requestURI().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } parsingRequestLinePhase = 5; } if ( parsingRequestLinePhase == 5 ) { // Spec says single SP but also be tolerant of multiple and/or HT boolean space = true; while (space) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.SP || buf[pos] == Constants.HT) { pos++; } else { space = false; } } parsingRequestLineStart = pos; parsingRequestLinePhase = 6; // Mark the current buffer position end = 0; } if (parsingRequestLinePhase == 6) { // // Reading the protocol // Protocol is always US-ASCII // while (!parsingRequestLineEol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true, false)) //request line parsing return false; } if (buf[pos] == Constants.CR) { end = pos; } else if (buf[pos] == Constants.LF) { if (end == 0) end = pos; parsingRequestLineEol = true; } pos++; } if ( (end - parsingRequestLineStart) > 0) { request.protocol().setBytes(buf, parsingRequestLineStart, end - parsingRequestLineStart); } else { request.protocol().setString(""); } parsingRequestLine = false; parsingRequestLinePhase = 0; parsingRequestLineEol = false; parsingRequestLineStart = 0; return true; } throw new IllegalStateException("Invalid request line parse phase:"+parsingRequestLinePhase); } private void expand(int newsize) { if ( newsize > buf.length ) { if (parsingHeader) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } // Should not happen log.warn("Expanding buffer size. Old size: " + buf.length + ", new size: " + newsize, new Exception()); byte[] tmp = new byte[newsize]; System.arraycopy(buf,0,tmp,0,buf.length); buf = tmp; } } /** * Perform blocking read with a timeout if desired * @param timeout boolean - if we want to use the timeout data * @param block - true if the system should perform a blocking read, false otherwise * @return boolean - true if data was read, false is no data read, EOFException if EOF is reached * @throws IOException if a socket exception occurs * @throws EOFException if end of stream is reached */ private int readSocket(boolean timeout, boolean block) throws IOException { int nRead = 0; socket.getBufHandler().getReadBuffer().clear(); if ( block ) { Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { // Ignore } try { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment)socket.getAttachment(false); if ( att == null ) throw new IOException("Key must be cancelled."); nRead = pool.read(socket.getBufHandler().getReadBuffer(),socket,selector,att.getTimeout()); } catch ( EOFException eof ) { nRead = -1; } finally { if ( selector != null ) pool.put(selector); } } else { nRead = socket.read(socket.getBufHandler().getReadBuffer()); } if (nRead > 0) { socket.getBufHandler().getReadBuffer().flip(); socket.getBufHandler().getReadBuffer().limit(nRead); expand(nRead + pos); socket.getBufHandler().getReadBuffer().get(buf, pos, nRead); lastValid = pos + nRead; return nRead; } else if (nRead == -1) { //return false; throw new EOFException(sm.getString("iib.eof.error")); } else { return 0; } } /** * Parse the HTTP headers. */ @Override public boolean parseHeaders() throws IOException { if (!parsingHeader) { throw new IllegalStateException( sm.getString("iib.parseheaders.ise.error")); } HeaderParseStatus status = HeaderParseStatus.HAVE_MORE_HEADERS; do { status = parseHeader(); // Checking that // (1) Headers plus request line size does not exceed its limit // (2) There are enough bytes to avoid expanding the buffer when // reading body // Technically, (2) is technical limitation, (1) is logical // 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 (pos > headerBufferSize || buf.length - pos < socketReadBufferSize) { throw new IllegalArgumentException( sm.getString("iib.requestheadertoolarge.error")); } } while ( status == HeaderParseStatus.HAVE_MORE_HEADERS ); if (status == HeaderParseStatus.DONE) { parsingHeader = false; end = pos; return true; } else { return false; } } /** * Parse an HTTP header. * * @return false after reading a blank line (which indicates that the * HTTP header parsing is done */ private HeaderParseStatus parseHeader() throws IOException { // // Check for blank line // byte chr = 0; while (headerParsePos == HeaderParsePosition.HEADER_START) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { pos++; return HeaderParseStatus.DONE; } else { break; } pos++; } if ( headerParsePos == HeaderParsePosition.HEADER_START ) { // Mark the current buffer position headerData.start = pos; headerParsePos = HeaderParsePosition.HEADER_NAME; } // // Reading the header name // Header name is always US-ASCII // while (headerParsePos == HeaderParsePosition.HEADER_NAME) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { //parse header return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.COLON) { headerParsePos = HeaderParsePosition.HEADER_VALUE_START; headerData.headerValue = headers.addValue(buf, headerData.start, pos - headerData.start); pos++; // Mark the current buffer position headerData.start = pos; headerData.realPos = pos; headerData.lastSignificantChar = pos; break; } else if (!HTTP_TOKEN_CHAR[chr]) { // If a non-token header is detected, skip the line and // ignore the header headerData.lastSignificantChar = pos; return skipLine(); } // chr is next byte of header name. Convert to lowercase. if ((chr >= Constants.A) && (chr <= Constants.Z)) { buf[pos] = (byte) (chr - Constants.LC_OFFSET); } pos++; } // Skip the line and ignore the header if (headerParsePos == HeaderParsePosition.HEADER_SKIPLINE) { return skipLine(); } // // Reading the header value (which can be spanned over multiple lines) // while (headerParsePos == HeaderParsePosition.HEADER_VALUE_START || headerParsePos == HeaderParsePosition.HEADER_VALUE || headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE) { if ( headerParsePos == HeaderParsePosition.HEADER_VALUE_START ) { // Skipping spaces while (true) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE_START return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.SP || chr == Constants.HT) { pos++; } else { headerParsePos = HeaderParsePosition.HEADER_VALUE; break; } } } if ( headerParsePos == HeaderParsePosition.HEADER_VALUE ) { // Reading bytes until the end of the line boolean eol = false; while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_VALUE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if (chr == Constants.CR) { // Skip } else if (chr == Constants.LF) { eol = true; } else if (chr == Constants.SP || chr == Constants.HT) { buf[headerData.realPos] = chr; headerData.realPos++; } else { buf[headerData.realPos] = chr; headerData.realPos++; headerData.lastSignificantChar = headerData.realPos; } pos++; } // Ignore whitespaces at the end of the line headerData.realPos = headerData.lastSignificantChar; // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header headerParsePos = HeaderParsePosition.HEADER_MULTI_LINE; } // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) {//parse header //HEADER_MULTI_LINE return HeaderParseStatus.NEED_MORE_DATA; } } chr = buf[pos]; if ( headerParsePos == HeaderParsePosition.HEADER_MULTI_LINE ) { if ( (chr != Constants.SP) && (chr != Constants.HT)) { headerParsePos = HeaderParsePosition.HEADER_START; break; } else { // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) buf[headerData.realPos] = chr; headerData.realPos++; headerParsePos = HeaderParsePosition.HEADER_VALUE_START; } } } // Set the header value headerData.headerValue.setBytes(buf, headerData.start, headerData.lastSignificantChar - headerData.start); headerData.recycle(); return HeaderParseStatus.HAVE_MORE_HEADERS; } public int getParsingRequestLinePhase() { return parsingRequestLinePhase; } private HeaderParseStatus skipLine() throws IOException { headerParsePos = HeaderParsePosition.HEADER_SKIPLINE; boolean eol = false; // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (!fill(true,false)) { return HeaderParseStatus.NEED_MORE_DATA; } } if (buf[pos] == Constants.CR) { // Skip } else if (buf[pos] == Constants.LF) { eol = true; } else { headerData.lastSignificantChar = pos; } pos++; } if (log.isDebugEnabled()) { log.debug(sm.getString("iib.invalidheader", new String(buf, headerData.start, headerData.lastSignificantChar - headerData.start + 1, DEFAULT_CHARSET))); } headerParsePos = HeaderParsePosition.HEADER_START; return HeaderParseStatus.HAVE_MORE_HEADERS; } private final HeaderParseData headerData = new HeaderParseData(); public static class HeaderParseData { /** * When parsing header name: first character of the header.<br /> * When skipping broken header line: first character of the header.<br /> * When parsing header value: first character after ':'. */ int start = 0; /** * 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 /> */ int realPos = 0; /** * When parsing header name: not used (stays as 0).<br /> * When skipping broken header line: last non-CR/non-LF character.<br /> * When parsing header value: position after the last not-LWS character.<br /> */ 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. */ MessageBytes headerValue = null; public void recycle() { start = 0; realPos = 0; lastSignificantChar = 0; headerValue = null; } } // ------------------------------------------------------ Protected Methods @Override protected void init(SocketWrapper<NioChannel> socketWrapper, AbstractEndpoint endpoint) throws IOException { socket = socketWrapper.getSocket(); if (socket == null) { // Socket has been closed in another thread throw new IOException(sm.getString("iib.socketClosed")); } socketReadBufferSize = socket.getBufHandler().getReadBuffer().capacity(); int bufLength = headerBufferSize + socketReadBufferSize; if (buf == null || buf.length < bufLength) { buf = new byte[bufLength]; } pool = ((NioEndpoint)endpoint).getSelectorPool(); } @Override protected boolean fill(boolean block) throws IOException, EOFException { return fill(true,block); } protected boolean fill(boolean timeout, boolean block) throws IOException, EOFException { boolean read = false; if (parsingHeader) { if (lastValid > headerBufferSize) { throw new IllegalArgumentException (sm.getString("iib.requestheadertoolarge.error")); } // Do a simple read with a short timeout read = readSocket(timeout,block)>0; } else { lastValid = pos = end; // Do a simple read with a short timeout read = readSocket(timeout, block)>0; } return read; } // ------------------------------------- InputStreamInputBuffer Inner Class /** * This class is an input buffer which will read its data from an input * stream. */ protected class SocketInputBuffer implements InputBuffer { /** * Read bytes into the specified chunk. */ @Override public int doRead(ByteChunk chunk, Request req ) throws IOException { if (pos >= lastValid) { if (!fill(true,true)) //read body, must be blocking, as the thread is inside the app return -1; } int length = lastValid - pos; chunk.setBytes(buf, pos, length); pos = lastValid; return (length); } } }
53,777
Bug 53777 Ability to bundle JAAS Configuration in Webappp
null
resolved fixed
6871d4c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T14:57:05Z
2012-08-24T17:40:00Z
java/org/apache/catalina/realm/JAASRealm.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.realm; import java.security.Principal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.AccountExpiredException; import javax.security.auth.login.CredentialExpiredException; import javax.security.auth.login.FailedLoginException; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletRequest; import org.apache.catalina.Container; import org.apache.catalina.LifecycleException; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; /** * <p>Implementation of <b>Realm</b> that authenticates users via the <em>Java * Authentication and Authorization Service</em> (JAAS). JAAS support requires * either JDK 1.4 (which includes it as part of the standard platform) or * JDK 1.3 (with the plug-in <code>jaas.jar</code> file).</p> * * <p>The value configured for the <code>appName</code> property is passed to * the <code>javax.security.auth.login.LoginContext</code> constructor, to * specify the <em>application name</em> used to select the set of relevant * <code>LoginModules</code> required.</p> * * <p>The JAAS Specification describes the result of a successful login as a * <code>javax.security.auth.Subject</code> instance, which can contain zero * or more <code>java.security.Principal</code> objects in the return value * of the <code>Subject.getPrincipals()</code> method. However, it provides * no guidance on how to distinguish Principals that describe the individual * user (and are thus appropriate to return as the value of * request.getUserPrincipal() in a web application) from the Principal(s) * that describe the authorized roles for this user. To maintain as much * independence as possible from the underlying <code>LoginMethod</code> * implementation executed by JAAS, the following policy is implemented by * this Realm:</p> * <ul> * <li>The JAAS <code>LoginModule</code> is assumed to return a * <code>Subject</code> with at least one <code>Principal</code> instance * representing the user himself or herself, and zero or more separate * <code>Principals</code> representing the security roles authorized * for this user.</li> * <li>On the <code>Principal</code> representing the user, the Principal * name is an appropriate value to return via the Servlet API method * <code>HttpServletRequest.getRemoteUser()</code>.</li> * <li>On the <code>Principals</code> representing the security roles, the * name is the name of the authorized security role.</li> * <li>This Realm will be configured with two lists of fully qualified Java * class names of classes that implement * <code>java.security.Principal</code> - one that identifies class(es) * representing a user, and one that identifies class(es) representing * a security role.</li> * <li>As this Realm iterates over the <code>Principals</code> returned by * <code>Subject.getPrincipals()</code>, it will identify the first * <code>Principal</code> that matches the "user classes" list as the * <code>Principal</code> for this user.</li> * <li>As this Realm iterates over the <code>Principals</code> returned by * <code>Subject.getPrincipals()</code>, it will accumulate the set of * all <code>Principals</code> matching the "role classes" list as * identifying the security roles for this user.</li> * <li>It is a configuration error for the JAAS login method to return a * validated <code>Subject</code> without a <code>Principal</code> that * matches the "user classes" list.</li> * <li>By default, the enclosing Container's name serves as the * application name used to obtain the JAAS LoginContext ("Catalina" in * a default installation). Tomcat must be able to find an application * with this name in the JAAS configuration file. Here is a hypothetical * JAAS configuration file entry for a database-oriented login module that uses * a Tomcat-managed JNDI database resource: * <blockquote><pre>Catalina { org.foobar.auth.DatabaseLoginModule REQUIRED JNDI_RESOURCE=jdbc/AuthDB USER_TABLE=users USER_ID_COLUMN=id USER_NAME_COLUMN=name USER_CREDENTIAL_COLUMN=password ROLE_TABLE=roles ROLE_NAME_COLUMN=name PRINCIPAL_FACTORY=org.foobar.auth.impl.SimplePrincipalFactory; };</pre></blockquote></li> * <li>To set the JAAS configuration file * location, set the <code>CATALINA_OPTS</code> environment variable * similar to the following: <blockquote><code>CATALINA_OPTS="-Djava.security.auth.login.config=$CATALINA_HOME/conf/jaas.config"</code></blockquote> * </li> * <li>As part of the login process, JAASRealm registers its own <code>CallbackHandler</code>, * called (unsurprisingly) <code>JAASCallbackHandler</code>. This handler supplies the * HTTP requests's username and credentials to the user-supplied <code>LoginModule</code></li> * <li>As with other <code>Realm</code> implementations, digested passwords are supported if * the <code>&lt;Realm&gt;</code> element in <code>server.xml</code> contains a * <code>digest</code> attribute; <code>JAASCallbackHandler</code> will digest the password * prior to passing it back to the <code>LoginModule</code></li> * </ul> * * @author Craig R. McClanahan * @author Yoav Shapira * @version $Id$ */ public class JAASRealm extends RealmBase { private static final Log log = LogFactory.getLog(JAASRealm.class); // ----------------------------------------------------- Instance Variables /** * The application name passed to the JAAS <code>LoginContext</code>, * which uses it to select the set of relevant <code>LoginModule</code>s. */ protected String appName = null; /** * Descriptive information about this <code>Realm</code> implementation. */ protected static final String name = "JAASRealm"; /** * The list of role class names, split out for easy processing. */ protected final List<String> roleClasses = new ArrayList<>(); /** * The set of user class names, split out for easy processing. */ protected final List<String> userClasses = new ArrayList<>(); /** * Whether to use context ClassLoader or default ClassLoader. * True means use context ClassLoader, and True is the default * value. */ protected boolean useContextClassLoader = true; // ------------------------------------------------------------- Properties /** * setter for the <code>appName</code> member variable */ public void setAppName(String name) { appName = name; } /** * getter for the <code>appName</code> member variable */ public String getAppName() { return appName; } /** * Sets whether to use the context or default ClassLoader. * True means use context ClassLoader. * * @param useContext True means use context ClassLoader */ public void setUseContextClassLoader(boolean useContext) { useContextClassLoader = useContext; log.info("Setting useContextClassLoader = " + useContext); } /** * Returns whether to use the context or default ClassLoader. * True means to use the context ClassLoader. * * @return The value of useContextClassLoader */ public boolean isUseContextClassLoader() { return useContextClassLoader; } @Override public void setContainer(Container container) { super.setContainer(container); if( appName==null ) { String name = container.getName(); if (!name.startsWith("/")) { name = "/" + name; } name = makeLegalForJAAS(name); appName=name; log.info("Set JAAS app name " + appName); } } /** * Comma-delimited list of <code>java.security.Principal</code> classes * that represent security roles. */ protected String roleClassNames = null; public String getRoleClassNames() { return (this.roleClassNames); } /** * Sets the list of comma-delimited classes that represent roles. The * classes in the list must implement <code>java.security.Principal</code>. * The supplied list of classes will be parsed when {@link #start()} is * called. */ public void setRoleClassNames(String roleClassNames) { this.roleClassNames = roleClassNames; } /** * Parses a comma-delimited list of class names, and store the class names * in the provided List. Each class must implement * <code>java.security.Principal</code>. * * @param classNamesString a comma-delimited list of fully qualified class names. * @param classNamesList the list in which the class names will be stored. * The list is cleared before being populated. */ protected void parseClassNames(String classNamesString, List<String> classNamesList) { classNamesList.clear(); if (classNamesString == null) return; ClassLoader loader = this.getClass().getClassLoader(); if (isUseContextClassLoader()) loader = Thread.currentThread().getContextClassLoader(); String[] classNames = classNamesString.split("[ ]*,[ ]*"); for (int i=0; i<classNames.length; i++) { if (classNames[i].length()==0) continue; try { Class<?> principalClass = Class.forName(classNames[i], false, loader); if (Principal.class.isAssignableFrom(principalClass)) { classNamesList.add(classNames[i]); } else { log.error("Class "+classNames[i]+" is not implementing "+ "java.security.Principal! Class not added."); } } catch (ClassNotFoundException e) { log.error("Class "+classNames[i]+" not found! Class not added."); } } } /** * Comma-delimited list of <code>java.security.Principal</code> classes * that represent individual users. */ protected String userClassNames = null; public String getUserClassNames() { return (this.userClassNames); } /** * Sets the list of comma-delimited classes that represent individual * users. The classes in the list must implement * <code>java.security.Principal</code>. The supplied list of classes will * be parsed when {@link #start()} is called. */ public void setUserClassNames(String userClassNames) { this.userClassNames = userClassNames; } // --------------------------------------------------------- Public Methods /** * Return the <code>Principal</code> associated with the specified username * and credentials, if there is one; otherwise return <code>null</code>. * * @param username Username of the <code>Principal</code> to look up * @param credentials Password or other credentials to use in * authenticating this username */ @Override public Principal authenticate(String username, String credentials) { return authenticate(username, new JAASCallbackHandler(this, username, credentials)); } /** * Return the <code>Principal</code> associated with the specified username * and digest, if there is one; otherwise return <code>null</code>. * * @param username Username of the <code>Principal</code> to look up * @param clientDigest Digest to use in authenticating this username * @param nonce Server generated nonce * @param nc Nonce count * @param cnonce Client generated nonce * @param qop Quality of protection applied to the message * @param realmName Realm name * @param md5a2 Second MD5 digest used to calculate the digest * MD5(Method + ":" + uri) */ @Override public Principal authenticate(String username, String clientDigest, String nonce, String nc, String cnonce, String qop, String realmName, String md5a2) { return authenticate(username, new JAASCallbackHandler(this, username, clientDigest, nonce, nc, cnonce, qop, realmName, md5a2, HttpServletRequest.DIGEST_AUTH)); } // -------------------------------------------------------- Package Methods // ------------------------------------------------------ Protected Methods /** * Perform the actual JAAS authentication */ protected Principal authenticate(String username, CallbackHandler callbackHandler) { // Establish a LoginContext to use for authentication try { LoginContext loginContext = null; if( appName==null ) appName="Tomcat"; if( log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.beginLogin", username, appName)); // What if the LoginModule is in the container class loader ? ClassLoader ocl = null; if (!isUseContextClassLoader()) { ocl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader()); } try { loginContext = new LoginContext(appName, callbackHandler); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); } finally { if(!isUseContextClassLoader()) { Thread.currentThread().setContextClassLoader(ocl); } } if( log.isDebugEnabled()) log.debug("Login context created " + username); // Negotiate a login via this LoginContext Subject subject = null; try { loginContext.login(); subject = loginContext.getSubject(); if (subject == null) { if( log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); } } catch (AccountExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.accountExpired", username)); return (null); } catch (CredentialExpiredException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.credentialExpired", username)); return (null); } catch (FailedLoginException e) { if (log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.failedLogin", username)); return (null); } catch (LoginException e) { log.warn(sm.getString("jaasRealm.loginException", username), e); return (null); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("jaasRealm.unexpectedError"), e); return (null); } if( log.isDebugEnabled()) log.debug(sm.getString("jaasRealm.loginContextCreated", username)); // Return the appropriate Principal for this authenticated Subject Principal principal = createPrincipal(username, subject, loginContext); if (principal == null) { log.debug(sm.getString("jaasRealm.authenticateFailure", username)); return (null); } if (log.isDebugEnabled()) { log.debug(sm.getString("jaasRealm.authenticateSuccess", username)); } return (principal); } catch( Throwable t) { log.error( "error ", t); return null; } } /** * Return a short name for this <code>Realm</code> implementation. */ @Override protected String getName() { return (name); } /** * Return the password associated with the given principal's user name. This * always returns null as the JAASRealm has no way of obtaining this * information. */ @Override protected String getPassword(String username) { return (null); } /** * Return the <code>Principal</code> associated with the given user name. */ @Override protected Principal getPrincipal(String username) { return authenticate(username, new JAASCallbackHandler(this, username, null, null, null, null, null, null, null, HttpServletRequest.CLIENT_CERT_AUTH)); } /** * Identify and return a <code>java.security.Principal</code> instance * representing the authenticated user for the specified <code>Subject</code>. * The Principal is constructed by scanning the list of Principals returned * by the JAASLoginModule. The first <code>Principal</code> object that matches * one of the class names supplied as a "user class" is the user Principal. * This object is returned to the caller. * Any remaining principal objects returned by the LoginModules are mapped to * roles, but only if their respective classes match one of the "role class" classes. * If a user Principal cannot be constructed, return <code>null</code>. * @param subject The <code>Subject</code> representing the logged-in user * @param loginContext Associated with the Principal so * {@link LoginContext#logout()} can be called later */ protected Principal createPrincipal(String username, Subject subject, LoginContext loginContext) { // Prepare to scan the Principals for this Subject List<String> roles = new ArrayList<>(); Principal userPrincipal = null; // Scan the Principals for this Subject Iterator<Principal> principals = subject.getPrincipals().iterator(); while (principals.hasNext()) { Principal principal = principals.next(); String principalClass = principal.getClass().getName(); if( log.isDebugEnabled() ) { log.debug(sm.getString("jaasRealm.checkPrincipal", principal, principalClass)); } if (userPrincipal == null && userClasses.contains(principalClass)) { userPrincipal = principal; if( log.isDebugEnabled() ) { log.debug(sm.getString("jaasRealm.userPrincipalSuccess", principal.getName())); } } if (roleClasses.contains(principalClass)) { roles.add(principal.getName()); if( log.isDebugEnabled() ) { log.debug(sm.getString("jaasRealm.rolePrincipalAdd", principal.getName())); } } } // Print failure message if needed if (userPrincipal == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("jaasRealm.userPrincipalFailure")); log.debug(sm.getString("jaasRealm.rolePrincipalFailure")); } } else { if (roles.size() == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString("jaasRealm.rolePrincipalFailure")); } } } // Return the resulting Principal for our authenticated user return new GenericPrincipal(username, null, roles, userPrincipal, loginContext); } /** * Ensure the given name is legal for JAAS configuration. * Added for Bugzilla 30869, made protected for easy customization * in case my implementation is insufficient, which I think is * very likely. * * @param src The name to validate * @return A string that's a valid JAAS realm name */ protected String makeLegalForJAAS(final String src) { String result = src; // Default name is "other" per JAAS spec if(result == null) { result = "other"; } // Strip leading slash if present, as Sun JAAS impl // barfs on it (see Bugzilla 30869 bug report). if(result.startsWith("/")) { result = result.substring(1); } return result; } // ------------------------------------------------------ Lifecycle Methods /** * Prepare for the beginning of active use of the public methods of this * component and implement the requirements of * {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected void startInternal() throws LifecycleException { // These need to be called after loading configuration, in case // useContextClassLoader appears after them in xml config parseClassNames(userClassNames, userClasses); parseClassNames(roleClassNames, roleClasses); super.startInternal(); } }
55,177
Bug 55177 connectionTimeout=-1 causes high CPU
null
resolved fixed
df6cee7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T20:28:01Z
2013-07-01T23:06:40Z
java/org/apache/coyote/http11/Http11Processor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.EOFException; import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import org.apache.coyote.ActionCode; import org.apache.coyote.http11.filters.BufferedInputFilter; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.JIoEndpoint; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; /** * Processes HTTP requests. * * @author Remy Maucherat * @author fhanik */ public class Http11Processor extends AbstractHttp11Processor<Socket> { private static final Log log = LogFactory.getLog(Http11Processor.class); @Override protected Log getLog() { return log; } // ------------------------------------------------------------ Constructor public Http11Processor(int headerBufferSize, JIoEndpoint endpoint, int maxTrailerSize) { super(endpoint); inputBuffer = new InternalInputBuffer(request, headerBufferSize); request.setInputBuffer(inputBuffer); outputBuffer = new InternalOutputBuffer(response, headerBufferSize); response.setOutputBuffer(outputBuffer); initializeFilters(maxTrailerSize); } // ----------------------------------------------------- Instance Variables /** * SSL information. */ protected SSLSupport sslSupport; /** * Socket associated with the current connection. */ protected SocketWrapper<Socket> socket; /** * The percentage of threads that have to be in use before keep-alive is * disabled to aid scalability. */ private int disableKeepAlivePercentage = 75; // --------------------------------------------------------- Public Methods /** * Set the SSL information for this HTTP connection. */ @Override public void setSslSupport(SSLSupport sslSupport) { this.sslSupport = sslSupport; } public int getDisableKeepAlivePercentage() { return disableKeepAlivePercentage; } public void setDisableKeepAlivePercentage(int disableKeepAlivePercentage) { this.disableKeepAlivePercentage = disableKeepAlivePercentage; } @Override protected boolean disableKeepAlive() { int threadRatio = -1; // These may return zero or negative values // Only calculate a thread ratio when both are >0 to ensure we get a // sensible result int maxThreads, threadsBusy; if ((maxThreads = endpoint.getMaxThreads()) > 0 && (threadsBusy = endpoint.getCurrentThreadsBusy()) > 0) { threadRatio = (threadsBusy * 100) / maxThreads; } // Disable keep-alive if we are running low on threads if (threadRatio > getDisableKeepAlivePercentage()) { return true; } return false; } @Override protected void setRequestLineReadTimeout() throws IOException { /* * When there is no data in the buffer and this is not the first * request on this connection and timeouts are being used the * first read for this request may need a different timeout to * take account of time spent waiting for a processing thread. * * This is a little hacky but better than exposing the socket * and the timeout info to the InputBuffer */ if (inputBuffer.lastValid == 0 && socket.getLastAccess() > -1) { int firstReadTimeout; if (keepAliveTimeout == -1) { firstReadTimeout = 0; } else { long queueTime = System.currentTimeMillis() - socket.getLastAccess(); if (queueTime >= keepAliveTimeout) { // Queued for longer than timeout but there might be // data so use shortest possible timeout firstReadTimeout = 1; } else { // Cast is safe since queueTime must be less than // keepAliveTimeout which is an int firstReadTimeout = keepAliveTimeout - (int) queueTime; } } socket.getSocket().setSoTimeout(firstReadTimeout); // Blocking IO so fill() always blocks if (!inputBuffer.fill(true)) { throw new EOFException(sm.getString("iib.eof.error")); } // Once the first byte has been read, the standard timeout should be // used so restore it here. socket.getSocket().setSoTimeout(endpoint.getSoTimeout()); } } @Override protected boolean handleIncompleteRequestLineRead() { // Not used with BIO since it uses blocking reads return false; } @Override protected void setSocketTimeout(int timeout) throws IOException { socket.getSocket().setSoTimeout(timeout); } @Override protected void setCometTimeouts(SocketWrapper<Socket> socketWrapper) { // NO-OP for BIO } @Override protected boolean breakKeepAliveLoop(SocketWrapper<Socket> socketWrapper) { openSocket = keepAlive; // If we don't have a pipe-lined request allow this thread to be // used by another connection if (inputBuffer.lastValid == 0) { return true; } return false; } @Override protected void registerForEvent(boolean read, boolean write) { // NO-OP for BIO } @Override protected void resetTimeouts() { // NO-OP for BIO } @Override protected void recycleInternal() { // Recycle this.socket = null; // Recycle ssl info sslSupport = null; } @Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("http11processor.comet.notsupported")); } // ----------------------------------------------------- ActionHook Methods /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override public void actionInternal(ActionCode actionCode, Object param) { if (actionCode == ActionCode.REQ_SSL_ATTRIBUTE ) { try { if (sslSupport != null) { Object sslO = sslSupport.getCipherSuite(); if (sslO != null) request.setAttribute (SSLSupport.CIPHER_SUITE_KEY, sslO); sslO = sslSupport.getPeerCertificateChain(false); if (sslO != null) request.setAttribute (SSLSupport.CERTIFICATE_KEY, sslO); sslO = sslSupport.getKeySize(); if (sslO != null) request.setAttribute (SSLSupport.KEY_SIZE_KEY, sslO); sslO = sslSupport.getSessionId(); if (sslO != null) request.setAttribute (SSLSupport.SESSION_ID_KEY, sslO); request.setAttribute(SSLSupport.SESSION_MGR, sslSupport); } } catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); } } else if (actionCode == ActionCode.REQ_HOST_ADDR_ATTRIBUTE) { if (socket == null) { request.remoteAddr().recycle(); } else { if (socket.getRemoteAddr() == null) { InetAddress inetAddr = socket.getSocket().getInetAddress(); if (inetAddr != null) { socket.setRemoteAddr(inetAddr.getHostAddress()); } } request.remoteAddr().setString(socket.getRemoteAddr()); } } else if (actionCode == ActionCode.REQ_LOCAL_NAME_ATTRIBUTE) { if (socket == null) { request.localName().recycle(); } else { if (socket.getLocalName() == null) { InetAddress inetAddr = socket.getSocket().getLocalAddress(); if (inetAddr != null) { socket.setLocalName(inetAddr.getHostName()); } } request.localName().setString(socket.getLocalName()); } } else if (actionCode == ActionCode.REQ_HOST_ATTRIBUTE) { if (socket == null) { request.remoteHost().recycle(); } else { if (socket.getRemoteHost() == null) { InetAddress inetAddr = socket.getSocket().getInetAddress(); if (inetAddr != null) { socket.setRemoteHost(inetAddr.getHostName()); } if (socket.getRemoteHost() == null) { if (socket.getRemoteAddr() == null && inetAddr != null) { socket.setRemoteAddr(inetAddr.getHostAddress()); } if (socket.getRemoteAddr() != null) { socket.setRemoteHost(socket.getRemoteAddr()); } } } request.remoteHost().setString(socket.getRemoteHost()); } } else if (actionCode == ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE) { if (socket == null) { request.localAddr().recycle(); } else { if (socket.getLocalAddr() == null) { socket.setLocalAddr( socket.getSocket().getLocalAddress().getHostAddress()); } request.localAddr().setString(socket.getLocalAddr()); } } else if (actionCode == ActionCode.REQ_REMOTEPORT_ATTRIBUTE) { if (socket == null) { request.setRemotePort(0); } else { if (socket.getRemotePort() == -1) { socket.setRemotePort(socket.getSocket().getPort()); } request.setRemotePort(socket.getRemotePort()); } } else if (actionCode == ActionCode.REQ_LOCALPORT_ATTRIBUTE) { if (socket == null) { request.setLocalPort(0); } else { if (socket.getLocalPort() == -1) { socket.setLocalPort(socket.getSocket().getLocalPort()); } request.setLocalPort(socket.getLocalPort()); } } else if (actionCode == ActionCode.REQ_SSL_CERTIFICATE) { if( sslSupport != null) { /* * 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(maxSavePostSize); inputBuffer.addActiveFilter (inputFilters[Constants.BUFFERED_FILTER]); try { Object sslO = sslSupport.getPeerCertificateChain(true); if( sslO != null) { request.setAttribute (SSLSupport.CERTIFICATE_KEY, sslO); } } catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); } } } else if (actionCode == ActionCode.ASYNC_COMPLETE) { if (asyncStateMachine.asyncComplete()) { ((JIoEndpoint) endpoint).processSocketAsync(this.socket, SocketStatus.OPEN_READ); } } else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) { if (param == null) return; long timeout = ((Long)param).longValue(); // if we are not piggy backing on a worker thread, set the timeout socket.setTimeout(timeout); } else if (actionCode == ActionCode.ASYNC_DISPATCH) { if (asyncStateMachine.asyncDispatch()) { ((JIoEndpoint) endpoint).processSocketAsync(this.socket, SocketStatus.OPEN_READ); } } } // ------------------------------------------------------ Protected Methods @Override protected void prepareRequestInternal() { // NOOP for BIO } @Override protected boolean prepareSendfile(OutputFilter[] outputFilters) { // Should never, ever call this code Exception e = new Exception(); log.error(sm.getString("http11processor.neverused"), e); return false; } @Override protected void setSocketWrapper(SocketWrapper<Socket> socketWrapper) { this.socket = socketWrapper; } @Override protected AbstractInputBuffer<Socket> getInputBuffer() { return inputBuffer; } @Override protected AbstractOutputBuffer<Socket> getOutputBuffer() { return outputBuffer; } /** * Set the socket buffer flag. */ @Override public void setSocketBuffer(int socketBuffer) { super.setSocketBuffer(socketBuffer); outputBuffer.setSocketBuffer(socketBuffer); } }
55,179
Bug 55179 Incorrect Parameter Name in RemoteIpValve Examples
null
resolved fixed
21f0a5c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T21:25:05Z
2013-07-02T01:53:20Z
java/org/apache/catalina/valves/RemoteIpValve.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.valves; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.ServletException; import org.apache.catalina.AccessLog; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * <p> * Tomcat port of <a href="http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this valve replaces the apparent * client remote IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request * headers (e.g. "X-Forwarded-For"). * </p> * <p> * Another feature of this valve is to replace the apparent scheme (http/https) and server port with the scheme presented by a proxy or a * load balancer via a request header (e.g. "X-Forwarded-Proto"). * </p> * <p> * This valve proceeds as follows: * </p> * <p> * If the incoming <code>request.getRemoteAddr()</code> matches the valve's list of internal proxies : * <ul> * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http * header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li> * <li>For each ip/host of the list: * <ul> * <li>if it matches the internal proxies list, the ip/host is swallowed</li> * <li>if it matches the trusted proxies list, the ip/host is added to the created proxies header</li> * <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li> * </ul> * </li> * <li>If the request http header named <code>$protocolHeader</code> (e.g. <code>x-forwarded-for</code>) equals to the value of * <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>, * <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the * <code>$httpsServerPort</code> configuration parameter.</li> * </ul> * </p> * <p> * <strong>Configuration parameters:</strong> * <table border="1"> * <tr> * <th>RemoteIpValve property</th> * <th>Description</th> * <th>Equivalent mod_remoteip directive</th> * <th>Format</th> * <th>Default Value</th> * </tr> * <tr> * <td>remoteIpHeader</td> * <td>Name of the Http Header read by this valve that holds the list of traversed IP addresses starting from the requesting client</td> * <td>RemoteIPHeader</td> * <td>Compliant http header name</td> * <td>x-forwarded-for</td> * </tr> * <tr> * <td>internalProxies</td> * <td>Regular expression that matches the IP addresses of internal proxies. * If they appear in the <code>remoteIpHeader</code> value, they will be * trusted and will not appear * in the <code>proxiesHeader</code> value</td> * <td>RemoteIPInternalProxy</td> * <td>Regular expression (in the syntax supported by * {@link java.util.regex.Pattern java.util.regex})</td> * <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}<br/> * By default, 10/8, 192.168/16, 169.254/16 and 127/8 are allowed ; 172.16/12 has not been enabled by default because it is complex to * describe with regular expressions</td> * </tr> * </tr> * <tr> * <td>proxiesHeader</td> * <td>Name of the http header created by this valve to hold the list of proxies that have been processed in the incoming * <code>remoteIpHeader</code></td> * <td>RemoteIPProxiesHeader</td> * <td>Compliant http header name</td> * <td>x-forwarded-by</td> * </tr> * <tr> * <td>trustedProxies</td> * <td>Regular expression that matches the IP addresses of trusted proxies. * If they appear in the <code>remoteIpHeader</code> value, they will be * trusted and will appear in the <code>proxiesHeader</code> value</td> * <td>RemoteIPTrustedProxy</td> * <td>Regular expression (in the syntax supported by * {@link java.util.regex.Pattern java.util.regex})</td> * <td>&nbsp;</td> * </tr> * <tr> * <td>protocolHeader</td> * <td>Name of the http header read by this valve that holds the flag that this request </td> * <td>N/A</td> * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td> * <td><code>null</code></td> * </tr> * <tr> * <td>protocolHeaderHttpsValue</td> * <td>Value of the <code>protocolHeader</code> to indicate that it is an Https request</td> * <td>N/A</td> * <td>String like <code>https</code> or <code>ON</code></td> * <td><code>https</code></td> * </tr> * <tr> * <td>httpServerPort</td> * <td>Value returned by {@link javax.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td> * <td>N/A</td> * <td>integer</td> * <td>80</td> * </tr> * <tr> * <td>httpsServerPort</td> * <td>Value returned by {@link javax.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td> * <td>N/A</td> * <td>integer</td> * <td>443</td> * </tr> * </table> * </p> * <p> * <p> * This Valve may be attached to any Container, depending on the granularity of the filtering you wish to perform. * </p> * <p> * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g. * <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as Tomcat doesn't have a * library similar to <a * href="http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>, * <code>RemoteIpValve</code> uses regular expression to configure <code>internalProxies</code> and <code>trustedProxies</code> in the same * fashion as {@link RequestFilterValve} does. * </p> * <hr/> * <p> * <strong>Sample with internal proxies</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * remoteIpProxiesHeader="x-forwarded-by" * protocolHeader="x-forwarded-proto" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, 192.168.0.10</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-proto']</td> * <td>https</td> * <td>https</td> * </tr> * <tr> * <td>request.scheme</td> * <td>http</td> * <td>https</td> * </tr> * <tr> * <td>request.secure</td> * <td>false</td> * <td>true</td> * </tr> * <tr> * <td>request.serverPort</td> * <td>80</td> * <td>443</td> * </tr> * </table> * Note : <code>x-forwarded-by</code> header is null because only internal proxies as been traversed by the request. * <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with trusted proxies</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * remoteIpProxiesHeader="x-forwarded-by" * trustedProxies="proxy1|proxy2" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, proxy1, proxy2</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1, proxy2</td> * </tr> * </table> * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both * are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with internal and trusted proxies</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * remoteIpProxiesHeader="x-forwarded-by" * trustedProxies="proxy1|proxy2" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, proxy1, proxy2, 192.168.0.10</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1, proxy2</td> * </tr> * </table> * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both * are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in * <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with an untrusted proxy</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * remoteIpProxiesHeader="x-forwarded-by" * trustedProxies="proxy1|proxy2" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>untrusted-proxy</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, untrusted-proxy, proxy1</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1</td> * </tr> * </table> * Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds * <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we can not trust that * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP * verified by <code>proxy1</code>. * </p> */ public class RemoteIpValve extends ValveBase { /** * {@link Pattern} for a comma delimited string that support whitespace characters */ private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*"); /** * Logger */ private static final Log log = LogFactory.getLog(RemoteIpValve.class); /** * Convert a given comma delimited String into an array of String * * @return array of String (non <code>null</code>) */ protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) { return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern .split(commaDelimitedStrings); } /** * Convert an array of strings in a comma delimited string */ protected static String listToCommaDelimitedString(List<String> stringList) { if (stringList == null) { return ""; } StringBuilder result = new StringBuilder(); for (Iterator<String> it = stringList.iterator(); it.hasNext();) { Object element = it.next(); if (element != null) { result.append(element); if (it.hasNext()) { result.append(", "); } } } return result.toString(); } /** * @see #setHttpServerPort(int) */ private int httpServerPort = 80; /** * @see #setHttpsServerPort(int) */ private int httpsServerPort = 443; private boolean changeLocalPort = false; /** * @see #setInternalProxies(String) */ private Pattern internalProxies = Pattern.compile( "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" + "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); /** * @see #setProtocolHeader(String) */ private String protocolHeader = null; /** * @see #setProtocolHeaderHttpsValue(String) */ private String protocolHeaderHttpsValue = "https"; private String portHeader = null; /** * @see #setProxiesHeader(String) */ private String proxiesHeader = "X-Forwarded-By"; /** * @see #setRemoteIpHeader(String) */ private String remoteIpHeader = "X-Forwarded-For"; /** * @see #setRequestAttributesEnabled(boolean) */ private boolean requestAttributesEnabled = true; /** * @see RemoteIpValve#setTrustedProxies(String) */ private Pattern trustedProxies = null; /** * Default constructor that ensures {@link ValveBase#ValveBase(boolean)} is * called with <code>true</code>. */ public RemoteIpValve() { // Async requests are supported with this valve super(true); } public int getHttpsServerPort() { return httpsServerPort; } public int getHttpServerPort() { return httpServerPort; } public boolean isChangeLocalPort() { return changeLocalPort; } public void setChangeLocalPort(boolean changeLocalPort) { this.changeLocalPort = changeLocalPort; } /** * Obtain the name of the HTTP header used to override the value returned * by {@link Request#getServerPort()} and (optionally depending on {link * {@link #isChangeLocalPort()} {@link Request#getLocalPort()}. * * @return The HTTP header name */ public String getPortHeader() { return portHeader; } /** * Set the name of the HTTP header used to override the value returned * by {@link Request#getServerPort()} and (optionally depending on {link * {@link #isChangeLocalPort()} {@link Request#getLocalPort()}. * * @param portHeader The HTTP header name */ public void setPortHeader(String portHeader) { this.portHeader = portHeader; } /** * @see #setInternalProxies(String) * @return Regular expression that defines the internal proxies */ public String getInternalProxies() { if (internalProxies == null) { return null; } return internalProxies.toString(); } /** * @see #setProtocolHeader(String) * @return the protocol header (e.g. "X-Forwarded-Proto") */ public String getProtocolHeader() { return protocolHeader; } /** * @see RemoteIpValve#setProtocolHeaderHttpsValue(String) * @return the value of the protocol header for incoming https request (e.g. "https") */ public String getProtocolHeaderHttpsValue() { return protocolHeaderHttpsValue; } /** * @see #setProxiesHeader(String) * @return the proxies header name (e.g. "X-Forwarded-By") */ public String getProxiesHeader() { return proxiesHeader; } /** * @see #setRemoteIpHeader(String) * @return the remote IP header name (e.g. "X-Forwarded-For") */ public String getRemoteIpHeader() { return remoteIpHeader; } /** * @see #setRequestAttributesEnabled(boolean) * @return <code>true</code> if the attributes will be logged, otherwise * <code>false</code> */ public boolean getRequestAttributesEnabled() { return requestAttributesEnabled; } /** * @see #setTrustedProxies(String) * @return Regular expression that defines the trusted proxies */ public String getTrustedProxies() { if (trustedProxies == null) { return null; } return trustedProxies.toString(); } /** * {@inheritDoc} */ @Override public void invoke(Request request, Response response) throws IOException, ServletException { final String originalRemoteAddr = request.getRemoteAddr(); final String originalRemoteHost = request.getRemoteHost(); final String originalScheme = request.getScheme(); final boolean originalSecure = request.isSecure(); final int originalServerPort = request.getServerPort(); if (internalProxies !=null && internalProxies.matcher(originalRemoteAddr).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } if (remoteIp != null) { request.setRemoteAddr(remoteIp); request.setRemoteHost(remoteIp); // use request.coyoteRequest.mimeHeaders.setValue(str).setString(str) because request.addHeader(str, str) is no-op in Tomcat // 6.0 if (proxiesHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes // of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { request.setSecure(true); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("https"); setPorts(request, httpsServerPort); } else { request.setSecure(false); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("http"); setPorts(request, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + originalRemoteAddr + "', originalRemoteHost='" + originalRemoteHost + "', originalSecure='" + originalSecure + "', originalScheme='" + originalScheme + "' will be seen as newRemoteAddr='" + request.getRemoteAddr() + "', newRemoteHost='" + request.getRemoteHost() + "', newScheme='" + request.getScheme() + "', newSecure='" + request.isSecure() + "'"); } } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } try { getNext().invoke(request, response); } finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); } } private void setPorts(Request request, int defaultPort) { int port = defaultPort; if (portHeader != null) { String portHeaderValue = request.getHeader(portHeader); if (portHeaderValue != null) { try { port = Integer.parseInt(portHeaderValue); } catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } } } } request.setServerPort(port); if (changeLocalPort) { request.setLocalPort(port); } } /** * <p> * Server Port value if the {@link #protocolHeader} is not <code>null</code> and does not indicate HTTP * </p> * <p> * Default value : 80 * </p> */ public void setHttpServerPort(int httpServerPort) { this.httpServerPort = httpServerPort; } /** * <p> * Server Port value if the {@link #protocolHeader} indicates HTTPS * </p> * <p> * Default value : 443 * </p> */ public void setHttpsServerPort(int httpsServerPort) { this.httpsServerPort = httpsServerPort; } /** * <p> * Regular expression that defines the internal proxies. * </p> * <p> * Default value : 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254.\d{1,3}.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3} * </p> */ public void setInternalProxies(String internalProxies) { if (internalProxies == null || internalProxies.length() == 0) { this.internalProxies = null; } else { this.internalProxies = Pattern.compile(internalProxies); } } /** * <p> * Header that holds the incoming protocol, usally named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and * request.secure will not be modified. * </p> * <p> * Default value : <code>null</code> * </p> */ public void setProtocolHeader(String protocolHeader) { this.protocolHeader = protocolHeader; } /** * <p> * Case insensitive value of the protocol header to indicate that the incoming http request uses SSL. * </p> * <p> * Default value : <code>https</code> * </p> */ public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) { this.protocolHeaderHttpsValue = protocolHeaderHttpsValue; } /** * <p> * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP * addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header, * while any intermediate RemoteIPInternalProxy addresses are discarded. * </p> * <p> * Name of the http header that holds the list of trusted proxies that has been traversed by the http request. * </p> * <p> * The value of this header can be comma delimited. * </p> * <p> * Default value : <code>X-Forwarded-By</code> * </p> */ public void setProxiesHeader(String proxiesHeader) { this.proxiesHeader = proxiesHeader; } /** * <p> * Name of the http header from which the remote ip is extracted. * </p> * <p> * The value of this header can be comma delimited. * </p> * <p> * Default value : <code>X-Forwarded-For</code> * </p> * * @param remoteIpHeader */ public void setRemoteIpHeader(String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } /** * Should this valve set request attributes for IP address, Hostname, * protocol and port used for the request? This are typically used in * conjunction with the {@link AccessLog} which will otherwise log the * original values. Default is <code>true</code>. * * The attributes set are: * <ul> * <li>org.apache.catalina.AccessLog.RemoteAddr</li> * <li>org.apache.catalina.AccessLog.RemoteHost</li> * <li>org.apache.catalina.AccessLog.Protocol</li> * <li>org.apache.catalina.AccessLog.ServerPort</li> * </ul> * * @param requestAttributesEnabled <code>true</code> causes the attributes * to be set, <code>false</code> disables * the setting of the attributes. */ public void setRequestAttributesEnabled(boolean requestAttributesEnabled) { this.requestAttributesEnabled = requestAttributesEnabled; } /** * <p> * Regular expression defining proxies that are trusted when they appear in * the {@link #remoteIpHeader} header. * </p> * <p> * Default value : empty list, no external proxy is trusted. * </p> */ public void setTrustedProxies(String trustedProxies) { if (trustedProxies == null || trustedProxies.length() == 0) { this.trustedProxies = null; } else { this.trustedProxies = Pattern.compile(trustedProxies); } } }
55,174
Bug 55174 [jsr 356][websocket] MessageHandler never gets notified again after it throws exception
I have a test which adds a MessageHandler which gets notified on text messages. If its implementation method onMessage(String text) throws some exception (e.g. runtime exception), this MessageHandler will never ever be notified again for any new text messages received by the session. I suppose this happens because the exception actually kills the underlying thread in which the notification has happened. I think the client side implementation shall be more robust and expect and be prepared for exceptions coming from calls to user code.
resolved fixed
ddd73d0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-01T22:08:06Z
2013-07-01T17:33:20Z
java/org/apache/tomcat/websocket/WsFrameBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.MessageHandler; import javax.websocket.PongMessage; import org.apache.tomcat.util.buf.Utf8Decoder; import org.apache.tomcat.util.res.StringManager; /** * Takes the ServletInputStream, processes the WebSocket frames it contains and * extracts the messages. WebSocket Pings received will be responded to * automatically without any action required by the application. */ public abstract class WsFrameBase { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); // Connection level attributes protected final WsSession wsSession; protected final byte[] inputBuffer; // Attributes for control messages // Control messages can appear in the middle of other messages so need // separate attributes private final ByteBuffer controlBufferBinary = ByteBuffer.allocate(125); private final CharBuffer controlBufferText = CharBuffer.allocate(125); // Attributes of the current message private final CharsetDecoder utf8DecoderControl = new Utf8Decoder(). onMalformedInput(CodingErrorAction.REPORT). onUnmappableCharacter(CodingErrorAction.REPORT); private final CharsetDecoder utf8DecoderMessage = new Utf8Decoder(). onMalformedInput(CodingErrorAction.REPORT). onUnmappableCharacter(CodingErrorAction.REPORT); private boolean continuationExpected = false; private boolean textMessage = false; private ByteBuffer messageBufferBinary; private CharBuffer messageBufferText; // Attributes of the current frame private boolean fin = false; private int rsv = 0; private byte opCode = 0; private final byte[] mask = new byte[4]; private int maskIndex = 0; private long payloadLength = 0; private long payloadWritten = 0; // Attributes tracking state private State state = State.NEW_FRAME; private volatile boolean open = true; private int readPos = 0; protected int writePos = 0; public WsFrameBase(WsSession wsSession) { inputBuffer = new byte[Constants.DEFAULT_BUFFER_SIZE]; messageBufferBinary = ByteBuffer.allocate(wsSession.getMaxBinaryMessageBufferSize()); messageBufferText = CharBuffer.allocate(wsSession.getMaxTextMessageBufferSize()); this.wsSession = wsSession; } protected void processInputBuffer() throws IOException { while (true) { wsSession.updateLastActive(); if (state == State.NEW_FRAME) { if (!processInitialHeader()) { break; } // If a close frame has been received, no further data should // have seen if (!open) { throw new IOException(sm.getString("wsFrame.closed")); } } if (state == State.PARTIAL_HEADER) { if (!processRemainingHeader()) { break; } } if (state == State.DATA) { if (!processData()) { break; } } } } /** * @return <code>true</code> if sufficient data was present to process all * of the initial header */ private boolean processInitialHeader() throws IOException { // Need at least two bytes of data to do this if (writePos - readPos < 2) { return false; } int b = inputBuffer[readPos++]; fin = (b & 0x80) > 0; rsv = (b & 0x70) >>> 4; if (rsv != 0) { // Note extensions may use rsv bits but currently no extensions are // supported throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.wrongRsv", Integer.valueOf(rsv)))); } opCode = (byte) (b & 0x0F); if (Util.isControl(opCode)) { if (!fin) { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.controlFragmented"))); } if (opCode != Constants.OPCODE_PING && opCode != Constants.OPCODE_PONG && opCode != Constants.OPCODE_CLOSE) { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode)))); } } else { if (continuationExpected) { if (opCode != Constants.OPCODE_CONTINUATION) { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.noContinuation"))); } } else { try { if (opCode == Constants.OPCODE_BINARY) { // New binary message textMessage = false; int size = wsSession.getMaxBinaryMessageBufferSize(); if (size != messageBufferBinary.capacity()) { messageBufferBinary = ByteBuffer.allocate(size); } } else if (opCode == Constants.OPCODE_TEXT) { // New text message textMessage = true; int size = wsSession.getMaxTextMessageBufferSize(); if (size != messageBufferText.capacity()) { messageBufferText = CharBuffer.allocate(size); } } else { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode)))); } } catch (IllegalStateException ise) { // Thrown if the session is already closed throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.sessionClosed"))); } } continuationExpected = !fin; } b = inputBuffer[readPos++]; // Client data must be masked if ((b & 0x80) == 0 && isMasked()) { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.notMasked"))); } payloadLength = b & 0x7F; state = State.PARTIAL_HEADER; return true; } protected abstract boolean isMasked(); /** * @return <code>true</code> if sufficient data was present to complete the * processing of the header */ private boolean processRemainingHeader() throws IOException { // Ignore the 2 bytes already read. 4 for the mask int headerLength; if (isMasked()) { headerLength = 4; } else { headerLength = 0; } // Add additional bytes depending on length if (payloadLength == 126) { headerLength += 2; } else if (payloadLength == 127) { headerLength += 8; } if (writePos - readPos < headerLength) { return false; } // Calculate new payload length if necessary if (payloadLength == 126) { payloadLength = byteArrayToLong(inputBuffer, readPos, 2); readPos += 2; } else if (payloadLength == 127) { payloadLength = byteArrayToLong(inputBuffer, readPos, 8); readPos += 8; } if (Util.isControl(opCode)) { if (payloadLength > 125) { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.controlPayloadTooBig", Long.valueOf(payloadLength)))); } if (!fin) { throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.controlNoFin"))); } } if (isMasked()) { System.arraycopy(inputBuffer, readPos, mask, 0, 4); readPos += 4; } state = State.DATA; return true; } private boolean processData() throws IOException { checkRoomPayload(); if (Util.isControl(opCode)) { return processDataControl(); } else if (textMessage) { return processDataText(); } else { return processDataBinary(); } } private boolean processDataControl() throws IOException { if (!appendPayloadToMessage(controlBufferBinary)) { return false; } controlBufferBinary.flip(); if (opCode == Constants.OPCODE_CLOSE) { open = false; String reason = null; int code = CloseCodes.NORMAL_CLOSURE.getCode(); if (controlBufferBinary.remaining() == 1) { controlBufferBinary.clear(); // Payload must be zero or greater than 2 throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.oneByteCloseCode"))); } if (controlBufferBinary.remaining() > 1) { code = controlBufferBinary.getShort(); if (controlBufferBinary.remaining() > 0) { CoderResult cr = utf8DecoderControl.decode( controlBufferBinary, controlBufferText, true); if (cr.isError()) { controlBufferBinary.clear(); controlBufferText.clear(); throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidUtf8Close"))); } // There will be no overflow as the output buffer is big // enough. There will be no underflow as all the data is // passed to the decoder in a single call. controlBufferText.flip(); reason = controlBufferText.toString(); } } wsSession.onClose(new CloseReason(Util.getCloseCode(code), reason)); } else if (opCode == Constants.OPCODE_PING) { if (wsSession.isOpen()) { wsSession.getBasicRemote().sendPong(controlBufferBinary); } } else if (opCode == Constants.OPCODE_PONG) { MessageHandler.Whole<PongMessage> mhPong = wsSession.getPongMessageHandler(); if (mhPong != null) { mhPong.onMessage(new WsPongMessage(controlBufferBinary)); } } else { // Should have caught this earlier but just in case... controlBufferBinary.clear(); throw new WsIOException(new CloseReason( CloseCodes.PROTOCOL_ERROR, sm.getString("wsFrame.invalidOpCode", Integer.valueOf(opCode)))); } controlBufferBinary.clear(); newFrame(); return true; } @SuppressWarnings("unchecked") private void sendMessageText(boolean last) throws WsIOException { MessageHandler mh = wsSession.getTextMessageHandler(); if (mh != null) { if (mh instanceof WrappedMessageHandler) { long maxMessageSize = ((WrappedMessageHandler) mh).getMaxMessageSize(); if (maxMessageSize > -1 && messageBufferText.remaining() > maxMessageSize) { throw new WsIOException(new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.messageTooBig", Long.valueOf(messageBufferText.remaining()), Long.valueOf(maxMessageSize)))); } } if (mh instanceof MessageHandler.Partial<?>) { ((MessageHandler.Partial<String>) mh).onMessage( messageBufferText.toString(), last); } else { // Caller ensures last == true if this branch is used ((MessageHandler.Whole<String>) mh).onMessage( messageBufferText.toString()); } messageBufferText.clear(); } } private boolean processDataText() throws IOException { // Copy the available data to the buffer while (!appendPayloadToMessage(messageBufferBinary)) { // Frame not complete - we ran out of something // Convert bytes to UTF-8 messageBufferBinary.flip(); while (true) { CoderResult cr = utf8DecoderMessage.decode( messageBufferBinary, messageBufferText, false); if (cr.isError()) { throw new WsIOException(new CloseReason( CloseCodes.NOT_CONSISTENT, sm.getString("wsFrame.invalidUtf8"))); } else if (cr.isOverflow()) { // Ran out of space in text buffer - flush it if (usePartial()) { messageBufferText.flip(); sendMessageText(false); messageBufferText.clear(); } else { throw new WsIOException(new CloseReason( CloseCodes.TOO_BIG, sm.getString("wsFrame.textMessageTooBig"))); } } else if (cr.isUnderflow()) { // Need more input // Compact what we have to create as much space as possible messageBufferBinary.compact(); // What did we run out of? if (readPos == writePos) { // Ran out of input data - get some more return false; } else { // Ran out of message buffer - exit inner loop and // refill break; } } } } messageBufferBinary.flip(); boolean last = false; // Frame is fully received // Convert bytes to UTF-8 while (true) { CoderResult cr = utf8DecoderMessage.decode(messageBufferBinary, messageBufferText, last); if (cr.isError()) { throw new WsIOException(new CloseReason( CloseCodes.NOT_CONSISTENT, sm.getString("wsFrame.invalidUtf8"))); } else if (cr.isOverflow()) { // Ran out of space in text buffer - flush it if (usePartial()) { messageBufferText.flip(); sendMessageText(false); messageBufferText.clear(); } else { throw new WsIOException(new CloseReason( CloseCodes.TOO_BIG, sm.getString("wsFrame.textMessageTooBig"))); } } else if (cr.isUnderflow() & !last) { // End of frame and possible message as well. if (continuationExpected) { // If partial messages are supported, send what we have // managed to decode if (usePartial()) { messageBufferText.flip(); sendMessageText(false); messageBufferText.clear(); } messageBufferBinary.compact(); newFrame(); // Process next frame return true; } else { // Make sure coder has flushed all output last = true; } } else { // End of message messageBufferText.flip(); sendMessageText(true); newMessage(); return true; } } } private boolean processDataBinary() throws IOException { // Copy the available data to the buffer while (!appendPayloadToMessage(messageBufferBinary)) { // Frame not complete - what did we run out of? if (readPos == writePos) { // Ran out of input data - get some more return false; } else { // Ran out of message buffer - flush it if (!usePartial()) { CloseReason cr = new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.bufferTooSmall", Integer.valueOf( messageBufferBinary.capacity()), Long.valueOf(payloadLength))); throw new WsIOException(cr); } messageBufferBinary.flip(); ByteBuffer copy = ByteBuffer.allocate(messageBufferBinary.limit()); copy.put(messageBufferBinary); copy.flip(); sendMessageBinary(copy, false); messageBufferBinary.clear(); } } // Frame is fully received // Send the message if either: // - partial messages are supported // - the message is complete if (usePartial() || !continuationExpected) { messageBufferBinary.flip(); ByteBuffer copy = ByteBuffer.allocate(messageBufferBinary.limit()); copy.put(messageBufferBinary); copy.flip(); sendMessageBinary(copy, !continuationExpected); messageBufferBinary.clear(); } if (continuationExpected) { // More data for this message expected, start a new frame newFrame(); } else { // Message is complete, start a new message newMessage(); } return true; } @SuppressWarnings("unchecked") private void sendMessageBinary(ByteBuffer msg, boolean last) throws WsIOException { MessageHandler mh = wsSession.getBinaryMessageHandler(); if (mh != null) { if (mh instanceof WrappedMessageHandler) { long maxMessageSize = ((WrappedMessageHandler) mh).getMaxMessageSize(); if (maxMessageSize > -1 && msg.remaining() > maxMessageSize) { throw new WsIOException(new CloseReason(CloseCodes.TOO_BIG, sm.getString("wsFrame.messageTooBig", Long.valueOf(msg.remaining()), Long.valueOf(maxMessageSize)))); } } if (mh instanceof MessageHandler.Partial<?>) { ((MessageHandler.Partial<ByteBuffer>) mh).onMessage(msg, last); } else { // Caller ensures last == true if this branch is used ((MessageHandler.Whole<ByteBuffer>) mh).onMessage(msg); } } } private void newMessage() { messageBufferBinary.clear(); messageBufferText.clear(); utf8DecoderMessage.reset(); continuationExpected = false; newFrame(); } private void newFrame() { if (readPos == writePos) { readPos = 0; writePos = 0; } maskIndex = 0; payloadWritten = 0; state = State.NEW_FRAME; // These get reset in processInitialHeader() // fin, rsv, opCode, payloadLength, mask checkRoomHeaders(); } private void checkRoomHeaders() { // Is the start of the current frame too near the end of the input // buffer? if (inputBuffer.length - readPos < 131) { // Limit based on a control frame with a full payload makeRoom(); } } private void checkRoomPayload() { if (inputBuffer.length - readPos - payloadLength + payloadWritten < 0) { makeRoom(); } } private void makeRoom() { System.arraycopy(inputBuffer, readPos, inputBuffer, 0, writePos - readPos); writePos = writePos - readPos; readPos = 0; } private boolean usePartial() { if (Util.isControl(opCode)) { return false; } else if (textMessage) { MessageHandler mh = wsSession.getTextMessageHandler(); if (mh != null) { return mh instanceof MessageHandler.Partial<?>; } return false; } else { // Must be binary MessageHandler mh = wsSession.getBinaryMessageHandler(); if (mh != null) { return mh instanceof MessageHandler.Partial<?>; } return false; } } private boolean appendPayloadToMessage(ByteBuffer dest) { if (isMasked()) { while (payloadWritten < payloadLength && readPos < writePos && dest.hasRemaining()) { byte b = (byte) ((inputBuffer[readPos] ^ mask[maskIndex]) & 0xFF); maskIndex++; if (maskIndex == 4) { maskIndex = 0; } readPos++; payloadWritten++; dest.put(b); } return (payloadWritten == payloadLength); } else { long toWrite = Math.min( payloadLength - payloadWritten, writePos - readPos); toWrite = Math.min(toWrite, dest.remaining()); dest.put(inputBuffer, readPos, (int) toWrite); readPos += toWrite; payloadWritten += toWrite; return (payloadWritten == payloadLength); } } protected static long byteArrayToLong(byte[] b, int start, int len) throws IOException { if (len > 8) { throw new IOException(sm.getString("wsFrame.byteToLongFail", Long.valueOf(len))); } int shift = 0; long result = 0; for (int i = start + len - 1; i >= start; i--) { result = result + ((b[i] & 0xFF) << shift); shift += 8; } return result; } protected boolean isOpen() { return open; } private static enum State { NEW_FRAME, PARTIAL_HEADER, DATA } }
55,180
Bug 55180 connectionTimeout="-1" causes timeout can't be negative
I configured server.xml like this: connectionTimeout="-1" disableUploadTimeout="false" connectionUploadTimeout="200" (maybe it is stupid to configure like this,if connectionTimeout=-1,can i make disableUploadTimeout=false?). It will cause : java.lang.IllegalArgumentException: timeout can't be negative at sun.nio.ch.SocketAdaptor.setSoTimeout(SocketAdaptor.java:361) at org.apache.coyote.http11.Http11NioProcessor.setSocketTimeout(Http11NioProcessor.java:251) ...... because of : if (!disableUploadTimeout) { //endpoint.getSoTimeout()=-1. setSocketTimeout(endpoint.getSoTimeout()); } ~~~~~~~~~~~~~~~~~~~~~~~~~ another thing: if i configure connectionTimeout="0". in NioBlockingSelector.read(ByteBuffer buf, NioChannel socket, long readTimeout),readTimeout = 0, in case socket.read(buf) == 0, it make timeout=true. if (readTimeout >= 0 && (keycount == 0)) timedout = (System.currentTimeMillis() - time) >= readTimeout; then throw the SocketTimeoutException(). thank you.
resolved fixed
4da2de0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T07:15:30Z
2013-07-02T04:40:00Z
java/org/apache/coyote/http11/AbstractHttp11Processor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Locale; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUpgradeHandler; import org.apache.coyote.AbstractProcessor; import org.apache.coyote.ActionCode; import org.apache.coyote.AsyncContextCallback; import org.apache.coyote.RequestInfo; import org.apache.coyote.http11.filters.BufferedInputFilter; import org.apache.coyote.http11.filters.ChunkedInputFilter; import org.apache.coyote.http11.filters.ChunkedOutputFilter; import org.apache.coyote.http11.filters.GzipOutputFilter; import org.apache.coyote.http11.filters.IdentityInputFilter; import org.apache.coyote.http11.filters.IdentityOutputFilter; import org.apache.coyote.http11.filters.SavedRequestInputFilter; import org.apache.coyote.http11.filters.VoidInputFilter; import org.apache.coyote.http11.filters.VoidOutputFilter; import org.apache.juli.logging.Log; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.Ascii; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.HexUtils; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.log.UserDataHelper; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractHttp11Processor<S> extends AbstractProcessor<S> { protected abstract Log getLog(); private final UserDataHelper userDataHelper; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Input. */ protected AbstractInputBuffer<S> inputBuffer ; /** * Output. */ protected AbstractOutputBuffer<S> outputBuffer; /* * 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; /** * Error flag. */ protected boolean error = false; /** * Keep-alive. */ protected boolean keepAlive = true; /** * Flag used to indicate that the socket should be kept open (e.g. for keep * alive or send file. */ protected boolean openSocket = false; /** * Flag used to indicate that the socket should treat the next request * processed like a keep-alive connection - i.e. one where there may not be * any data to process. The initial value of this flag on entering the * process method is different for connectors that use polling (NIO / APR - * data is always expected) compared to those that use blocking (BIO - data * is only expected if the connection isn't in the keep-alive state). */ protected boolean keptAlive; /** * Flag that indicates that send file processing is in progress and that the * socket should not be returned to the poller (where a poller is used). */ protected boolean sendfileInProgress = false; /** * Flag that indicates if the request headers have been completely read. */ protected boolean readComplete = true; /** * HTTP/1.1 flag. */ protected boolean http11 = true; /** * HTTP/0.9 flag. */ protected boolean http09 = false; /** * Content delimiter for the request (if false, the connection will * be closed at the end of the request). */ protected boolean contentDelimitation = true; /** * Is there an expectation ? */ protected boolean expectation = false; /** * Comet used. */ protected boolean comet = false; /** * Regular expression that defines the restricted user agents. */ protected Pattern restrictedUserAgents = null; /** * Maximum number of Keep-Alive requests to honor. */ protected int maxKeepAliveRequests = -1; /** * The number of seconds Tomcat will wait for a subsequent request * before closing the connection. */ protected int keepAliveTimeout = -1; /** * Maximum timeout on uploads. 5 minutes as in Apache HTTPD server. */ protected int connectionUploadTimeout = 300000; /** * Flag to disable setting a different time-out on uploads. */ protected boolean disableUploadTimeout = false; /** * Allowed compression level. */ protected int compressionLevel = 0; /** * Minimum content size to make compression. */ protected int compressionMinSize = 2048; /** * Max saved post size. */ protected int maxSavePostSize = 4 * 1024; /** * Regular expression that defines the user agents to not use gzip with */ protected Pattern noCompressionUserAgents = null; /** * List of MIMES which could be gzipped */ protected String[] compressableMimeTypes = { "text/html", "text/xml", "text/plain" }; /** * Host name (used to avoid useless B2C conversion on the host name). */ protected char[] hostNameC = new char[0]; /** * Allow a customized the server header for the tin-foil hat folks. */ protected String server = null; /** * Instance of the new protocol to use after the HTTP connection has been * upgraded. */ protected HttpUpgradeHandler httpUpgradeHandler = null; public AbstractHttp11Processor(AbstractEndpoint endpoint) { super(endpoint); userDataHelper = new UserDataHelper(getLog()); } /** * Set compression level. */ public void setCompression(String compression) { if (compression.equals("on")) { this.compressionLevel = 1; } else if (compression.equals("force")) { this.compressionLevel = 2; } else if (compression.equals("off")) { this.compressionLevel = 0; } else { try { // Try to parse compression as an int, which would give the // minimum compression size compressionMinSize = Integer.parseInt(compression); this.compressionLevel = 1; } catch (Exception e) { this.compressionLevel = 0; } } } /** * Set Minimum size to trigger compression. */ public void setCompressionMinSize(int compressionMinSize) { this.compressionMinSize = compressionMinSize; } /** * Set no compression user agent pattern. Regular expression as supported * by {@link Pattern}. * * ie: "gorilla|desesplorer|tigrus" */ public void setNoCompressionUserAgents(String noCompressionUserAgents) { if (noCompressionUserAgents == null || noCompressionUserAgents.length() == 0) { this.noCompressionUserAgents = null; } else { this.noCompressionUserAgents = Pattern.compile(noCompressionUserAgents); } } /** * Add a mime-type which will be compressible * The mime-type String will be exactly matched * in the response mime-type header . * * @param mimeType mime-type string */ public void addCompressableMimeType(String mimeType) { compressableMimeTypes = addStringArray(compressableMimeTypes, mimeType); } /** * Set compressible mime-type list (this method is best when used with * a large number of connectors, where it would be better to have all of * them referenced a single array). */ public void setCompressableMimeTypes(String[] compressableMimeTypes) { this.compressableMimeTypes = compressableMimeTypes; } /** * Set compressable mime-type list * List contains users agents separated by ',' : * * ie: "text/html,text/xml,text/plain" */ public void setCompressableMimeTypes(String compressableMimeTypes) { if (compressableMimeTypes != null) { this.compressableMimeTypes = null; StringTokenizer st = new StringTokenizer(compressableMimeTypes, ","); while (st.hasMoreTokens()) { addCompressableMimeType(st.nextToken().trim()); } } } /** * Return compression level. */ public String getCompression() { switch (compressionLevel) { case 0: return "off"; case 1: return "on"; case 2: return "force"; } return "off"; } /** * General use method * * @param sArray the StringArray * @param value string */ private String[] addStringArray(String sArray[], String value) { String[] result = null; if (sArray == null) { result = new String[1]; result[0] = value; } else { result = new String[sArray.length + 1]; for (int i = 0; i < sArray.length; i++) { result[i] = sArray[i]; } result[sArray.length] = value; } return result; } /** * Checks if any entry in the string array starts with the specified value * * @param sArray the StringArray * @param value string */ private boolean startsWithStringArray(String sArray[], String value) { if (value == null) { return false; } for (int i = 0; i < sArray.length; i++) { if (value.startsWith(sArray[i])) { return true; } } return false; } /** * Set restricted user agent list (which will downgrade the connector * to HTTP/1.0 mode). Regular expression as supported by {@link Pattern}. * * ie: "gorilla|desesplorer|tigrus" */ public void setRestrictedUserAgents(String restrictedUserAgents) { if (restrictedUserAgents == null || restrictedUserAgents.length() == 0) { this.restrictedUserAgents = null; } else { this.restrictedUserAgents = Pattern.compile(restrictedUserAgents); } } /** * Set the maximum number of Keep-Alive requests to honor. * This is to safeguard from DoS attacks. Setting to a negative * value disables the check. */ public void setMaxKeepAliveRequests(int mkar) { maxKeepAliveRequests = mkar; } /** * Return the number of Keep-Alive requests that we will honor. */ public int getMaxKeepAliveRequests() { return maxKeepAliveRequests; } /** * Set the Keep-Alive timeout. */ public void setKeepAliveTimeout(int timeout) { keepAliveTimeout = timeout; } /** * Return the number Keep-Alive timeout. */ public int getKeepAliveTimeout() { return keepAliveTimeout; } /** * Set the maximum size of a POST which will be buffered in SSL mode. */ public void setMaxSavePostSize(int msps) { maxSavePostSize = msps; } /** * Return the maximum size of a POST which will be buffered in SSL mode. */ public int getMaxSavePostSize() { return maxSavePostSize; } /** * Set the flag to control upload time-outs. */ public void setDisableUploadTimeout(boolean isDisabled) { disableUploadTimeout = isDisabled; } /** * Get the flag that controls upload time-outs. */ public boolean getDisableUploadTimeout() { return disableUploadTimeout; } /** * Set the socket buffer flag. */ public void setSocketBuffer(int socketBuffer) { outputBuffer.setSocketBuffer(socketBuffer); } /** * Get the socket buffer flag. */ public int getSocketBuffer() { return outputBuffer.getSocketBuffer(); } /** * Set the upload timeout. */ public void setConnectionUploadTimeout(int timeout) { connectionUploadTimeout = timeout ; } /** * Get the upload timeout. */ public int getConnectionUploadTimeout() { return connectionUploadTimeout; } /** * Set the server header name. */ public void setServer( String server ) { if (server==null || server.equals("")) { this.server = null; } else { this.server = server; } } /** * Get the server header name. */ public String getServer() { return server; } /** * Check if the resource could be compressed, if the client supports it. */ private boolean isCompressable() { // Check if content is not already gzipped MessageBytes contentEncodingMB = response.getMimeHeaders().getValue("Content-Encoding"); if ((contentEncodingMB != null) && (contentEncodingMB.indexOf("gzip") != -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check if sufficient length to trigger the compression long contentLength = response.getContentLengthLong(); if ((contentLength == -1) || (contentLength > compressionMinSize)) { // Check for compatible MIME-TYPE if (compressableMimeTypes != null) { return (startsWithStringArray(compressableMimeTypes, response.getContentType())); } } return false; } /** * Check if compression should be used for this resource. Already checked * that the resource could be compressed if the client supports it. */ private boolean useCompression() { // Check if browser support gzip encoding MessageBytes acceptEncodingMB = request.getMimeHeaders().getValue("accept-encoding"); if ((acceptEncodingMB == null) || (acceptEncodingMB.indexOf("gzip") == -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check for incompatible Browser if (noCompressionUserAgents != null) { MessageBytes userAgentValueMB = request.getMimeHeaders().getValue("user-agent"); if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (noCompressionUserAgents != null && noCompressionUserAgents.matcher(userAgentValue).matches()) { return false; } } } return true; } /** * Specialized utility method: find a sequence of lower case bytes inside * a ByteChunk. */ protected int findBytes(ByteChunk bc, byte[] b) { byte first = b[0]; byte[] buff = bc.getBuffer(); int start = bc.getStart(); int end = bc.getEnd(); // Look for first char int srcEnd = b.length; for (int i = start; i <= (end - srcEnd); i++) { if (Ascii.toLower(buff[i]) != first) { continue; } // found first char, now look for a match int myPos = i+1; for (int srcPos = 1; srcPos < srcEnd;) { if (Ascii.toLower(buff[myPos++]) != b[srcPos++]) { break; } if (srcPos == srcEnd) { return i - start; // found it } } } return -1; } /** * Determine if we must drop the connection because of the HTTP status * code. Use the same list of codes as Apache/httpd. */ protected 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 */; } /** * Allows the super class to set the socket wrapper being used. */ protected abstract void setSocketWrapper(SocketWrapper<S> socketWrapper); /** * Exposes input buffer to super class to allow better code re-use. * @return The input buffer used by the processor. */ protected abstract AbstractInputBuffer<S> getInputBuffer(); /** * Exposes output buffer to super class to allow better code re-use. * @return The output buffer used by the processor. */ protected abstract AbstractOutputBuffer<S> getOutputBuffer(); /** * Initialize standard input and output filters. */ protected void initializeFilters(int maxTrailerSize) { // Create and add the identity filters. getInputBuffer().addFilter(new IdentityInputFilter()); getOutputBuffer().addFilter(new IdentityOutputFilter()); // Create and add the chunked filters. getInputBuffer().addFilter(new ChunkedInputFilter(maxTrailerSize)); getOutputBuffer().addFilter(new ChunkedOutputFilter()); // Create and add the void filters. getInputBuffer().addFilter(new VoidInputFilter()); getOutputBuffer().addFilter(new VoidOutputFilter()); // Create and add buffered input filter getInputBuffer().addFilter(new BufferedInputFilter()); // Create and add the chunked filters. //getInputBuffer().addFilter(new GzipInputFilter()); getOutputBuffer().addFilter(new GzipOutputFilter()); pluggableFilterIndex = getInputBuffer().getFilters().length; } /** * Add an input filter to the current request. * * @return false if the encoding was not found (which would mean it is * unsupported) */ protected boolean addInputFilter(InputFilter[] inputFilters, String encodingName) { if (encodingName.equals("identity")) { // Skip } else if (encodingName.equals("chunked")) { getInputBuffer().addActiveFilter (inputFilters[Constants.CHUNKED_FILTER]); contentDelimitation = true; } else { for (int i = pluggableFilterIndex; i < inputFilters.length; i++) { if (inputFilters[i].getEncodingName() .toString().equals(encodingName)) { getInputBuffer().addActiveFilter(inputFilters[i]); return true; } } return false; } return true; } /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override public final void action(ActionCode actionCode, Object param) { if (actionCode == ActionCode.CLOSE) { // End the processing of the current request try { getOutputBuffer().endRequest(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.COMMIT) { // Commit current response if (response.isCommitted()) { return; } // Validate and write response headers try { prepareResponse(); getOutputBuffer().commit(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.ACK) { // Acknowledge request // Send a 100 status back if it makes sense (response not committed // yet, and client specified an expectation for 100-continue) if ((response.isCommitted()) || !expectation) { return; } getInputBuffer().setSwallowInput(true); try { getOutputBuffer().sendAck(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.CLIENT_FLUSH) { try { getOutputBuffer().flush(); } catch (IOException e) { // Set error flag error = true; response.setErrorException(e); } } else if (actionCode == ActionCode.DISABLE_SWALLOW_INPUT) { // Do not swallow request input but // make sure we are closing the connection error = true; getInputBuffer().setSwallowInput(false); } else if (actionCode == ActionCode.RESET) { // Reset response // Note: This must be called before the response is committed getOutputBuffer().reset(); } else if (actionCode == ActionCode.REQ_SET_BODY_REPLAY) { ByteChunk body = (ByteChunk) param; InputFilter savedBody = new SavedRequestInputFilter(body); savedBody.setRequest(request); AbstractInputBuffer<S> internalBuffer = (AbstractInputBuffer<S>) request.getInputBuffer(); internalBuffer.addActiveFilter(savedBody); } else if (actionCode == ActionCode.ASYNC_START) { asyncStateMachine.asyncStart((AsyncContextCallback) param); } else if (actionCode == ActionCode.ASYNC_DISPATCHED) { asyncStateMachine.asyncDispatched(); } else if (actionCode == ActionCode.ASYNC_TIMEOUT) { AtomicBoolean result = (AtomicBoolean) param; result.set(asyncStateMachine.asyncTimeout()); } else if (actionCode == ActionCode.ASYNC_RUN) { asyncStateMachine.asyncRun((Runnable) param); } else if (actionCode == ActionCode.ASYNC_ERROR) { asyncStateMachine.asyncError(); } else if (actionCode == ActionCode.ASYNC_IS_STARTED) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted()); } else if (actionCode == ActionCode.ASYNC_IS_DISPATCHING) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching()); } else if (actionCode == ActionCode.ASYNC_IS_ASYNC) { ((AtomicBoolean) param).set(asyncStateMachine.isAsync()); } else if (actionCode == ActionCode.ASYNC_IS_TIMINGOUT) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut()); } else if (actionCode == ActionCode.ASYNC_IS_ERROR) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError()); } else if (actionCode == ActionCode.AVAILABLE) { request.setAvailable(inputBuffer.available()); } else if (actionCode == ActionCode.NB_WRITE_INTEREST) { AtomicBoolean isReady = (AtomicBoolean)param; try { isReady.set(getOutputBuffer().isReady()); } catch (IOException e) { getLog().debug("isReady() failed", e); error = true; } } else if (actionCode == ActionCode.NB_READ_INTEREST) { registerForEvent(true, false); } else if (actionCode == ActionCode.UPGRADE) { httpUpgradeHandler = (HttpUpgradeHandler) param; // Stop further HTTP output getOutputBuffer().finished = true; } else if (actionCode == ActionCode.REQUEST_BODY_FULLY_READ) { AtomicBoolean result = (AtomicBoolean) param; result.set(getInputBuffer().isFinished()); } else { actionInternal(actionCode, param); } } abstract void actionInternal(ActionCode actionCode, Object param); /** * Processors (currently only HTTP BIO) may elect to disable HTTP keep-alive * in some circumstances. This method allows the processor implementation to * determine if keep-alive should be disabled or not. */ protected abstract boolean disableKeepAlive(); /** * Configures the timeout to be used for reading the request line. */ protected abstract void setRequestLineReadTimeout() throws IOException; /** * Defines how a connector handles an incomplete request line read. * * @return <code>true</code> if the processor should break out of the * processing loop, otherwise <code>false</code>. */ protected abstract boolean handleIncompleteRequestLineRead(); /** * Set the socket timeout. */ protected abstract void setSocketTimeout(int timeout) throws IOException; /** * Process pipelined HTTP requests using the specified input and output * streams. * * @param socketWrapper Socket from which the HTTP requests will be read * and the HTTP responses will be written. * * @throws IOException error during an I/O operation */ @Override public SocketState process(SocketWrapper<S> socketWrapper) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the I/O setSocketWrapper(socketWrapper); getInputBuffer().init(socketWrapper, endpoint); getOutputBuffer().init(socketWrapper, endpoint); // Flags error = false; keepAlive = true; comet = false; openSocket = false; sendfileInProgress = false; readComplete = true; if (endpoint.getUsePolling()) { keptAlive = false; } else { keptAlive = socketWrapper.isKeptAlive(); } if (disableKeepAlive()) { socketWrapper.setKeepAliveLeft(0); } while (!error && keepAlive && !comet && !isAsync() && httpUpgradeHandler == null && !endpoint.isPaused()) { // Parsing the request header try { setRequestLineReadTimeout(); if (!getInputBuffer().parseRequestLine(keptAlive)) { if (handleIncompleteRequestLineRead()) { break; } } if (endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); error = true; } else { // Make sure that connectors that are non-blocking during // header processing (NIO) only set the start time the first // time a request is processed. if (request.getStartTime() < 0) { request.setStartTime(System.currentTimeMillis()); } keptAlive = true; // Set this every time in case limit has been changed via JMX request.getMimeHeaders().setLimit(endpoint.getMaxHeaderCount()); // Currently only NIO will ever return false here if (!getInputBuffer().parseHeaders()) { // We've read part of the request, don't recycle it // instead associate it with the socket openSocket = true; readComplete = false; break; } if (!disableUploadTimeout) { setSocketTimeout(connectionUploadTimeout); } } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); UserDataHelper.Mode logMode = userDataHelper.getNextMode(); if (logMode != null) { String message = sm.getString( "http11processor.header.parse"); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "http11processor.fallToDebug"); //$FALL-THROUGH$ case INFO: getLog().info(message); break; case DEBUG: getLog().debug(message); } } // 400 - Bad Request response.setStatus(400); getAdapter().log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); getAdapter().log(request, response, 0); error = true; } } if (maxKeepAliveRequests == 1) { keepAlive = false; } else if (maxKeepAliveRequests > 0 && socketWrapper.decrementKeepAlive() <= 0) { keepAlive = false; } // Process the request in the adapter if (!error) { try { 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 // 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 && !error) { // Avoid checking twice. error = response.getErrorException() != null || (!isAsync() && statusDropsConnection(response.getStatus())); } setCometTimeouts(socketWrapper); } catch (InterruptedIOException e) { error = true; } catch (HeadersTooLargeException e) { error = true; // The response should not have been committed but check it // anyway to be safe if (!response.isCommitted()) { response.reset(); response.setStatus(500); response.setHeader("Connection", "close"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); error = true; } } // Finish the handling of the request rp.setStage(org.apache.coyote.Constants.STAGE_ENDINPUT); if (!isAsync() && !comet) { if (error) { // If we know we are closing the connection, don't drain // input. This way uploading a 100GB file doesn't tie up the // thread if the servlet has rejected it. getInputBuffer().setSwallowInput(false); } endRequest(); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDOUTPUT); // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); if (!isAsync() && !comet || error) { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); } if (!disableUploadTimeout) { setSocketTimeout(endpoint.getSoTimeout()); } rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); if (breakKeepAliveLoop(socketWrapper)) { break; } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || endpoint.isPaused()) { return SocketState.CLOSED; } else if (isAsync() || comet) { return SocketState.LONG; } else if (isUpgrade()) { return SocketState.UPGRADING; } else { if (sendfileInProgress) { return SocketState.SENDFILE; } else { if (openSocket) { if (readComplete) { return SocketState.OPEN; } else { return SocketState.LONG; } } else { return SocketState.CLOSED; } } } } /** * Regsiter the socket for the specified events. * * @param read Register the socket for read events * @param write Regsiter the socket for write events */ protected abstract void registerForEvent(boolean read, boolean write); /** * After reading the request headers, we have to setup the request filters. */ protected void prepareRequest() { http11 = true; http09 = false; contentDelimitation = false; expectation = false; prepareRequestInternal(); if (endpoint.isSSLEnabled()) { request.scheme().setString("https"); } MessageBytes protocolMB = request.protocol(); if (protocolMB.equals(Constants.HTTP_11)) { http11 = true; protocolMB.setString(Constants.HTTP_11); } else if (protocolMB.equals(Constants.HTTP_10)) { http11 = false; keepAlive = false; protocolMB.setString(Constants.HTTP_10); } else if (protocolMB.equals("")) { // HTTP/0.9 http09 = true; http11 = false; keepAlive = false; } else { // Unsupported protocol http11 = false; error = true; // Send 505; Unsupported HTTP version if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " Unsupported HTTP version \""+protocolMB+"\""); } response.setStatus(505); } MessageBytes methodMB = request.method(); if (methodMB.equals(Constants.GET)) { methodMB.setString(Constants.GET); } else if (methodMB.equals(Constants.POST)) { methodMB.setString(Constants.POST); } MimeHeaders headers = request.getMimeHeaders(); // Check connection header MessageBytes connectionValueMB = headers.getValue(Constants.CONNECTION); if (connectionValueMB != null) { ByteChunk connectionValueBC = connectionValueMB.getByteChunk(); if (findBytes(connectionValueBC, Constants.CLOSE_BYTES) != -1) { keepAlive = false; } else if (findBytes(connectionValueBC, Constants.KEEPALIVE_BYTES) != -1) { keepAlive = true; } } MessageBytes expectMB = null; if (http11) { expectMB = headers.getValue("expect"); } if ((expectMB != null) && (expectMB.indexOfIgnoreCase("100-continue", 0) != -1)) { getInputBuffer().setSwallowInput(false); expectation = true; } // Check user-agent header if ((restrictedUserAgents != null) && ((http11) || (keepAlive))) { MessageBytes userAgentValueMB = headers.getValue("user-agent"); // Check in the restricted list, and adjust the http11 // and keepAlive flags accordingly if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (restrictedUserAgents != null && restrictedUserAgents.matcher(userAgentValue).matches()) { http11 = false; keepAlive = false; } } } // Check for a full URI (including protocol://host:port/) ByteChunk uriBC = request.requestURI().getByteChunk(); if (uriBC.startsWithIgnoreCase("http", 0)) { int pos = uriBC.indexOf("://", 0, 3, 4); int uriBCStart = uriBC.getStart(); int slashPos = -1; if (pos != -1) { byte[] uriB = uriBC.getBytes(); slashPos = uriBC.indexOf('/', pos + 3); if (slashPos == -1) { slashPos = uriBC.getLength(); // Set URI as "/" request.requestURI().setBytes (uriB, uriBCStart + pos + 1, 1); } else { request.requestURI().setBytes (uriB, uriBCStart + slashPos, uriBC.getLength() - slashPos); } MessageBytes hostMB = headers.setValue("host"); hostMB.setBytes(uriB, uriBCStart + pos + 3, slashPos - pos - 3); } } // Input filter setup InputFilter[] inputFilters = getInputBuffer().getFilters(); // Parse transfer-encoding header MessageBytes transferEncodingValueMB = null; if (http11) { transferEncodingValueMB = headers.getValue("transfer-encoding"); } if (transferEncodingValueMB != null) { String transferEncodingValue = transferEncodingValueMB.toString(); // Parse the comma separated list. "identity" codings are ignored int startPos = 0; int commaPos = transferEncodingValue.indexOf(','); String encodingName = null; while (commaPos != -1) { encodingName = transferEncodingValue.substring (startPos, commaPos).toLowerCase(Locale.ENGLISH).trim(); if (!addInputFilter(inputFilters, encodingName)) { // Unsupported transfer encoding error = true; // 501 - Unimplemented response.setStatus(501); } startPos = commaPos + 1; commaPos = transferEncodingValue.indexOf(',', startPos); } encodingName = transferEncodingValue.substring(startPos) .toLowerCase(Locale.ENGLISH).trim(); if (!addInputFilter(inputFilters, encodingName)) { // Unsupported transfer encoding error = true; // 501 - Unimplemented if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " Unsupported transfer encoding \""+encodingName+"\""); } response.setStatus(501); } } // Parse content-length header long contentLength = request.getContentLengthLong(); if (contentLength >= 0 && !contentDelimitation) { getInputBuffer().addActiveFilter (inputFilters[Constants.IDENTITY_FILTER]); contentDelimitation = true; } MessageBytes valueMB = headers.getValue("host"); // Check host header if (http11 && (valueMB == null)) { error = true; // 400 - Bad request if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " host header missing"); } response.setStatus(400); } parseHost(valueMB); if (!contentDelimitation) { // If there's no content length // (broken HTTP/1.0 or HTTP/1.1), assume // the client is not broken and didn't send a body getInputBuffer().addActiveFilter (inputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } if (error) { getAdapter().log(request, response, 0); } } /** * Connector implementation specific request preparation. Ideally, this will * go away in the future. */ protected abstract void prepareRequestInternal(); /** * When committing the response, we have to validate the set of headers, as * well as setup the response filters. */ private void prepareResponse() { boolean entityBody = true; contentDelimitation = false; OutputFilter[] outputFilters = getOutputBuffer().getFilters(); if (http09 == true) { // HTTP/0.9 getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); return; } int statusCode = response.getStatus(); if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304) { // No entity body getOutputBuffer().addActiveFilter (outputFilters[Constants.VOID_FILTER]); entityBody = false; contentDelimitation = true; } MessageBytes methodMB = request.method(); if (methodMB.equals("HEAD")) { // No entity body getOutputBuffer().addActiveFilter (outputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } // Sendfile support boolean sendingWithSendfile = false; if (getEndpoint().getUseSendfile()) { sendingWithSendfile = prepareSendfile(outputFilters); } // Check for compression boolean isCompressable = false; boolean useCompression = false; if (entityBody && (compressionLevel > 0) && !sendingWithSendfile) { isCompressable = isCompressable(); if (isCompressable) { useCompression = useCompression(); } // Change content-length to -1 to force chunking if (useCompression) { response.setContentLength(-1); } } MimeHeaders headers = response.getMimeHeaders(); if (!entityBody) { response.setContentLength(-1); } // A SC_NO_CONTENT response may include entity headers if (entityBody || statusCode == HttpServletResponse.SC_NO_CONTENT) { String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language") .setString(contentLanguage); } } long contentLength = response.getContentLengthLong(); boolean connectionClosePresent = false; if (contentLength != -1) { headers.setValue("Content-Length").setLong(contentLength); getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); contentDelimitation = true; } else { // If the response code supports an entity body and we're on // HTTP 1.1 then we chunk unless we have a Connection: close header connectionClosePresent = isConnectionClose(headers); if (entityBody && http11 && !connectionClosePresent) { getOutputBuffer().addActiveFilter (outputFilters[Constants.CHUNKED_FILTER]); contentDelimitation = true; headers.addValue(Constants.TRANSFERENCODING).setString(Constants.CHUNKED); } else { getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); } } if (useCompression) { getOutputBuffer().addActiveFilter(outputFilters[Constants.GZIP_FILTER]); headers.setValue("Content-Encoding").setString("gzip"); } // If it might be compressed, set the Vary header if (isCompressable) { // Make Proxies happy via Vary (from mod_deflate) MessageBytes vary = headers.getValue("Vary"); if (vary == null) { // Add a new Vary header headers.setValue("Vary").setString("Accept-Encoding"); } else if (vary.equals("*")) { // No action required } else { // Merge into current header headers.setValue("Vary").setString( vary.getString() + ",Accept-Encoding"); } } // Add date header headers.setValue("Date").setString(FastHttpDateFormat.getCurrentDate()); // FIXME: Add transfer encoding header if ((entityBody) && (!contentDelimitation)) { // Mark as close the connection after the request, and add the // connection: close header keepAlive = false; } // If we know that the request is bad this early, add the // Connection: close header. keepAlive = keepAlive && !statusDropsConnection(statusCode); if (!keepAlive) { // Avoid adding the close header twice if (!connectionClosePresent) { headers.addValue(Constants.CONNECTION).setString( Constants.CLOSE); } } else if (!http11 && !error) { headers.addValue(Constants.CONNECTION).setString(Constants.KEEPALIVE); } // Build the response header getOutputBuffer().sendStatus(); // Add server header if (server != null) { // Always overrides anything the app might set headers.setValue("Server").setString(server); } else if (headers.getValue("Server") == null) { // If app didn't set the header, use the default getOutputBuffer().write(Constants.SERVER_BYTES); } int size = headers.size(); for (int i = 0; i < size; i++) { getOutputBuffer().sendHeader(headers.getName(i), headers.getValue(i)); } getOutputBuffer().endHeaders(); } private boolean isConnectionClose(MimeHeaders headers) { MessageBytes connection = headers.getValue(Constants.CONNECTION); if (connection == null) { return false; } return connection.equals(Constants.CLOSE); } abstract boolean prepareSendfile(OutputFilter[] outputFilters); /** * Parse host. */ protected void parseHost(MessageBytes valueMB) { if (valueMB == null || valueMB.isNull()) { // HTTP/1.0 // If no host header, use the port info from the endpoint // The host will be obtained lazily from the socket if required // using ActionCode#REQ_LOCAL_NAME_ATTRIBUTE request.setServerPort(endpoint.getPort()); return; } ByteChunk valueBC = valueMB.getByteChunk(); byte[] valueB = valueBC.getBytes(); int valueL = valueBC.getLength(); int valueS = valueBC.getStart(); int colonPos = -1; if (hostNameC.length < valueL) { hostNameC = new char[valueL]; } boolean ipv6 = (valueB[valueS] == '['); boolean bracketClosed = false; for (int i = 0; i < valueL; i++) { char b = (char) valueB[i + valueS]; hostNameC[i] = b; if (b == ']') { bracketClosed = true; } else if (b == ':') { if (!ipv6 || bracketClosed) { colonPos = i; break; } } } if (colonPos < 0) { if (!endpoint.isSSLEnabled()) { // 80 - Default HTTP port request.setServerPort(80); } else { // 443 - Default HTTPS port request.setServerPort(443); } request.serverName().setChars(hostNameC, 0, valueL); } else { request.serverName().setChars(hostNameC, 0, colonPos); int port = 0; int mult = 1; for (int i = valueL - 1; i > colonPos; i--) { int charValue = HexUtils.getDec(valueB[i + valueS]); if (charValue == -1 || charValue > 9) { // Invalid character error = true; // 400 - Bad request response.setStatus(400); break; } port = port + (charValue * mult); mult = 10 * mult; } request.setServerPort(port); } } @Override public SocketState asyncDispatch(SocketStatus status) { if (status == SocketStatus.OPEN_WRITE) { try { asyncStateMachine.asyncOperation(); try { if (outputBuffer.hasDataToWrite()) { if (outputBuffer.flushBuffer(false)) { // There is data to write but go via Response to // maintain a consistent view of non-blocking state response.checkRegisterForWrite(true); return SocketState.LONG; } } } catch (IOException x) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to write async data.",x); } status = SocketStatus.ASYNC_WRITE_ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, x); } } catch (IllegalStateException x) { registerForEvent(false, true); } } else if (status == SocketStatus.OPEN_READ && request.getReadListener() != null) { try { try { if (inputBuffer.nbRead() > 0) { asyncStateMachine.asyncOperation(); } } catch (IOException x) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to read async data.",x); } status = SocketStatus.ASYNC_READ_ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, x); } } catch (IllegalStateException x) { registerForEvent(true, false); } } RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !getAdapter().asyncDispatch(request, response, status); resetTimeouts(); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; } finally { if (error) { // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (isAsync()) { return SocketState.LONG; } else { if (!keepAlive) { return SocketState.CLOSED; } else { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); return SocketState.OPEN; } } } @Override public boolean isComet() { return comet; } @Override public boolean isUpgrade() { return httpUpgradeHandler != null; } @Override public SocketState upgradeDispatch(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("http11Processor.upgrade")); } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { return httpUpgradeHandler; } /** * Provides a mechanism for those connector implementations (currently only * NIO) that need to reset timeouts from Async timeouts to standard HTTP * timeouts once async processing completes. */ protected abstract void resetTimeouts(); /** * Provides a mechanism for those connectors (currently only NIO) that need * that need to set comet timeouts. */ protected abstract void setCometTimeouts(SocketWrapper<S> socketWrapper); public void endRequest() { // Finish the handling of the request try { getInputBuffer().endRequest(); } catch (IOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; } try { getOutputBuffer().endRequest(); } catch (IOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; } } /** * Checks to see if the keep-alive loop should be broken, performing any * processing (e.g. sendfile handling) that may have an impact on whether * or not the keep-alive loop should be broken. * @return true if the keep-alive loop should be broken */ protected abstract boolean breakKeepAliveLoop( SocketWrapper<S> socketWrapper); @Override public final void recycle(boolean isSocketClosing) { if (getInputBuffer() != null) { getInputBuffer().recycle(); } if (getOutputBuffer() != null) { getOutputBuffer().recycle(); } if (asyncStateMachine != null) { asyncStateMachine.recycle(); } httpUpgradeHandler = null; comet = false; recycleInternal(); } protected abstract void recycleInternal(); }
55,181
Bug 55181 Ping and Pong messages should have identical application data
null
resolved fixed
19c0bd3
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T08:26:28Z
2013-07-02T13:00:00Z
java/org/apache/tomcat/websocket/WsPongMessage.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.nio.ByteBuffer; import javax.websocket.PongMessage; public class WsPongMessage implements PongMessage { private final ByteBuffer applicationData; public WsPongMessage(ByteBuffer applicationData) { this.applicationData = applicationData; } @Override public ByteBuffer getApplicationData() { return applicationData; } }
55,181
Bug 55181 Ping and Pong messages should have identical application data
null
resolved fixed
19c0bd3
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T08:26:28Z
2013-07-02T13:00:00Z
test/org/apache/tomcat/websocket/TestWsPingPongMessages.java
55,165
Bug 55165 subprotocols not available with annotated serverendpoint
null
resolved fixed
b069c78
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T09:40:26Z
2013-07-01T00:53:20Z
java/org/apache/tomcat/websocket/server/WsServerContainer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.server; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.Map; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.DispatcherType; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.DeploymentException; import javax.websocket.Encoder; import javax.websocket.Endpoint; import javax.websocket.server.ServerContainer; import javax.websocket.server.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; import javax.websocket.server.ServerEndpointConfig.Configurator; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.WsSession; import org.apache.tomcat.websocket.WsWebSocketContainer; import org.apache.tomcat.websocket.pojo.PojoEndpointServer; import org.apache.tomcat.websocket.pojo.PojoMethodMapping; /** * Provides a per class loader (i.e. per web application) instance of a * ServerContainer. Web application wide defaults may be configured by setting * the following servlet context initialisation parameters to the desired * values. * <ul> * <li>{@link Constants#BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li> * <li>{@link Constants#TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM}</li> * </ul> */ public class WsServerContainer extends WsWebSocketContainer implements ServerContainer { // Needs to be a WeakHashMap to prevent memory leaks when a context is // stopped private static final Map<ClassLoader,WsServerContainer> classLoaderContainerMap = new WeakHashMap<>(); private static final Object classLoaderContainerMapLock = new Object(); private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final CloseReason AUTHENTICATED_HTTP_SESSION_CLOSED = new CloseReason(CloseCodes.VIOLATED_POLICY, "This connection was established under an authenticated " + "HTTP session that has ended."); public static WsServerContainer getServerContainer() { ClassLoader tccl = Thread.currentThread().getContextClassLoader(); WsServerContainer result = null; synchronized (classLoaderContainerMapLock) { result = classLoaderContainerMap.get(tccl); if (result == null) { result = new WsServerContainer(); classLoaderContainerMap.put(tccl, result); } } return result; } // For unit testing protected static void recycle() { synchronized (classLoaderContainerMapLock) { classLoaderContainerMap.clear(); } } private final WsWriteTimeout wsWriteTimeout = new WsWriteTimeout(); private volatile ServletContext servletContext = null; private final Map<String,ServerEndpointConfig> configExactMatchMap = new ConcurrentHashMap<>(); private final ConcurrentHashMap<Integer,SortedSet<TemplatePathMatch>> configTemplateMatchMap = new ConcurrentHashMap<>(); private volatile boolean addAllowed = true; private final ConcurrentHashMap<String,Set<WsSession>> authenticatedSessions = new ConcurrentHashMap<>(); private WsServerContainer() { // Hide default constructor } public void setServletContext(ServletContext servletContext) { if (this.servletContext == servletContext) { return; } this.servletContext = servletContext; // Configure servlet context wide defaults String value = servletContext.getInitParameter( Constants.BINARY_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM); if (value != null) { setDefaultMaxBinaryMessageBufferSize(Integer.parseInt(value)); } value = servletContext.getInitParameter( Constants.TEXT_BUFFER_SIZE_SERVLET_CONTEXT_INIT_PARAM); if (value != null) { setDefaultMaxTextMessageBufferSize(Integer.parseInt(value)); } FilterRegistration fr = servletContext.addFilter( WsFilter.class.getName(), WsFilter.class); EnumSet<DispatcherType> types = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD); fr.addMappingForUrlPatterns(types, true, "/*"); } /** * Published the provided endpoint implementation at the specified path with * the specified configuration. {@link #setServletContext(ServletContext)} * must be called before calling this method. * * @param sec The configuration to use when creating endpoint instances * @throws DeploymentException */ @Override public void addEndpoint(ServerEndpointConfig sec) throws DeploymentException { if (!addAllowed) { throw new DeploymentException( sm.getString("serverContainer.addNotAllowed")); } if (servletContext == null) { throw new DeploymentException( sm.getString("serverContainer.servletContextMissing")); } String path = sec.getPath(); UriTemplate uriTemplate = new UriTemplate(path); if (uriTemplate.hasParameters()) { Integer key = Integer.valueOf(uriTemplate.getSegmentCount()); SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key); if (templateMatches == null) { // Ensure that if concurrent threads execute this block they // both end up using the same TreeSet instance templateMatches = new TreeSet<>( TemplatePathMatchComparator.getInstance()); configTemplateMatchMap.putIfAbsent(key, templateMatches); templateMatches = configTemplateMatchMap.get(key); } if (!templateMatches.add(new TemplatePathMatch(sec, uriTemplate))) { // Duplicate uriTemplate; throw new DeploymentException( sm.getString("serverContainer.duplicatePaths", path)); } } else { // Exact match ServerEndpointConfig old = configExactMatchMap.put(path, sec); if (old != null) { // Duplicate path mappings throw new DeploymentException( sm.getString("serverContainer.duplicatePaths", path)); } } } /** * Provides the equivalent of {@link #addEndpoint(ServerEndpointConfig)} * for publishing plain old java objects (POJOs) that have been annotated as * WebSocket endpoints. * * @param pojo The annotated POJO */ @Override public void addEndpoint(Class<?> pojo) throws DeploymentException { ServerEndpoint annotation = pojo.getAnnotation(ServerEndpoint.class); if (annotation == null) { throw new DeploymentException( sm.getString("serverContainer.missingAnnotation", pojo.getName())); } String path = annotation.value(); // Validate encoders validateEncoders(annotation.encoders()); // Method mapping PojoMethodMapping methodMapping = new PojoMethodMapping(pojo, annotation.decoders(), path); // ServerEndpointConfig ServerEndpointConfig sec; Class<? extends Configurator> configuratorClazz = annotation.configurator(); Configurator configurator = null; if (!configuratorClazz.equals(Configurator.class)) { try { configurator = annotation.configurator().newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "serverContainer.configuratorFail", annotation.configurator().getName(), pojo.getClass().getName()), e); } } sec = ServerEndpointConfig.Builder.create(pojo, path). decoders(Arrays.asList(annotation.decoders())). encoders(Arrays.asList(annotation.encoders())). configurator(configurator). build(); sec.getUserProperties().put( PojoEndpointServer.POJO_METHOD_MAPPING_KEY, methodMapping); addEndpoint(sec); } public WsMappingResult findMapping(String path) { // Prevent registering additional endpoints once the first attempt has // been made to use one if (addAllowed) { addAllowed = false; } // Check an exact match. Simple case as there are no templates. ServerEndpointConfig sec = configExactMatchMap.get(path); if (sec != null) { return new WsMappingResult(sec, Collections.EMPTY_MAP); } // No exact match. Need to look for template matches. UriTemplate pathUriTemplate = null; try { pathUriTemplate = new UriTemplate(path); } catch (DeploymentException e) { // Path is not valid so can't be matched to a WebSocketEndpoint return null; } // Number of segments has to match Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount()); SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key); if (templateMatches == null) { // No templates with an equal number of segments so there will be // no matches return null; } // List is in alphabetical order of normalised templates. // Correct match is the first one that matches. Map<String,String> pathParams = null; for (TemplatePathMatch templateMatch : templateMatches) { pathParams = templateMatch.getUriTemplate().match(pathUriTemplate); if (pathParams != null) { sec = templateMatch.getConfig(); break; } } if (sec == null) { // No match return null; } if (!PojoEndpointServer.class.isAssignableFrom(sec.getEndpointClass())) { // Need to make path params available to POJO sec.getUserProperties().put( PojoEndpointServer.POJO_PATH_PARAM_KEY, pathParams); } return new WsMappingResult(sec, pathParams); } protected WsWriteTimeout getTimeout() { return wsWriteTimeout; } /** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void registerSession(Endpoint endpoint, WsSession wsSession) { super.registerSession(endpoint, wsSession); if (wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) { registerAuthenticatedSession(wsSession, wsSession.getHttpSessionId()); } } /** * {@inheritDoc} * * Overridden to make it visible to other classes in this package. */ @Override protected void unregisterSession(Endpoint endpoint, WsSession wsSession) { if (wsSession.getUserPrincipal() != null && wsSession.getHttpSessionId() != null) { unregisterAuthenticatedSession(wsSession, wsSession.getHttpSessionId()); } super.unregisterSession(endpoint, wsSession); } private void registerAuthenticatedSession(WsSession wsSession, String httpSessionId) { Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId); if (wsSession == null) { wsSessions = Collections.newSetFromMap( new ConcurrentHashMap<WsSession,Boolean>()); authenticatedSessions.putIfAbsent(httpSessionId, wsSessions); wsSessions = authenticatedSessions.get(httpSessionId); } wsSessions.add(wsSession); } private void unregisterAuthenticatedSession(WsSession wsSession, String httpSessionId) { Set<WsSession> wsSessions = authenticatedSessions.get(httpSessionId); wsSessions.remove(wsSession); } public void closeAuthenticatedSession(String httpSessionId) { Set<WsSession> wsSessions = authenticatedSessions.remove(httpSessionId); for (WsSession wsSession : wsSessions) { try { wsSession.close(AUTHENTICATED_HTTP_SESSION_CLOSED); } catch (IOException e) { // Any IOExceptions during close will have been caught and the // onError method called. } } } private static void validateEncoders(Class<? extends Encoder>[] encoders) throws DeploymentException { for (Class<? extends Encoder> encoder : encoders) { // Need to instantiate decoder to ensure it is valid and that // deployment can be failed if it is not @SuppressWarnings("unused") Encoder instance; try { encoder.newInstance(); } catch(InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "serverContainer.encoderFail", encoder.getName()), e); } } } private static class TemplatePathMatch { private final ServerEndpointConfig config; private final UriTemplate uriTemplate; public TemplatePathMatch(ServerEndpointConfig config, UriTemplate uriTemplate) { this.config = config; this.uriTemplate = uriTemplate; } public ServerEndpointConfig getConfig() { return config; } public UriTemplate getUriTemplate() { return uriTemplate; } } /** * This Comparator implementation is thread-safe so only create a single * instance. */ private static class TemplatePathMatchComparator implements Comparator<TemplatePathMatch> { private static final TemplatePathMatchComparator INSTANCE = new TemplatePathMatchComparator(); public static TemplatePathMatchComparator getInstance() { return INSTANCE; } private TemplatePathMatchComparator() { // Hide default constructor } @Override public int compare(TemplatePathMatch tpm1, TemplatePathMatch tpm2) { return tpm1.getUriTemplate().getNormalizedPath().compareTo( tpm2.getUriTemplate().getNormalizedPath()); } } }
55,183
Bug 55183 Missing WS Protocol Header in session negotiatedHeaders
null
resolved fixed
a634d85
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T16:13:13Z
2013-07-02T15:46:40Z
java/org/apache/tomcat/websocket/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; /** * Internal implementation constants. */ public class Constants { protected static final String PACKAGE_NAME = Constants.class.getPackage().getName(); // OP Codes public static final byte OPCODE_CONTINUATION = 0x00; public static final byte OPCODE_TEXT = 0x01; public static final byte OPCODE_BINARY = 0x02; public static final byte OPCODE_CLOSE = 0x08; public static final byte OPCODE_PING = 0x09; public static final byte OPCODE_PONG = 0x0A; // Internal OP Codes // RFC 6455 limits OP Codes to 4 bits so these should never clash // Always set bit 4 so these will be treated as control codes static final byte INTERNAL_OPCODE_FLUSH = 0x18; // Buffers static final int DEFAULT_BUFFER_SIZE = 8 * 1024; // Client connection public static final String HOST_HEADER_NAME = "Host"; public static final String UPGRADE_HEADER_NAME = "Upgrade"; public static final String UPGRADE_HEADER_VALUE = "websocket"; public static final String CONNECTION_HEADER_NAME = "Connection"; public static final String CONNECTION_HEADER_VALUE = "upgrade"; public static final String WS_VERSION_HEADER_NAME = "Sec-WebSocket-Version"; public static final String WS_VERSION_HEADER_VALUE = "13"; public static final String WS_KEY_HEADER_NAME = "Sec-WebSocket-Key"; public static final String WS_PROTOCOL_HEADER_NAME = "Sec-WebSocket-Protocol"; public static final String WS_EXTENSIONS_HEADER_NAME = "Sec-WebSocket-Extensions"; private Constants() { // Hide default constructor } }
55,183
Bug 55183 Missing WS Protocol Header in session negotiatedHeaders
null
resolved fixed
a634d85
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T16:13:13Z
2013-07-02T15:46:40Z
java/org/apache/tomcat/websocket/WsWebSocketContainer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousSocketChannel; import java.nio.charset.Charset; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; import javax.websocket.ClientEndpoint; import javax.websocket.ClientEndpointConfig; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.HandshakeResponse; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.codec.binary.Base64; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.util.threads.ThreadPoolExecutor; import org.apache.tomcat.websocket.pojo.PojoEndpointClient; public class WsWebSocketContainer implements WebSocketContainer, BackgroundProcess { /** * Property name to set to configure the value that is passed to * {@link SSLEngine#setEnabledProtocols(String[])}. The value should be a * comma separated string. */ public static final String SSL_PROTOCOLS_PROPERTY = "org.apache.tomcat.websocket.SSL_PROTOCOLS"; public static final String SSL_TRUSTSTORE_PROPERTY = "org.apache.tomcat.websocket.SSL_TRUSTSTORE"; public static final String SSL_TRUSTSTORE_PWD_PROPERTY = "org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD"; public static final String SSL_TRUSTSTORE_PWD_DEFAULT = "changeit"; private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final Random random = new Random(); private static final Charset iso88591 = Charset.forName("ISO-8859-1"); private static final byte[] crlf = new byte[] {13, 10}; private static final AsynchronousChannelGroup asynchronousChannelGroup; static { AsynchronousChannelGroup result = null; // Need to do this with the right thread context class loader else the // first web app to call this will trigger a leak ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( AsyncIOThreadFactory.class.getClassLoader()); // These are the same settings as the default // AsynchronousChannelGroup int initialSize = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new AsyncIOThreadFactory()); try { result = AsynchronousChannelGroup.withCachedThreadPool( executorService, initialSize); } catch (IOException e) { // No good reason for this to happen. throw new IllegalStateException(sm.getString( "wsWebSocketContainer.asynchronousChannelGroupFail")); } } finally { Thread.currentThread().setContextClassLoader(original); } asynchronousChannelGroup = result; } private final Log log = LogFactory.getLog(WsWebSocketContainer.class); private final Map<Class<?>, Set<WsSession>> endpointSessionMap = new HashMap<>(); private final Map<WsSession,WsSession> sessions = new ConcurrentHashMap<>(); private final Object endPointSessionMapLock = new Object(); private long defaultAsyncTimeout = -1; private int maxBinaryMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private int maxTextMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private volatile long defaultMaxSessionIdleTimeout = 0; private int backgroundProcessCount = 0; private int processPeriod = 10; @Override public Session connectToServer(Object pojo, URI path) throws DeploymentException { ClientEndpoint annotation = pojo.getClass().getAnnotation(ClientEndpoint.class); if (annotation == null) { throw new DeploymentException( sm.getString("wsWebSocketContainer.missingAnnotation", pojo.getClass().getName())); } Endpoint ep = new PojoEndpointClient(pojo, annotation.decoders()); Class<? extends ClientEndpointConfig.Configurator> configuratorClazz = pojo.getClass().getAnnotation( ClientEndpoint.class).configurator(); ClientEndpointConfig.Configurator configurator = null; if (!ClientEndpointConfig.Configurator.class.equals( configuratorClazz)) { try { configurator = configuratorClazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.defaultConfiguratorFail"), e); } } ClientEndpointConfig config = ClientEndpointConfig.Builder.create(). configurator(configurator). decoders(Arrays.asList(annotation.decoders())). encoders(Arrays.asList(annotation.encoders())). build(); return connectToServer(ep, config, path); } @Override public Session connectToServer(Class<?> annotatedEndpointClass, URI path) throws DeploymentException { Object pojo; try { pojo = annotatedEndpointClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", annotatedEndpointClass.getName()), e); } return connectToServer(pojo, path); } @Override public Session connectToServer(Class<? extends Endpoint> clazz, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { Endpoint endpoint; try { endpoint = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", clazz.getName()), e); } return connectToServer(endpoint, clientEndpointConfiguration, path); } @Override public Session connectToServer(Endpoint endpoint, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { boolean secure = false; String scheme = path.getScheme(); if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme))) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.pathWrongScheme", scheme)); } String host = path.getHost(); if (host == null) { throw new DeploymentException( sm.getString("wsWebSocketContainer.pathNoHost")); } int port = path.getPort(); Map<String,List<String>> reqHeaders = createRequestHeaders(host, port, clientEndpointConfiguration.getPreferredSubprotocols(), clientEndpointConfiguration.getExtensions()); clientEndpointConfiguration.getConfigurator(). beforeRequest(reqHeaders); ByteBuffer request = createRequest(path, reqHeaders); SocketAddress sa; if (port == -1) { if ("ws".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 80); } else if ("wss".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 443); secure = true; } else { throw new DeploymentException( sm.getString("wsWebSocketContainer.invalidScheme")); } } else { if ("wss".equalsIgnoreCase(scheme)) { secure = true; } sa = new InetSocketAddress(host, port); } AsynchronousSocketChannel socketChannel; try { socketChannel = AsynchronousSocketChannel.open(asynchronousChannelGroup); } catch (IOException ioe) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.asynchronousSocketChannelFail"), ioe); } Future<Void> fConnect = socketChannel.connect(sa); AsyncChannelWrapper channel; if (secure) { SSLEngine sslEngine = createSSLEngine( clientEndpointConfiguration.getUserProperties()); channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine); } else { channel = new AsyncChannelWrapperNonSecure(socketChannel); } ByteBuffer response; String subProtocol; try { fConnect.get(); Future<Void> fHandshake = channel.handshake(); fHandshake.get(); int toWrite = request.limit(); Future<Integer> fWrite = channel.write(request); Integer thisWrite = fWrite.get(); toWrite -= thisWrite.intValue(); while (toWrite > 0) { fWrite = channel.write(request); thisWrite = fWrite.get(); toWrite -= thisWrite.intValue(); } // Same size as the WsFrame input buffer response = ByteBuffer.allocate(maxBinaryMessageBufferSize); HandshakeResponse handshakeResponse = processResponse(response, channel); clientEndpointConfiguration.getConfigurator(). afterResponse(handshakeResponse); // Sub-protocol List<String> values = handshakeResponse.getHeaders().get( Constants.WS_PROTOCOL_HEADER_NAME); if (values == null || values.size() == 0) { subProtocol = null; } else if (values.size() == 1) { subProtocol = values.get(0); } else { throw new DeploymentException( sm.getString("Sec-WebSocket-Protocol")); } } catch (ExecutionException | InterruptedException | SSLException | EOFException e) { throw new DeploymentException( sm.getString("wsWebSocketContainer.httpRequestFailed"), e); } // Switch to WebSocket WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel); WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient, this, null, null, null, null, null, subProtocol, Collections.EMPTY_MAP, false, clientEndpointConfiguration); endpoint.onOpen(wsSession, clientEndpointConfiguration); registerSession(endpoint, wsSession); // Object creation will trigger input processing @SuppressWarnings("unused") WsFrameClient wsFrameClient = new WsFrameClient(response, channel, wsSession); return wsSession; } protected void registerSession(Endpoint endpoint, WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); if (!wsSession.isOpen()) { // The session was closed during onOpen. No need to register it. return; } synchronized (endPointSessionMapLock) { if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().register(this); } Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions == null) { wsSessions = new HashSet<>(); endpointSessionMap.put(endpointClazz, wsSessions); } wsSessions.add(wsSession); } sessions.put(wsSession, wsSession); } protected void unregisterSession(Endpoint endpoint, WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpointClazz); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); } Set<Session> getOpenSessions(Class<?> endpoint) { HashSet<Session> result = new HashSet<>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; } private Map<String,List<String>> createRequestHeaders(String host, int port, List<String> subProtocols, List<Extension> extensions) { Map<String,List<String>> headers = new HashMap<>(); // Host header List<String> hostValues = new ArrayList<>(1); if (port == -1) { hostValues.add(host); } else { hostValues.add(host + ':' + port); } headers.put(Constants.HOST_HEADER_NAME, hostValues); // Upgrade header List<String> upgradeValues = new ArrayList<>(1); upgradeValues.add(Constants.UPGRADE_HEADER_VALUE); headers.put(Constants.UPGRADE_HEADER_NAME, upgradeValues); // Connection header List<String> connectionValues = new ArrayList<>(1); connectionValues.add(Constants.CONNECTION_HEADER_VALUE); headers.put(Constants.CONNECTION_HEADER_NAME, connectionValues); // WebSocket version header List<String> wsVersionValues = new ArrayList<>(1); wsVersionValues.add(Constants.WS_VERSION_HEADER_VALUE); headers.put(Constants.WS_VERSION_HEADER_NAME, wsVersionValues); // WebSocket key List<String> wsKeyValues = new ArrayList<>(1); wsKeyValues.add(generateWsKeyValue()); headers.put(Constants.WS_KEY_HEADER_NAME, wsKeyValues); // WebSocket sub-protocols if (subProtocols != null && subProtocols.size() > 0) { headers.put(Constants.WS_PROTOCOL_HEADER_NAME, subProtocols); } // WebSocket extensions if (extensions != null && extensions.size() > 0) { headers.put(Constants.WS_EXTENSIONS_HEADER_NAME, generateExtensionHeaders(extensions)); } return headers; } private List<String> generateExtensionHeaders(List<Extension> extensions) { List<String> result = new ArrayList<>(extensions.size()); for (Extension extension : extensions) { StringBuilder header = new StringBuilder(); header.append(extension.getName()); for (Extension.Parameter param : extension.getParameters()) { header.append(';'); header.append(param.getName()); String value = param.getValue(); if (value != null && value.length() > 0) { header.append('='); header.append(value); } } } return result; } private String generateWsKeyValue() { byte[] keyBytes = new byte[16]; random.nextBytes(keyBytes); return Base64.encodeBase64String(keyBytes); } private ByteBuffer createRequest(URI uri, Map<String,List<String>> reqHeaders) { ByteBuffer result = ByteBuffer.allocate(4 * 1024); // Request line result.put("GET ".getBytes(iso88591)); result.put(uri.getRawPath().getBytes(iso88591)); String query = uri.getRawQuery(); if (query != null) { result.put((byte) '?'); result.put(query.getBytes(iso88591)); } result.put(" HTTP/1.1\r\n".getBytes(iso88591)); // Headers Iterator<Entry<String,List<String>>> iter = reqHeaders.entrySet().iterator(); while (iter.hasNext()) { Entry<String,List<String>> entry = iter.next(); addHeader(result, entry.getKey(), entry.getValue()); } // Terminating CRLF result.put(crlf); result.flip(); return result; } private void addHeader(ByteBuffer result, String key, List<String> values) { StringBuilder sb = new StringBuilder(); Iterator<String> iter = values.iterator(); if (!iter.hasNext()) { return; } sb.append(iter.next()); while (iter.hasNext()) { sb.append(','); sb.append(iter.next()); } result.put(key.getBytes(iso88591)); result.put(": ".getBytes(iso88591)); result.put(sb.toString().getBytes(iso88591)); result.put(crlf); } /** * Process response, blocking until HTTP response has been fully received. * @throws ExecutionException * @throws InterruptedException * @throws DeploymentException */ private HandshakeResponse processResponse(ByteBuffer response, AsyncChannelWrapper channel) throws InterruptedException, ExecutionException, DeploymentException, EOFException { Map<String,List<String>> headers = new HashMap<>(); boolean readStatus = false; boolean readHeaders = false; String line = null; while (!readHeaders) { // Blocking read Future<Integer> read = channel.read(response); Integer bytesRead = read.get(); if (bytesRead.intValue() == -1) { throw new EOFException(); } response.flip(); while (response.hasRemaining() && !readHeaders) { if (line == null) { line = readLine(response); } else { line += readLine(response); } if ("\r\n".equals(line)) { readHeaders = true; } else if (line.endsWith("\r\n")) { if (readStatus) { parseHeaders(line, headers); } else { parseStatus(line); readStatus = true; } line = null; } } } return new WsHandshakeResponse(headers); } private void parseStatus(String line) throws DeploymentException { // This client only understands HTTP 1.1 // RFC2616 is case specific if (!line.startsWith("HTTP/1.1 101")) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus", line)); } } private void parseHeaders(String line, Map<String,List<String>> headers) { // Treat headers as single values by default. int index = line.indexOf(':'); if (index == -1) { log.warn(sm.getString("wsWebSocketContainer.invalidHeader", line)); return; } String headerName = line.substring(0, index).trim().toLowerCase(); // TODO handle known multi-value headers String headerValue = line.substring(index + 1).trim(); List<String> values = headers.get(headerName); if (values == null) { values = new ArrayList<>(1); headers.put(headerName, values); } values.add(headerValue); } private String readLine(ByteBuffer response) { // All ISO-8859-1 StringBuilder sb = new StringBuilder(); char c = 0; while (response.hasRemaining()) { c = (char) response.get(); sb.append(c); if (c == 10) { break; } } return sb.toString(); } private SSLEngine createSSLEngine(Map<String,Object> userProperties) throws DeploymentException { try { // Create the SSL Context SSLContext sslContext = SSLContext.getInstance("TLS"); // Trust store String sslTrustStoreValue = (String) userProperties.get(SSL_TRUSTSTORE_PROPERTY); if (sslTrustStoreValue != null) { String sslTrustStorePwdValue = (String) userProperties.get( SSL_TRUSTSTORE_PWD_PROPERTY); if (sslTrustStorePwdValue == null) { sslTrustStorePwdValue = SSL_TRUSTSTORE_PWD_DEFAULT; } File keyStoreFile = new File(sslTrustStoreValue); KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream is = new FileInputStream(keyStoreFile)) { ks.load(is, sslTrustStorePwdValue.toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(), null); } else { sslContext.init(null, null, null); } SSLEngine engine = sslContext.createSSLEngine(); String sslProtocolsValue = (String) userProperties.get(SSL_PROTOCOLS_PROPERTY); if (sslProtocolsValue != null) { engine.setEnabledProtocols(sslProtocolsValue.split(",")); } engine.setUseClientMode(true); return engine; } catch (Exception e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.sslEngineFail"), e); } } @Override public long getDefaultMaxSessionIdleTimeout() { return defaultMaxSessionIdleTimeout; } @Override public void setDefaultMaxSessionIdleTimeout(long timeout) { this.defaultMaxSessionIdleTimeout = timeout; } @Override public int getDefaultMaxBinaryMessageBufferSize() { return maxBinaryMessageBufferSize; } @Override public void setDefaultMaxBinaryMessageBufferSize(int max) { maxBinaryMessageBufferSize = max; } @Override public int getDefaultMaxTextMessageBufferSize() { return maxTextMessageBufferSize; } @Override public void setDefaultMaxTextMessageBufferSize(int max) { maxTextMessageBufferSize = max; } /** * {@inheritDoc} * * Currently, this implementation does not support any extensions. */ @Override public Set<Extension> getInstalledExtensions() { return Collections.EMPTY_SET; } /** * {@inheritDoc} * * The default value for this implementation is -1. */ @Override public long getDefaultAsyncSendTimeout() { return defaultAsyncTimeout; } /** * {@inheritDoc} * * The default value for this implementation is -1. */ @Override public void setAsyncSendTimeout(long timeout) { this.defaultAsyncTimeout = timeout; } // ----------------------------------------------- BackgroundProcess methods @Override public void backgroundProcess() { // This method gets called once a second. backgroundProcessCount ++; if (backgroundProcessCount >= processPeriod) { backgroundProcessCount = 0; for (WsSession wsSession : sessions.keySet()) { wsSession.expire(); } } } @Override public void setProcessPeriod(int period) { this.processPeriod = period; } /** * {@inheritDoc} * * The default value is 10 which means session expirations are processed * every 10 seconds. */ @Override public int getProcessPeriod() { return processPeriod; } /** * Create threads for AsyncIO that have the right context class loader to * prevent memory leaks. */ private static class AsyncIOThreadFactory implements ThreadFactory { private AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("WebSocketClient-AsyncIO-" + count.incrementAndGet()); t.setContextClassLoader(this.getClass().getClassLoader()); t.setDaemon(true); return t; } } }
55,183
Bug 55183 Missing WS Protocol Header in session negotiatedHeaders
null
resolved fixed
a634d85
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T16:13:13Z
2013-07-02T15:46:40Z
test/org/apache/tomcat/websocket/TestWsSubprotocols.java
55,184
Bug 55184 NPE in PojoMethodMapping getMessageHandler
null
resolved fixed
a267dbf
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-02T16:45:16Z
2013-07-02T18:33:20Z
java/org/apache/tomcat/websocket/pojo/PojoMethodMapping.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.pojo; import java.io.InputStream; import java.io.Reader; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.websocket.CloseReason; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.DeploymentException; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.OnClose; import javax.websocket.OnError; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.PongMessage; import javax.websocket.Session; import javax.websocket.server.PathParam; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.DecoderEntry; import org.apache.tomcat.websocket.Util; import org.apache.tomcat.websocket.Util.DecoderMatch; /** * For a POJO class annotated with * {@link javax.websocket.server.ServerEndpoint}, an instance of this class * creates and caches the method handler, method information and parameter * information for the onXXX calls. */ public class PojoMethodMapping { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final Method onOpen; private final Method onClose; private final Method onError; private final PojoPathParam[] onOpenParams; private final PojoPathParam[] onCloseParams; private final PojoPathParam[] onErrorParams; private final Set<MessageHandlerInfo> onMessage = new HashSet<>(); private final String wsPath; public PojoMethodMapping(Class<?> clazzPojo, Class<? extends Decoder>[] decoderClazzes, String wsPath) throws DeploymentException { this.wsPath = wsPath; List<DecoderEntry> decoders = Util.getDecoders(decoderClazzes); Method open = null; Method close = null; Method error = null; for (Method method : clazzPojo.getDeclaredMethods()) { if (method.getAnnotation(OnOpen.class) != null) { checkPublic(method); if (open == null) { open = method; } else { // Duplicate annotation throw new DeploymentException(sm.getString( "pojoMethodMapping.duplicateAnnotation", OnOpen.class, clazzPojo)); } } else if (method.getAnnotation(OnClose.class) != null) { checkPublic(method); if (close == null) { close = method; } else { // Duplicate annotation throw new DeploymentException(sm.getString( "pojoMethodMapping.duplicateAnnotation", OnClose.class, clazzPojo)); } } else if (method.getAnnotation(OnError.class) != null) { checkPublic(method); if (error == null) { error = method; } else { // Duplicate annotation throw new DeploymentException(sm.getString( "pojoMethodMapping.duplicateAnnotation", OnError.class, clazzPojo)); } } else if (method.getAnnotation(OnMessage.class) != null) { checkPublic(method); onMessage.add(new MessageHandlerInfo(method, decoders)); } else { // Method not annotated } } this.onOpen = open; this.onClose = close; this.onError = error; onOpenParams = getPathParams(onOpen, MethodType.ON_OPEN); onCloseParams = getPathParams(onClose, MethodType.ON_CLOSE); onErrorParams = getPathParams(onError, MethodType.ON_ERROR); } private void checkPublic(Method m) throws DeploymentException { if (!Modifier.isPublic(m.getModifiers())) { throw new DeploymentException(sm.getString( "pojoMethodMapping.methodNotPublic", m.getName())); } } public String getWsPath() { return wsPath; } public Method getOnOpen() { return onOpen; } public Object[] getOnOpenArgs(Map<String,String> pathParameters, Session session, EndpointConfig config) throws DecodeException { return buildArgs(onOpenParams, pathParameters, session, config, null, null); } public Method getOnClose() { return onClose; } public Object[] getOnCloseArgs(Map<String,String> pathParameters, Session session, CloseReason closeReason) throws DecodeException { return buildArgs(onCloseParams, pathParameters, session, null, null, closeReason); } public Method getOnError() { return onError; } public Object[] getOnErrorArgs(Map<String,String> pathParameters, Session session, Throwable throwable) throws DecodeException { return buildArgs(onErrorParams, pathParameters, session, null, throwable, null); } public Set<MessageHandler> getMessageHandlers(Object pojo, Map<String,String> pathParameters, Session session, EndpointConfig config) { Set<MessageHandler> result = new HashSet<>(); for (MessageHandlerInfo messageMethod : onMessage) { result.addAll(messageMethod.getMessageHandlers(pojo, pathParameters, session, config)); } return result; } private static PojoPathParam[] getPathParams(Method m, MethodType methodType) throws DeploymentException { if (m == null) { return new PojoPathParam[0]; } boolean foundThrowable = false; Class<?>[] types = m.getParameterTypes(); Annotation[][] paramsAnnotations = m.getParameterAnnotations(); PojoPathParam[] result = new PojoPathParam[types.length]; for (int i = 0; i < types.length; i++) { Class<?> type = types[i]; if (type.equals(Session.class)) { result[i] = new PojoPathParam(type, null); } else if (methodType == MethodType.ON_OPEN && type.equals(EndpointConfig.class)) { result[i] = new PojoPathParam(type, null); } else if (methodType == MethodType.ON_ERROR && type.equals(Throwable.class)) { foundThrowable = true; result[i] = new PojoPathParam(type, null); } else if (methodType == MethodType.ON_CLOSE && type.equals(CloseReason.class)) { result[i] = new PojoPathParam(type, null); } else { Annotation[] paramAnnotations = paramsAnnotations[i]; for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation.annotationType().equals( PathParam.class)) { // Check that the type is valid. "0" coerces to every // valid type try { Util.coerceToType(type, "0"); } catch (IllegalArgumentException iae) { throw new DeploymentException(sm.getString( "pojoMethodMapping.invalidPathParamType"), iae); } result[i] = new PojoPathParam(type, ((PathParam) paramAnnotation).value()); break; } } // Parameters without annotations are not permitted if (result[i] == null) { throw new DeploymentException(sm.getString( "pojoMethodMapping.paramWithoutAnnotation", type, m.getName(), m.getClass().getName())); } } } if (methodType == MethodType.ON_ERROR && !foundThrowable) { throw new DeploymentException(sm.getString( "pojoMethodMapping.onErrorNoThrowable", m.getName(), m.getDeclaringClass().getName())); } return result; } private static Object[] buildArgs(PojoPathParam[] pathParams, Map<String,String> pathParameters, Session session, EndpointConfig config, Throwable throwable, CloseReason closeReason) throws DecodeException { Object[] result = new Object[pathParams.length]; for (int i = 0; i < pathParams.length; i++) { Class<?> type = pathParams[i].getType(); if (type.equals(Session.class)) { result[i] = session; } else if (type.equals(EndpointConfig.class)) { result[i] = config; } else if (type.equals(Throwable.class)) { result[i] = throwable; } else if (type.equals(CloseReason.class)) { result[i] = closeReason; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); try { result[i] = Util.coerceToType(type, value); } catch (Exception e) { throw new DecodeException(value, sm.getString( "pojoMethodMapping.decodePathParamFail", value, type), e); } } } return result; } private static class MessageHandlerInfo { private final Method m; private int indexString = -1; private int indexByteArray = -1; private int indexByteBuffer = -1; private int indexPong = -1; private int indexBoolean = -1; private int indexSession = -1; private int indexInputStream = -1; private int indexReader = -1; private int indexPrimitive = -1; private Map<Integer,PojoPathParam> indexPathParams = new HashMap<>(); private int indexPayload = -1; private DecoderMatch decoderMatch = null; private long maxMessageSize = -1; public MessageHandlerInfo(Method m, List<DecoderEntry> decoderEntries) { this.m = m; Class<?>[] types = m.getParameterTypes(); Annotation[][] paramsAnnotations = m.getParameterAnnotations(); for (int i = 0; i < types.length; i++) { boolean paramFound = false; Annotation[] paramAnnotations = paramsAnnotations[i]; for (Annotation paramAnnotation : paramAnnotations) { if (paramAnnotation.annotationType().equals( PathParam.class)) { indexPathParams.put( Integer.valueOf(i), new PojoPathParam(types[i], ((PathParam) paramAnnotation).value())); paramFound = true; break; } } if (paramFound) { continue; } if (String.class.isAssignableFrom(types[i])) { if (indexString == -1) { indexString = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (Reader.class.isAssignableFrom(types[i])) { if (indexReader == -1) { indexReader = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (boolean.class == types[i]) { if (indexBoolean == -1) { indexBoolean = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateLastParam", m.getName(), m.getDeclaringClass().getName())); } } else if (ByteBuffer.class.isAssignableFrom(types[i])) { if (indexByteBuffer == -1) { indexByteBuffer = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (byte[].class == types[i]) { if (indexByteArray == -1) { indexByteArray = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (InputStream.class.isAssignableFrom(types[i])) { if (indexInputStream == -1) { indexInputStream = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (Util.isPrimitive(types[i])) { if (indexPrimitive == -1) { indexPrimitive = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else if (Session.class.isAssignableFrom(types[i])) { if (indexSession == -1) { indexSession = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateSessionParam", m.getName(), m.getDeclaringClass().getName())); } } else if (PongMessage.class.isAssignableFrom(types[i])) { if (indexPong == -1) { indexPong = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicatePongMessageParam", m.getName(), m.getDeclaringClass().getName())); } } else { if (decoderMatch != null && decoderMatch.hasMatches()) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } decoderMatch = new DecoderMatch(types[i], decoderEntries); if (decoderMatch.hasMatches()) { indexPayload = i; } } } // Additional checks required if (indexString != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexString; } } if (indexReader != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexReader; } } if (indexByteArray != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexByteArray; } } if (indexByteBuffer != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexByteBuffer; } } if (indexInputStream != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexInputStream; } } if (indexPrimitive != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexPrimitive; } } if (indexPong != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.pongWithPayload", m.getName(), m.getDeclaringClass().getName())); } else { indexPayload = indexPong; } } if (indexPayload == -1 && indexPrimitive == -1 && indexBoolean != -1) { // The boolean we found is a payload, not a last flag indexPayload = indexBoolean; indexPrimitive = indexBoolean; indexBoolean = -1; } if (indexPayload == -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.noPayload", m.getName(), m.getDeclaringClass().getName())); } if (indexPong != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialPong", m.getName(), m.getDeclaringClass().getName())); } if(indexReader != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialReader", m.getName(), m.getDeclaringClass().getName())); } if(indexInputStream != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialInputStream", m.getName(), m.getDeclaringClass().getName())); } if (decoderMatch != null && decoderMatch.hasMatches() && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialObject", m.getName(), m.getDeclaringClass().getName())); } maxMessageSize = m.getAnnotation(OnMessage.class).maxMessageSize(); } public Set<MessageHandler> getMessageHandlers(Object pojo, Map<String,String> pathParameters, Session session, EndpointConfig config) { Object[] params = new Object[m.getParameterTypes().length]; for (Map.Entry<Integer,PojoPathParam> entry : indexPathParams.entrySet()) { PojoPathParam pathParam = entry.getValue(); String valueString = pathParameters.get(pathParam.getName()); Object value = null; try { value = Util.coerceToType(pathParam.getType(), valueString); } catch (Exception e) { DecodeException de = new DecodeException(valueString, sm.getString( "pojoMethodMapping.decodePathParamFail", valueString, pathParam.getType()), e); params = new Object[] { de }; } params[entry.getKey().intValue()] = value; } Set<MessageHandler> results = new HashSet<>(2); if (indexBoolean == -1) { // Basic if (indexString != -1 || indexPrimitive != -1) { MessageHandler mh = new PojoMessageHandlerWholeText(pojo, m, session, config, null, params, indexPayload, false, indexSession, maxMessageSize); results.add(mh); } else if (indexReader != -1) { MessageHandler mh = new PojoMessageHandlerWholeText(pojo, m, session, config, null, params, indexReader, true, indexSession, maxMessageSize); results.add(mh); } else if (indexByteArray != -1) { MessageHandler mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, null, params, indexByteArray, true, indexSession, false, maxMessageSize); results.add(mh); } else if (indexByteBuffer != -1) { MessageHandler mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, null, params, indexByteBuffer, false, indexSession, false, maxMessageSize); results.add(mh); } else if (indexInputStream != -1) { MessageHandler mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, null, params, indexInputStream, true, indexSession, true, maxMessageSize); results.add(mh); } else if (decoderMatch.hasMatches()) { if (decoderMatch.getBinaryDecoders().size() > 0) { MessageHandler mh = new PojoMessageHandlerWholeBinary( pojo, m, session, config, decoderMatch.getBinaryDecoders(), params, indexPayload, true, indexSession, true, maxMessageSize); results.add(mh); } if (decoderMatch.getTextDecoders().size() > 0) { MessageHandler mh = new PojoMessageHandlerWholeText( pojo, m, session, config, decoderMatch.getTextDecoders(), params, indexPayload, true, indexSession, maxMessageSize); results.add(mh); } } else { MessageHandler mh = new PojoMessageHandlerWholePong(pojo, m, session, params, indexPong, false, indexSession); results.add(mh); } } else { // ASync if (indexString != -1) { MessageHandler mh = new PojoMessageHandlerPartialText(pojo, m, session, params, indexString, false, indexBoolean, indexSession, maxMessageSize); results.add(mh); } else if (indexByteArray != -1) { MessageHandler mh = new PojoMessageHandlerPartialBinary( pojo, m, session, params, indexByteArray, true, indexBoolean, indexSession, maxMessageSize); results.add(mh); } else { MessageHandler mh = new PojoMessageHandlerPartialBinary( pojo, m, session, params, indexByteBuffer, false, indexBoolean, indexSession, maxMessageSize); results.add(mh); } } return results; } } private static enum MethodType { ON_OPEN, ON_CLOSE, ON_ERROR } }
55,186
Bug 55186 useIPVHosts=true , incorrect to get Request.localName
null
resolved fixed
2eb065f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-05T13:34:16Z
2013-07-03T05:40:00Z
java/org/apache/coyote/Request.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.util.HashMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.ReadListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.UDecoder; import org.apache.tomcat.util.http.Cookies; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.Parameters; import org.apache.tomcat.util.res.StringManager; /** * This is a low-level, efficient representation of a server request. Most * fields are GC-free, expensive operations are delayed until the user code * needs the information. * * Processing is delegated to modules, using a hook mechanism. * * This class is not intended for user code - it is used internally by tomcat * for processing the request in the most efficient way. Users ( servlets ) can * access the information using a facade, which provides the high-level view * of the request. * * Tomcat defines a number of attributes: * <ul> * <li>"org.apache.tomcat.request" - allows access to the low-level * request object in trusted applications * </ul> * * @author James Duncan Davidson [duncan@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author Harish Prabandham * @author Alex Cruikshank [alex@epitonic.com] * @author Hans Bergsten [hans@gefionsoftware.com] * @author Costin Manolache * @author Remy Maucherat */ public final class Request { private static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------------- Constructors public Request() { parameters.setQuery(queryMB); parameters.setURLDecoder(urlDecoder); } // ----------------------------------------------------- Instance Variables private int serverPort = -1; private final MessageBytes serverNameMB = MessageBytes.newInstance(); private int remotePort; private int localPort; private final MessageBytes schemeMB = MessageBytes.newInstance(); private final MessageBytes methodMB = MessageBytes.newInstance(); private final MessageBytes unparsedURIMB = MessageBytes.newInstance(); private final MessageBytes uriMB = MessageBytes.newInstance(); private final MessageBytes decodedUriMB = MessageBytes.newInstance(); private final MessageBytes queryMB = MessageBytes.newInstance(); private final MessageBytes protoMB = MessageBytes.newInstance(); // remote address/host private final MessageBytes remoteAddrMB = MessageBytes.newInstance(); private final MessageBytes localNameMB = MessageBytes.newInstance(); private final MessageBytes remoteHostMB = MessageBytes.newInstance(); private final MessageBytes localAddrMB = MessageBytes.newInstance(); private final MimeHeaders headers = new MimeHeaders(); private final MessageBytes instanceId = MessageBytes.newInstance(); /** * Notes. */ private final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Associated input buffer. */ private InputBuffer inputBuffer = null; /** * URL decoder. */ private final UDecoder urlDecoder = new UDecoder(); /** * HTTP specific fields. (remove them ?) */ private long contentLength = -1; private MessageBytes contentTypeMB = null; private String charEncoding = null; private final Cookies cookies = new Cookies(headers); private final Parameters parameters = new Parameters(); private final MessageBytes remoteUser=MessageBytes.newInstance(); private final MessageBytes authType=MessageBytes.newInstance(); private final HashMap<String,Object> attributes=new HashMap<>(); private Response response; private ActionHook hook; private int bytesRead=0; // Time of the request - useful to avoid repeated calls to System.currentTime private long startTime = -1; private int available = 0; private final RequestInfo reqProcessorMX=new RequestInfo(this); protected volatile ReadListener listener; public ReadListener getReadListener() { return listener; } public void setReadListener(ReadListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("request.nullReadListener")); } if (getReadListener() != null) { throw new IllegalStateException( sm.getString("request.readListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("request.notAsync")); } this.listener = listener; } // ------------------------------------------------------------- Properties /** * Get the instance id (or JVM route). Currently Ajp is sending it with each * request. In future this should be fixed, and sent only once ( or * 'negotiated' at config time so both tomcat and apache share the same name. * * @return the instance id */ public MessageBytes instanceId() { return instanceId; } public MimeHeaders getMimeHeaders() { return headers; } public UDecoder getURLDecoder() { return urlDecoder; } // -------------------- Request data -------------------- public MessageBytes scheme() { return schemeMB; } public MessageBytes method() { return methodMB; } public MessageBytes unparsedURI() { return unparsedURIMB; } public MessageBytes requestURI() { return uriMB; } public MessageBytes decodedURI() { return decodedUriMB; } public MessageBytes queryString() { return queryMB; } public MessageBytes protocol() { return protoMB; } /** * Return the buffer holding the server name, if * any. Use isNull() to check if there is no value * set. * This is the "virtual host", derived from the * Host: header. */ public MessageBytes serverName() { return serverNameMB; } public int getServerPort() { return serverPort; } public void setServerPort(int serverPort ) { this.serverPort=serverPort; } public MessageBytes remoteAddr() { return remoteAddrMB; } public MessageBytes remoteHost() { return remoteHostMB; } public MessageBytes localName() { return localNameMB; } public MessageBytes localAddr() { return localAddrMB; } public int getRemotePort(){ return remotePort; } public void setRemotePort(int port){ this.remotePort = port; } public int getLocalPort(){ return localPort; } public void setLocalPort(int port){ this.localPort = port; } // -------------------- encoding/type -------------------- /** * Get the character encoding used for this request. */ public String getCharacterEncoding() { if (charEncoding != null) { return charEncoding; } charEncoding = getCharsetFromContentType(getContentType()); return charEncoding; } public void setCharacterEncoding(String enc) { this.charEncoding = enc; } public void setContentLength(int len) { this.contentLength = len; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { if( contentLength > -1 ) { return contentLength; } MessageBytes clB = headers.getUniqueValue("content-length"); contentLength = (clB == null || clB.isNull()) ? -1 : clB.getLong(); return contentLength; } public String getContentType() { contentType(); if ((contentTypeMB == null) || contentTypeMB.isNull()) { return null; } return contentTypeMB.toString(); } public void setContentType(String type) { contentTypeMB.setString(type); } public MessageBytes contentType() { if (contentTypeMB == null) { contentTypeMB = headers.getValue("content-type"); } return contentTypeMB; } public void setContentType(MessageBytes mb) { contentTypeMB=mb; } public String getHeader(String name) { return headers.getHeader(name); } // -------------------- Associated response -------------------- public Response getResponse() { return response; } public void setResponse( Response response ) { this.response=response; response.setRequest( this ); } public void action(ActionCode actionCode, Object param) { if( hook==null && response!=null ) { hook=response.getHook(); } if (hook != null) { if( param==null ) { hook.action(actionCode, this); } else { hook.action(actionCode, param); } } } // -------------------- Cookies -------------------- public Cookies getCookies() { return cookies; } // -------------------- Parameters -------------------- public Parameters getParameters() { return parameters; } // -------------------- Other attributes -------------------- // We can use notes for most - need to discuss what is of general interest public void setAttribute( String name, Object o ) { attributes.put( name, o ); } public HashMap<String,Object> getAttributes() { return attributes; } public Object getAttribute(String name ) { return attributes.get(name); } public MessageBytes getRemoteUser() { return remoteUser; } public MessageBytes getAuthType() { return authType; } public int getAvailable() { return available; } public void setAvailable(int available) { this.available = available; } // -------------------- Input Buffer -------------------- public InputBuffer getInputBuffer() { return inputBuffer; } public void setInputBuffer(InputBuffer inputBuffer) { this.inputBuffer = inputBuffer; } /** * Read data from the input buffer and put it into a byte chunk. * * The buffer is owned by the protocol implementation - it will be reused on the next read. * The Adapter must either process the data in place or copy it to a separate buffer if it needs * to hold it. In most cases this is done during byte->char conversions or via InputStream. Unlike * InputStream, this interface allows the app to process data in place, without copy. * */ public int doRead(ByteChunk chunk) throws IOException { int n = inputBuffer.doRead(chunk, this); if (n > 0) { bytesRead+=n; } return n; } // -------------------- debug -------------------- @Override public String toString() { return "R( " + requestURI().toString() + ")"; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } // -------------------- Per-Request "notes" -------------------- /** * Used to store private data. Thread data could be used instead - but * if you have the req, getting/setting a note is just a array access, may * be faster than ThreadLocal for very frequent operations. * * Example use: * Jk: * HandlerRequest.HOSTBUFFER = 10 CharChunk, buffer for Host decoding * WorkerEnv: SSL_CERT_NOTE=16 - MessageBytes containing the cert * * Catalina CoyoteAdapter: * ADAPTER_NOTES = 1 - stores the HttpServletRequest object ( req/res) * * To avoid conflicts, note in the range 0 - 8 are reserved for the * servlet container ( catalina connector, etc ), and values in 9 - 16 * for connector use. * * 17-31 range is not allocated or used. */ public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Recycling -------------------- public void recycle() { bytesRead=0; contentLength = -1; contentTypeMB = null; charEncoding = null; headers.recycle(); serverNameMB.recycle(); serverPort=-1; localPort = -1; remotePort = -1; available = 0; cookies.recycle(); parameters.recycle(); unparsedURIMB.recycle(); uriMB.recycle(); decodedUriMB.recycle(); queryMB.recycle(); methodMB.recycle(); protoMB.recycle(); schemeMB.recycle(); instanceId.recycle(); remoteUser.recycle(); authType.recycle(); attributes.clear(); listener = null; startTime = -1; } // -------------------- Info -------------------- public void updateCounters() { reqProcessorMX.updateCounters(); } public RequestInfo getRequestProcessor() { return reqProcessorMX; } public int getBytesRead() { return bytesRead; } public boolean isProcessing() { return reqProcessorMX.getStage()==org.apache.coyote.Constants.STAGE_SERVICE; } /** * Parse the character encoding from the specified content type header. * If the content type is null, or there is no explicit character encoding, * <code>null</code> is returned. * * @param contentType a content type header */ private static String getCharsetFromContentType(String contentType) { if (contentType == null) { return (null); } int start = contentType.indexOf("charset="); if (start < 0) { return (null); } String encoding = contentType.substring(start + 8); int end = encoding.indexOf(';'); if (end >= 0) { encoding = encoding.substring(0, end); } encoding = encoding.trim(); if ((encoding.length() > 2) && (encoding.startsWith("\"")) && (encoding.endsWith("\""))) { encoding = encoding.substring(1, encoding.length() - 1); } return (encoding.trim()); } }
55,200
Bug 55200 [websocket] Problem writing many subsequent binary messages
I see sometimes failing connections due to IOException (see below). This happens when trying to send thousands of binary messages (1024 bytes each) without any delay between the subsequent messages. Having look at the code in AsyncChannelWrapperSecure$WriteTask.run(219), I think it is not correct to assume that if not all of the bytes in the buffer are written, this shall produce IOException. I think in this case, there shall be an attempt to write the rest of the bytes in a cycle. Here one exception I got during the test: Exception is :java.io.IOException: java.util.concurrent.ExecutionException: java.io.IOException: Only wrote [460] of [1,098] bytes at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.startMessageBlock(WsRemoteEndpointImplBase.java:204) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.sendBytes(WsRemoteEndpointImplBase.java:113) at org.apache.tomcat.websocket.WsRemoteEndpointBasic.sendBinary(WsRemoteEndpointBasic.java:43) at WebsocketsTestManager$TestThread.run(WebsocketsTestManager.java:271) Caused by: java.util.concurrent.ExecutionException: java.io.IOException: Only wrote [460] of [1,098] bytes at org.apache.tomcat.websocket.WsRemoteEndpointImplBase$FutureToSendHandler.get(WsRemoteEndpointImplBase.java:729) at org.apache.tomcat.websocket.WsRemoteEndpointImplBase.startMessageBlock(WsRemoteEndpointImplBase.java:202) ... 3 more Caused by: java.io.IOException: Only wrote [460] of [1,098] bytes at org.apache.tomcat.websocket.AsyncChannelWrapperSecure$WriteTask.run(AsyncChannelWrapperSecure.java:220) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615) at java.lang.Thread.run(Thread.java:789)
resolved fixed
00e4f3f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-05T17:22:06Z
2013-07-05T18:46:40Z
java/org/apache/tomcat/websocket/AsyncChannelWrapperSecure.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import javax.net.ssl.SSLException; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * Wraps the {@link AsynchronousSocketChannel} with SSL/TLS. This needs a lot * more testing before it can be considered robust. */ public class AsyncChannelWrapperSecure implements AsyncChannelWrapper { private static final Log log = LogFactory.getLog(AsyncChannelWrapperSecure.class); private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final ByteBuffer DUMMY = ByteBuffer.allocate(8192); private final AsynchronousSocketChannel socketChannel; private final SSLEngine sslEngine; private final ByteBuffer socketReadBuffer; private final ByteBuffer socketWriteBuffer; // One thread for read, one for write private final ExecutorService executor = Executors.newFixedThreadPool(2); private AtomicBoolean writing = new AtomicBoolean(false); private AtomicBoolean reading = new AtomicBoolean(false); public AsyncChannelWrapperSecure(AsynchronousSocketChannel socketChannel, SSLEngine sslEngine) { this.socketChannel = socketChannel; this.sslEngine = sslEngine; int socketBufferSize = sslEngine.getSession().getPacketBufferSize(); socketReadBuffer = ByteBuffer.allocateDirect(socketBufferSize); socketWriteBuffer = ByteBuffer.allocateDirect(socketBufferSize); } @Override public Future<Integer> read(ByteBuffer dst) { WrapperFuture<Integer,Void> future = new WrapperFuture<>(); if (!reading.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentRead")); } ReadTask readTask = new ReadTask(dst, future); executor.execute(readTask); return future; } @Override public <A> void read(ByteBuffer dst, A attachment, CompletionHandler<Integer,? super A> handler) { WrapperFuture<Integer,? super A> future = new WrapperFuture<>(handler, attachment); if (!reading.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentRead")); } ReadTask readTask = new ReadTask(dst, future); executor.execute(readTask); } @Override public Future<Integer> write(ByteBuffer src) { WrapperFuture<Long,Void> inner = new WrapperFuture<>(); if (!writing.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentWrite")); } WriteTask writeTask = new WriteTask(new ByteBuffer[] {src}, 0, 1, inner); executor.execute(writeTask); Future<Integer> future = new LongToIntegerFuture(inner); return future; } @Override public <A> void write(ByteBuffer[] srcs, int offset, int length, long timeout, TimeUnit unit, A attachment, CompletionHandler<Long,? super A> handler) { WrapperFuture<Long,? super A> future = new WrapperFuture<>(handler, attachment); if (!writing.compareAndSet(false, true)) { throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.concurrentWrite")); } WriteTask writeTask = new WriteTask(srcs, offset, length, future); executor.execute(writeTask); } @Override public void close() { try { socketChannel.close(); } catch (IOException e) { log.info(sm.getString("asyncChannelWrapperSecure.closeFail")); } } @Override public Future<Void> handshake() throws SSLException { WrapperFuture<Void,Void> wFuture = new WrapperFuture<>(); Thread t = new WebSocketSslHandshakeThread(wFuture); t.start(); return wFuture; } private class WriteTask implements Runnable { private final ByteBuffer[] srcs; private final int offset; private final int length; private final WrapperFuture<Long,?> future; public WriteTask(ByteBuffer[] srcs, int offset, int length, WrapperFuture<Long,?> future) { this.srcs = srcs; this.future = future; this.offset = offset; this.length = length; } @Override public void run() { long written = 0; try { for (int i = offset; i < offset + length; i++) { ByteBuffer src = srcs[i]; while (src.hasRemaining()) { socketWriteBuffer.clear(); // Encrypt the data SSLEngineResult r = sslEngine.wrap(src, socketWriteBuffer); written += r.bytesConsumed(); Status s = r.getStatus(); if (s == Status.OK || s == Status.BUFFER_OVERFLOW) { // Need to write out the bytes and may need to read from // the source again to empty it } else { // Status.BUFFER_UNDERFLOW - only happens on unwrap // Status.CLOSED - unexpected throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.statusWrap")); } // Check for tasks if (r.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable = sslEngine.getDelegatedTask(); while (runnable != null) { runnable.run(); runnable = sslEngine.getDelegatedTask(); } } socketWriteBuffer.flip(); // Do the write Future<Integer> f = socketChannel.write(socketWriteBuffer); Integer socketWrite = f.get(); if (socketWrite.intValue() != r.bytesProduced()) { throw new IOException(sm.getString( "asyncChannelWrapperSecure.writeFail", Integer.valueOf(socketWrite.intValue()), Integer.valueOf(r.bytesProduced()))); } } } if (writing.compareAndSet(true, false)) { future.complete(Long.valueOf(written)); } else { future.fail(new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.wrongStateWrite"))); } } catch (Exception e) { future.fail(e); } } } private class ReadTask implements Runnable { private final ByteBuffer dest; private final WrapperFuture<Integer,?> future; public ReadTask(ByteBuffer dest, WrapperFuture<Integer,?> future) { this.dest = dest; this.future = future; } @Override public void run() { int read = 0; boolean forceRead = false; try { while (read == 0) { socketReadBuffer.compact(); if (forceRead) { Future<Integer> f = socketChannel.read(socketReadBuffer); Integer socketRead = f.get(); if (socketRead.intValue() == -1) { throw new EOFException(sm.getString( "asyncChannelWrapperSecure.eof")); } } socketReadBuffer.flip(); if (socketReadBuffer.hasRemaining()) { // Decrypt the data in the buffer SSLEngineResult r = sslEngine.unwrap(socketReadBuffer, dest); read += r.bytesProduced(); Status s = r.getStatus(); if (s == Status.OK || s == Status.BUFFER_OVERFLOW) { // Bytes available for reading and there may be // sufficientNeed data in the socketReadBuffer to // support further reads without reading from the // socket } else if (s == Status.BUFFER_UNDERFLOW) { // There is partial data in the socketReadBuffer if (read == 0) { // Need more data before the partial data can be // processed and some output generated forceRead = true; } // else return the data we have and deal with the // partial data on the next read } else { // Status.CLOSED - unexpected throw new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.statusUnwrap")); } // Check for tasks if (r.getHandshakeStatus() == HandshakeStatus.NEED_TASK) { Runnable runnable = sslEngine.getDelegatedTask(); while (runnable != null) { runnable.run(); runnable = sslEngine.getDelegatedTask(); } } } else { forceRead = true; } } if (reading.compareAndSet(true, false)) { future.complete(Integer.valueOf(read)); } else { future.fail(new IllegalStateException(sm.getString( "asyncChannelWrapperSecure.wrongStateRead"))); } } catch (Exception e) { future.fail(e); } } } private class WebSocketSslHandshakeThread extends Thread { private final WrapperFuture<Void,Void> hFuture; private HandshakeStatus handshakeStatus; private Status resultStatus; public WebSocketSslHandshakeThread(WrapperFuture<Void,Void> hFuture) { this.hFuture = hFuture; } @Override public void run() { try { sslEngine.beginHandshake(); // So the first compact does the right thing socketReadBuffer.position(socketReadBuffer.limit()); handshakeStatus = sslEngine.getHandshakeStatus(); resultStatus = Status.OK; boolean handshaking = true; while(handshaking) { switch (handshakeStatus) { case NEED_WRAP: { socketWriteBuffer.clear(); SSLEngineResult r = sslEngine.wrap(DUMMY, socketWriteBuffer); checkResult(r, true); socketWriteBuffer.flip(); Future<Integer> fWrite = socketChannel.write(socketWriteBuffer); fWrite.get(); break; } case NEED_UNWRAP: { socketReadBuffer.compact(); if (socketReadBuffer.position() == 0 || resultStatus == Status.BUFFER_UNDERFLOW) { Future<Integer> fRead = socketChannel.read(socketReadBuffer); fRead.get(); } socketReadBuffer.flip(); SSLEngineResult r = sslEngine.unwrap(socketReadBuffer, DUMMY); checkResult(r, false); break; } case NEED_TASK: { Runnable r = null; while ((r = sslEngine.getDelegatedTask()) != null) { r.run(); } handshakeStatus = sslEngine.getHandshakeStatus(); break; } case FINISHED: { handshaking = false; break; } default: { throw new SSLException("TODO"); } } } } catch (SSLException | InterruptedException | ExecutionException e) { hFuture.fail(e); } hFuture.complete(null); } private void checkResult(SSLEngineResult result, boolean wrap) throws SSLException { handshakeStatus = result.getHandshakeStatus(); resultStatus = result.getStatus(); if (resultStatus != Status.OK && (wrap || resultStatus != Status.BUFFER_UNDERFLOW)) { throw new SSLException("TODO"); } if (wrap && result.bytesConsumed() != 0) { throw new SSLException("TODO"); } if (!wrap && result.bytesProduced() != 0) { throw new SSLException("TODO"); } } } private static class WrapperFuture<T,A> implements Future<T> { private final CompletionHandler<T,A> handler; private final A attachment; private volatile T result = null; private volatile Throwable throwable = null; private CountDownLatch completionLatch = new CountDownLatch(1); public WrapperFuture() { this(null, null); } public WrapperFuture(CompletionHandler<T,A> handler, A attachment) { this.handler = handler; this.attachment = attachment; } public void complete(T result) { this.result = result; completionLatch.countDown(); if (handler != null) { handler.completed(result, attachment); } } public void fail(Throwable t) { throwable = t; completionLatch.countDown(); if (handler != null) { handler.failed(throwable, attachment); } } @Override public final boolean cancel(boolean mayInterruptIfRunning) { // Could support cancellation by closing the connection return false; } @Override public final boolean isCancelled() { // Could support cancellation by closing the connection return false; } @Override public final boolean isDone() { return completionLatch.getCount() > 0; } @Override public T get() throws InterruptedException, ExecutionException { completionLatch.await(); if (throwable != null) { throw new ExecutionException(throwable); } return result; } @Override public T get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { boolean latchResult = completionLatch.await(timeout, unit); if (latchResult == false) { throw new TimeoutException(); } if (throwable != null) { throw new ExecutionException(throwable); } return result; } } private static final class LongToIntegerFuture implements Future<Integer> { private final Future<Long> wrapped; public LongToIntegerFuture(Future<Long> wrapped) { this.wrapped = wrapped; } @Override public boolean cancel(boolean mayInterruptIfRunning) { return wrapped.cancel(mayInterruptIfRunning); } @Override public boolean isCancelled() { return wrapped.isCancelled(); } @Override public boolean isDone() { return wrapped.isDone(); } @Override public Integer get() throws InterruptedException, ExecutionException { Long result = wrapped.get(); if (result.longValue() > Integer.MAX_VALUE) { throw new ExecutionException(sm.getString( "asyncChannelWrapperSecure.tooBig", result), null); } return new Integer(result.intValue()); } @Override public Integer get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { Long result = wrapped.get(timeout, unit); if (result.longValue() > Integer.MAX_VALUE) { throw new ExecutionException(sm.getString( "asyncChannelWrapperSecure.tooBig", result), null); } return new Integer(result.intValue()); } } }
55,210
Bug 55210 SEVERE: The ServletContentInitializer [# Licensed to the Apache Software Foundation (ASF) under one or more] could not be created
null
resolved fixed
b932ace
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-08T06:53:50Z
2013-07-08T02:20:00Z
java/org/apache/catalina/startup/ContextConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.startup; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.JarURLConnection; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.SessionCookieConfig; import javax.servlet.annotation.HandlesTypes; import javax.servlet.descriptor.JspPropertyGroupDescriptor; import javax.servlet.descriptor.TaglibDescriptor; import org.apache.catalina.Authenticator; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.Pipeline; import org.apache.catalina.Server; import org.apache.catalina.Service; import org.apache.catalina.Valve; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.catalina.core.ApplicationJspPropertyGroupDescriptor; import org.apache.catalina.core.ApplicationTaglibDescriptor; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardHost; import org.apache.catalina.deploy.ApplicationListener; import org.apache.catalina.deploy.ContextEjb; import org.apache.catalina.deploy.ContextEnvironment; import org.apache.catalina.deploy.ContextLocalEjb; import org.apache.catalina.deploy.ContextResource; import org.apache.catalina.deploy.ContextResourceEnvRef; import org.apache.catalina.deploy.ContextService; import org.apache.catalina.deploy.ErrorPage; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.deploy.FilterMap; import org.apache.catalina.deploy.JspPropertyGroup; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.MessageDestinationRef; import org.apache.catalina.deploy.MultipartDef; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.deploy.SecurityRoleRef; import org.apache.catalina.deploy.ServletDef; import org.apache.catalina.deploy.SessionConfig; import org.apache.catalina.deploy.WebXml; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.Introspection; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.JarScanType; import org.apache.tomcat.JarScanner; import org.apache.tomcat.JarScannerCallback; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.bcel.classfile.AnnotationElementValue; import org.apache.tomcat.util.bcel.classfile.AnnotationEntry; import org.apache.tomcat.util.bcel.classfile.ArrayElementValue; import org.apache.tomcat.util.bcel.classfile.ClassFormatException; import org.apache.tomcat.util.bcel.classfile.ClassParser; import org.apache.tomcat.util.bcel.classfile.ElementValue; import org.apache.tomcat.util.bcel.classfile.ElementValuePair; import org.apache.tomcat.util.bcel.classfile.JavaClass; import org.apache.tomcat.util.digester.Digester; import org.apache.tomcat.util.digester.RuleSet; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.util.scan.Jar; import org.apache.tomcat.util.scan.JarFactory; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; /** * Startup event listener for a <b>Context</b> that configures the properties * of that Context, and the associated defined servlets. * * @author Craig R. McClanahan * @author Jean-Francois Arcand * @version $Id$ */ public class ContextConfig implements LifecycleListener { private static final Log log = LogFactory.getLog( ContextConfig.class ); private static final String SCI_LOCATION = "META-INF/services/javax.servlet.ServletContainerInitializer"; /** * The string resources for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); protected static final LoginConfig DUMMY_LOGIN_CONFIG = new LoginConfig("NONE", null, null, null); /** * The set of Authenticators that we know how to configure. The key is * the name of the implemented authentication method, and the value is * the fully qualified Java class name of the corresponding Valve. */ protected static final Properties authenticators; static { // Load our mapping properties for the standard authenticators InputStream is = ContextConfig.class.getClassLoader().getResourceAsStream( "org/apache/catalina/startup/Authenticators.properties"); Properties props = null; props = new Properties(); if (is != null) { try { props.load(is); } catch (IOException e) { props = null; } } authenticators = props; } /** * Deployment count. */ protected static long deploymentCount = 0L; /** * Cache of default web.xml fragments per Host */ protected static final Map<Host,DefaultWebXmlCacheEntry> hostWebXmlCache = new ConcurrentHashMap<>(); // ----------------------------------------------------- Instance Variables /** * Custom mappings of login methods to authenticators */ protected Map<String,Authenticator> customAuthenticators; /** * The Context we are associated with. */ protected Context context = null; /** * The default web application's deployment descriptor location. */ protected String defaultWebXml = null; /** * Track any fatal errors during startup configuration processing. */ protected boolean ok = false; /** * Original docBase. */ protected String originalDocBase = null; /** * Anti-locking docBase. It is a path to a copy of the web application * in the java.io.tmpdir directory. This path is always an absolute one. */ private File antiLockingDocBase = null; /** * Map of ServletContainerInitializer to classes they expressed interest in. */ protected final Map<ServletContainerInitializer, Set<Class<?>>> initializerClassMap = new LinkedHashMap<>(); /** * Map of Types to ServletContainerInitializer that are interested in those * types. */ protected final Map<Class<?>, Set<ServletContainerInitializer>> typeInitializerMap = new HashMap<>(); /** * Cache of JavaClass objects (byte code) by fully qualified class name. * Only populated if it is necessary to scan the super types and interfaces * as part of the processing for {@link HandlesTypes}. */ protected final Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>(); /** * Flag that indicates if at least one {@link HandlesTypes} entry is present * that represents an annotation. */ protected boolean handlesTypesAnnotations = false; /** * Flag that indicates if at least one {@link HandlesTypes} entry is present * that represents a non-annotation. */ protected boolean handlesTypesNonAnnotations = false; /** * The <code>Digester</code> we will use to process web application * deployment descriptor files. */ protected Digester webDigester = null; protected WebRuleSet webRuleSet = null; /** * The <code>Digester</code> we will use to process web fragment * deployment descriptor files. */ protected Digester webFragmentDigester = null; protected WebRuleSet webFragmentRuleSet = null; // ------------------------------------------------------------- Properties /** * Return the location of the default deployment descriptor */ public String getDefaultWebXml() { if( defaultWebXml == null ) { defaultWebXml=Constants.DefaultWebXml; } return (this.defaultWebXml); } /** * Set the location of the default deployment descriptor * * @param path Absolute/relative path to the default web.xml */ public void setDefaultWebXml(String path) { this.defaultWebXml = path; } /** * Sets custom mappings of login methods to authenticators. * * @param customAuthenticators Custom mappings of login methods to * authenticators */ public void setCustomAuthenticators( Map<String,Authenticator> customAuthenticators) { this.customAuthenticators = customAuthenticators; } // --------------------------------------------------------- Public Methods /** * Process events for an associated Context. * * @param event The lifecycle event that has occurred */ @Override public void lifecycleEvent(LifecycleEvent event) { // Identify the context we are associated with try { context = (Context) event.getLifecycle(); } catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; } // Process the event that has occurred if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { configureStart(); } else if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) { beforeStart(); } else if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) { // Restore docBase for management tools if (originalDocBase != null) { context.setDocBase(originalDocBase); } } else if (event.getType().equals(Lifecycle.CONFIGURE_STOP_EVENT)) { configureStop(); } else if (event.getType().equals(Lifecycle.AFTER_INIT_EVENT)) { init(); } else if (event.getType().equals(Lifecycle.AFTER_DESTROY_EVENT)) { destroy(); } } // -------------------------------------------------------- protected Methods /** * Process the application classes annotations, if it exists. */ protected void applicationAnnotationsConfig() { long t1=System.currentTimeMillis(); WebAnnotationSet.loadApplicationAnnotations(context); long t2=System.currentTimeMillis(); if (context instanceof StandardContext) { ((StandardContext) context).setStartupTime(t2-t1+ ((StandardContext) context).getStartupTime()); } } /** * Set up an Authenticator automatically if required, and one has not * already been configured. */ protected void authenticatorConfig() { LoginConfig loginConfig = context.getLoginConfig(); SecurityConstraint constraints[] = context.findConstraints(); if (context.getIgnoreAnnotations() && (constraints == null || constraints.length ==0) && !context.getPreemptiveAuthentication()) { return; } else { if (loginConfig == null) { // Not metadata-complete or security constraints present, need // an authenticator to support @ServletSecurity annotations // and/or constraints loginConfig = DUMMY_LOGIN_CONFIG; context.setLoginConfig(loginConfig); } } // Has an authenticator been configured already? if (context.getAuthenticator() != null) { return; } // Has a Realm been configured for us to authenticate against? if (context.getRealm() == null) { log.error(sm.getString("contextConfig.missingRealm")); ok = false; return; } /* * First check to see if there is a custom mapping for the login * method. If so, use it. Otherwise, check if there is a mapping in * org/apache/catalina/startup/Authenticators.properties. */ Valve authenticator = null; if (customAuthenticators != null) { authenticator = (Valve) customAuthenticators.get(loginConfig.getAuthMethod()); } if (authenticator == null) { if (authenticators == null) { log.error(sm.getString("contextConfig.authenticatorResources")); ok = false; return; } // Identify the class name of the Valve we should configure String authenticatorName = null; authenticatorName = authenticators.getProperty(loginConfig.getAuthMethod()); if (authenticatorName == null) { log.error(sm.getString("contextConfig.authenticatorMissing", loginConfig.getAuthMethod())); ok = false; return; } // Instantiate and install an Authenticator of the requested class try { Class<?> authenticatorClass = Class.forName(authenticatorName); authenticator = (Valve) authenticatorClass.newInstance(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; } } if (authenticator != null) { Pipeline pipeline = context.getPipeline(); if (pipeline != null) { pipeline.addValve(authenticator); if (log.isDebugEnabled()) { log.debug(sm.getString( "contextConfig.authenticatorConfigured", loginConfig.getAuthMethod())); } } } } /** * Create and return a Digester configured to process the * web application deployment descriptor (web.xml). */ public void createWebXmlDigester(boolean namespaceAware, boolean validation) { webRuleSet = new WebRuleSet(false); webDigester = DigesterFactory.newDigester(validation, namespaceAware, webRuleSet); webDigester.getParser(); webFragmentRuleSet = new WebRuleSet(true); webFragmentDigester = DigesterFactory.newDigester(validation, namespaceAware, webFragmentRuleSet); webFragmentDigester.getParser(); } /** * Create (if necessary) and return a Digester configured to process the * context configuration descriptor for an application. */ protected Digester createContextDigester() { Digester digester = new Digester(); digester.setValidating(false); digester.setRulesValidation(true); HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>(); ArrayList<String> attrs = new ArrayList<>(); attrs.add("className"); fakeAttributes.put(Object.class, attrs); digester.setFakeAttributes(fakeAttributes); RuleSet contextRuleSet = new ContextRuleSet("", false); digester.addRuleSet(contextRuleSet); RuleSet namingRuleSet = new NamingRuleSet("Context/"); digester.addRuleSet(namingRuleSet); return digester; } /** * Process the default configuration file, if it exists. */ protected void contextConfig(Digester digester) { String defaultContextXml = null; // Open the default context.xml file, if it exists if (context instanceof StandardContext) { defaultContextXml = ((StandardContext)context).getDefaultContextXml(); } // set the default if we don't have any overrides if (defaultContextXml == null) { defaultContextXml = Constants.DefaultContextXml; } if (!context.getOverride()) { File defaultContextFile = new File(defaultContextXml); if (!defaultContextFile.isAbsolute()) { defaultContextFile = new File(context.getCatalinaBase(), defaultContextXml); } if (defaultContextFile.exists()) { try { URL defaultContextUrl = defaultContextFile.toURI().toURL(); processContextConfig(digester, defaultContextUrl); } catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", defaultContextFile), e); } } File hostContextFile = new File(getHostConfigBase(), Constants.HostContextXml); if (hostContextFile.exists()) { try { URL hostContextUrl = hostContextFile.toURI().toURL(); processContextConfig(digester, hostContextUrl); } catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", hostContextFile), e); } } } if (context.getConfigFile() != null) { processContextConfig(digester, context.getConfigFile()); } } /** * Process a context.xml. */ protected void processContextConfig(Digester digester, URL contextXml) { if (log.isDebugEnabled()) { log.debug("Processing context [" + context.getName() + "] configuration file [" + contextXml + "]"); } InputSource source = null; InputStream stream = null; try { source = new InputSource(contextXml.toString()); URLConnection xmlConn = contextXml.openConnection(); xmlConn.setUseCaches(false); stream = xmlConn.getInputStream(); } catch (Exception e) { log.error(sm.getString("contextConfig.contextMissing", contextXml) , e); } if (source == null) { return; } try { source.setByteStream(stream); digester.setClassLoader(this.getClass().getClassLoader()); digester.setUseContextClassLoader(false); digester.push(context.getParent()); digester.push(context); XmlErrorHandler errorHandler = new XmlErrorHandler(); digester.setErrorHandler(errorHandler); digester.parse(source); if (errorHandler.getWarnings().size() > 0 || errorHandler.getErrors().size() > 0) { errorHandler.logFindings(log, contextXml.toString()); ok = false; } if (log.isDebugEnabled()) { log.debug("Successfully processed context [" + context.getName() + "] configuration file [" + contextXml + "]"); } } catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; } catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); } } } /** * Adjust docBase. */ protected void fixDocBase() throws IOException { Host host = (Host) context.getParent(); File appBase = host.getAppBaseFile(); String docBase = context.getDocBase(); if (docBase == null) { // Trying to guess the docBase according to the path String path = context.getPath(); if (path == null) { return; } ContextName cn = new ContextName(path, context.getWebappVersion()); docBase = cn.getBaseName(); } File file = new File(docBase); if (!file.isAbsolute()) { docBase = (new File(appBase, docBase)).getPath(); } else { docBase = file.getCanonicalPath(); } file = new File(docBase); String origDocBase = docBase; ContextName cn = new ContextName(context.getPath(), context.getWebappVersion()); String pathName = cn.getBaseName(); boolean unpackWARs = true; if (host instanceof StandardHost && context instanceof StandardContext) { unpackWARs = ((StandardHost) host).isUnpackWARs() && ((StandardContext) context).getUnpackWAR(); } if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && unpackWARs) { URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/"); docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } else if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && !unpackWARs) { URL war = new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/"); ExpandWar.validate(host, war, pathName); } else { File docDir = new File(docBase); if (!docDir.exists()) { File warFile = new File(docBase + ".war"); if (warFile.exists()) { URL war = new URL("jar:" + warFile.toURI().toURL() + "!/"); if (unpackWARs) { docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); } else { docBase = warFile.getCanonicalPath(); ExpandWar.validate(host, war, pathName); } } if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } } if (docBase.startsWith(appBase.getPath() + File.separatorChar)) { docBase = docBase.substring(appBase.getPath().length()); docBase = docBase.replace(File.separatorChar, '/'); if (docBase.startsWith("/")) { docBase = docBase.substring(1); } } else { docBase = docBase.replace(File.separatorChar, '/'); } context.setDocBase(docBase); } protected void antiLocking() { if ((context instanceof StandardContext) && ((StandardContext) context).getAntiResourceLocking()) { Host host = (Host) context.getParent(); String docBase = context.getDocBase(); if (docBase == null) { return; } originalDocBase = docBase; File docBaseFile = new File(docBase); if (!docBaseFile.isAbsolute()) { docBaseFile = new File(host.getAppBaseFile(), docBase); } String path = context.getPath(); if (path == null) { return; } ContextName cn = new ContextName(path, context.getWebappVersion()); docBase = cn.getBaseName(); if (originalDocBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) { antiLockingDocBase = new File( System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase + ".war"); } else { antiLockingDocBase = new File( System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase); } antiLockingDocBase = antiLockingDocBase.getAbsoluteFile(); if (log.isDebugEnabled()) { log.debug("Anti locking context[" + context.getName() + "] setting docBase to " + antiLockingDocBase.getPath()); } // Cleanup just in case an old deployment is lying around ExpandWar.delete(antiLockingDocBase); if (ExpandWar.copy(docBaseFile, antiLockingDocBase)) { context.setDocBase(antiLockingDocBase.getPath()); } } } /** * Process a "init" event for this Context. */ protected void init() { // Called from StandardContext.init() Digester contextDigester = createContextDigester(); contextDigester.getParser(); if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.init")); } context.setConfigured(false); ok = true; contextConfig(contextDigester); createWebXmlDigester(context.getXmlNamespaceAware(), context.getXmlValidation()); } /** * Process a "before start" event for this Context. */ protected synchronized void beforeStart() { try { fixDocBase(); } catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); } antiLocking(); } /** * Process a "contextConfig" event for this Context. */ protected synchronized void configureStart() { // Called from StandardContext.start() if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.start")); } if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.xmlSettings", context.getName(), Boolean.valueOf(context.getXmlValidation()), Boolean.valueOf(context.getXmlNamespaceAware()))); } webConfig(); if (!context.getIgnoreAnnotations()) { applicationAnnotationsConfig(); } if (ok) { validateSecurityRoles(); } // Configure an authenticator if we need one if (ok) { authenticatorConfig(); } // Dump the contents of this pipeline if requested if (log.isDebugEnabled()) { log.debug("Pipeline Configuration:"); Pipeline pipeline = context.getPipeline(); Valve valves[] = null; if (pipeline != null) { valves = pipeline.getValves(); } if (valves != null) { for (int i = 0; i < valves.length; i++) { log.debug(" " + valves[i].getClass().getName()); } } log.debug("======================"); } // Make our application available if no problems were encountered if (ok) { context.setConfigured(true); } else { log.error(sm.getString("contextConfig.unavailable")); context.setConfigured(false); } } /** * Process a "stop" event for this Context. */ protected synchronized void configureStop() { if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.stop")); } int i; // Removing children Container[] children = context.findChildren(); for (i = 0; i < children.length; i++) { context.removeChild(children[i]); } // Removing application parameters /* ApplicationParameter[] applicationParameters = context.findApplicationParameters(); for (i = 0; i < applicationParameters.length; i++) { context.removeApplicationParameter (applicationParameters[i].getName()); } */ // Removing security constraints SecurityConstraint[] securityConstraints = context.findConstraints(); for (i = 0; i < securityConstraints.length; i++) { context.removeConstraint(securityConstraints[i]); } // Removing Ejbs /* ContextEjb[] contextEjbs = context.findEjbs(); for (i = 0; i < contextEjbs.length; i++) { context.removeEjb(contextEjbs[i].getName()); } */ // Removing environments /* ContextEnvironment[] contextEnvironments = context.findEnvironments(); for (i = 0; i < contextEnvironments.length; i++) { context.removeEnvironment(contextEnvironments[i].getName()); } */ // Removing errors pages ErrorPage[] errorPages = context.findErrorPages(); for (i = 0; i < errorPages.length; i++) { context.removeErrorPage(errorPages[i]); } // Removing filter defs FilterDef[] filterDefs = context.findFilterDefs(); for (i = 0; i < filterDefs.length; i++) { context.removeFilterDef(filterDefs[i]); } // Removing filter maps FilterMap[] filterMaps = context.findFilterMaps(); for (i = 0; i < filterMaps.length; i++) { context.removeFilterMap(filterMaps[i]); } // Removing local ejbs /* ContextLocalEjb[] contextLocalEjbs = context.findLocalEjbs(); for (i = 0; i < contextLocalEjbs.length; i++) { context.removeLocalEjb(contextLocalEjbs[i].getName()); } */ // Removing Mime mappings String[] mimeMappings = context.findMimeMappings(); for (i = 0; i < mimeMappings.length; i++) { context.removeMimeMapping(mimeMappings[i]); } // Removing parameters String[] parameters = context.findParameters(); for (i = 0; i < parameters.length; i++) { context.removeParameter(parameters[i]); } // Removing resource env refs /* String[] resourceEnvRefs = context.findResourceEnvRefs(); for (i = 0; i < resourceEnvRefs.length; i++) { context.removeResourceEnvRef(resourceEnvRefs[i]); } */ // Removing resource links /* ContextResourceLink[] contextResourceLinks = context.findResourceLinks(); for (i = 0; i < contextResourceLinks.length; i++) { context.removeResourceLink(contextResourceLinks[i].getName()); } */ // Removing resources /* ContextResource[] contextResources = context.findResources(); for (i = 0; i < contextResources.length; i++) { context.removeResource(contextResources[i].getName()); } */ // Removing security role String[] securityRoles = context.findSecurityRoles(); for (i = 0; i < securityRoles.length; i++) { context.removeSecurityRole(securityRoles[i]); } // Removing servlet mappings String[] servletMappings = context.findServletMappings(); for (i = 0; i < servletMappings.length; i++) { context.removeServletMapping(servletMappings[i]); } // FIXME : Removing status pages // Removing welcome files String[] welcomeFiles = context.findWelcomeFiles(); for (i = 0; i < welcomeFiles.length; i++) { context.removeWelcomeFile(welcomeFiles[i]); } // Removing wrapper lifecycles String[] wrapperLifecycles = context.findWrapperLifecycles(); for (i = 0; i < wrapperLifecycles.length; i++) { context.removeWrapperLifecycle(wrapperLifecycles[i]); } // Removing wrapper listeners String[] wrapperListeners = context.findWrapperListeners(); for (i = 0; i < wrapperListeners.length; i++) { context.removeWrapperListener(wrapperListeners[i]); } // Remove (partially) folders and files created by antiLocking if (antiLockingDocBase != null) { // No need to log failure - it is expected in this case ExpandWar.delete(antiLockingDocBase, false); } // Reset ServletContextInitializer scanning initializerClassMap.clear(); typeInitializerMap.clear(); ok = true; } /** * Process a "destroy" event for this Context. */ protected synchronized void destroy() { // Called from StandardContext.destroy() if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.destroy")); } // Skip clearing the work directory if Tomcat is being shutdown Server s = getServer(); if (s != null && !s.getState().isAvailable()) { return; } // Changed to getWorkPath per Bugzilla 35819. if (context instanceof StandardContext) { String workDir = ((StandardContext) context).getWorkPath(); if (workDir != null) { ExpandWar.delete(new File(workDir)); } } } private Server getServer() { Container c = context; while (c != null && !(c instanceof Engine)) { c = c.getParent(); } if (c == null) { return null; } Service s = ((Engine)c).getService(); if (s == null) { return null; } return s.getServer(); } /** * Validate the usage of security role names in the web application * deployment descriptor. If any problems are found, issue warning * messages (for backwards compatibility) and add the missing roles. * (To make these problems fatal instead, simply set the <code>ok</code> * instance variable to <code>false</code> as well). */ protected void validateSecurityRoles() { // Check role names used in <security-constraint> elements SecurityConstraint constraints[] = context.findConstraints(); for (int i = 0; i < constraints.length; i++) { String roles[] = constraints[i].findAuthRoles(); for (int j = 0; j < roles.length; j++) { if (!"*".equals(roles[j]) && !context.findSecurityRole(roles[j])) { log.info(sm.getString("contextConfig.role.auth", roles[j])); context.addSecurityRole(roles[j]); } } } // Check role names used in <servlet> elements Container wrappers[] = context.findChildren(); for (int i = 0; i < wrappers.length; i++) { Wrapper wrapper = (Wrapper) wrappers[i]; String runAs = wrapper.getRunAs(); if ((runAs != null) && !context.findSecurityRole(runAs)) { log.info(sm.getString("contextConfig.role.runas", runAs)); context.addSecurityRole(runAs); } String names[] = wrapper.findSecurityReferences(); for (int j = 0; j < names.length; j++) { String link = wrapper.findSecurityReference(names[j]); if ((link != null) && !context.findSecurityRole(link)) { log.info(sm.getString("contextConfig.role.link", link)); context.addSecurityRole(link); } } } } protected File getHostConfigBase() { File file = null; if (context.getParent() instanceof Host) { file = ((Host)context.getParent()).getConfigBaseFile(); } return file; } /** * Scan the web.xml files that apply to the web application and merge them * using the rules defined in the spec. For the global web.xml files, * where there is duplicate configuration, the most specific level wins. ie * an application's web.xml takes precedence over the host level or global * web.xml file. */ protected void webConfig() { /* * Anything and everything can override the global and host defaults. * This is implemented in two parts * - Handle as a web fragment that gets added after everything else so * everything else takes priority * - Mark Servlets as overridable so SCI configuration can replace * configuration from the defaults */ /* * The rules for annotation scanning are not as clear-cut as one might * think. Tomcat implements the following process: * - As per SRV.1.6.2, Tomcat will scan for annotations regardless of * which Servlet spec version is declared in web.xml. The EG has * confirmed this is the expected behaviour. * - As per http://java.net/jira/browse/SERVLET_SPEC-36, if the main * web.xml is marked as metadata-complete, JARs are still processed * for SCIs. * - If metadata-complete=true and an absolute ordering is specified, * JARs excluded from the ordering are also excluded from the SCI * processing. * - If an SCI has a @HandlesType annotation then all classes (except * those in JARs excluded from an absolute ordering) need to be * scanned to check if they match. */ Set<WebXml> defaults = new HashSet<>(); defaults.add(getDefaultWebXmlFragment()); WebXml webXml = createWebXml(); // Parse context level web.xml InputSource contextWebXml = getContextWebXmlSource(); parseWebXml(contextWebXml, webXml, false); ServletContext sContext = context.getServletContext(); // Ordering is important here // Step 1. Identify all the JARs packaged with the application and those // provided by the container. If any of the application JARs have a // web-fragment.xml it will be parsed at this point. web-fragment.xml // files are ignored for container provided JARs. Map<String,WebXml> fragments = processJarsForWebFragments(); // Step 2. Order the fragments. Set<WebXml> orderedFragments = null; orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext); // Step 3. Look for ServletContainerInitializer implementations if (ok) { processServletContainerInitializers(orderedFragments); } if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) { // Step 4. Process /WEB-INF/classes for annotations if (ok) { WebResource[] webResources = context.getResources().listResources("/WEB-INF/classes"); for (WebResource webResource : webResources) { processAnnotationsWebResource(webResource, webXml, webXml.isMetadataComplete()); } } // Step 5. Process JARs for annotations - only need to process // those fragments we are going to use if (ok) { processAnnotations( orderedFragments, webXml.isMetadataComplete()); } // Cache, if used, is no longer required so clear it javaClassCache.clear(); } if (!webXml.isMetadataComplete()) { // Step 6. Merge web-fragment.xml files into the main web.xml // file. if (ok) { ok = webXml.merge(orderedFragments); } // Step 7. Apply global defaults // Have to merge defaults before JSP conversion since defaults // provide JSP servlet definition. webXml.merge(defaults); // Step 8. Convert explicitly mentioned jsps to servlets if (ok) { convertJsps(webXml); } // Step 9. Apply merged web.xml to Context if (ok) { configureContext(webXml); } } else { webXml.merge(defaults); convertJsps(webXml); configureContext(webXml); } // Step 9a. Make the merged web.xml available to other // components, specifically Jasper, to save those components // from having to re-generate it. // TODO Use a ServletContainerInitializer for Jasper String mergedWebXml = webXml.toXml(); sContext.setAttribute( org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML, mergedWebXml); if (context.getLogEffectiveWebXml()) { log.info("web.xml:\n" + mergedWebXml); } // Always need to look for static resources // Step 10. Look for static resources packaged in JARs if (ok) { // Spec does not define an order. // Use ordered JARs followed by remaining JARs Set<WebXml> resourceJars = new LinkedHashSet<>(); if (orderedFragments != null) { for (WebXml fragment : orderedFragments) { resourceJars.add(fragment); } } for (WebXml fragment : fragments.values()) { if (!resourceJars.contains(fragment)) { resourceJars.add(fragment); } } processResourceJARs(resourceJars); // See also StandardContext.resourcesStart() for // WEB-INF/classes/META-INF/resources configuration } // Step 11. Apply the ServletContainerInitializer config to the // context if (ok) { for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializerClassMap.entrySet()) { if (entry.getValue().isEmpty()) { context.addServletContainerInitializer( entry.getKey(), null); } else { context.addServletContainerInitializer( entry.getKey(), entry.getValue()); } } } } private void configureContext(WebXml webxml) { // As far as possible, process in alphabetical order so it is easy to // check everything is present // Some validation depends on correct public ID context.setPublicId(webxml.getPublicId()); // Everything else in order context.setEffectiveMajorVersion(webxml.getMajorVersion()); context.setEffectiveMinorVersion(webxml.getMinorVersion()); for (Entry<String, String> entry : webxml.getContextParams().entrySet()) { context.addParameter(entry.getKey(), entry.getValue()); } context.setDenyUncoveredHttpMethods( webxml.getDenyUncoveredHttpMethods()); context.setDisplayName(webxml.getDisplayName()); context.setDistributable(webxml.isDistributable()); for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) { context.getNamingResources().addLocalEjb(ejbLocalRef); } for (ContextEjb ejbRef : webxml.getEjbRefs().values()) { context.getNamingResources().addEjb(ejbRef); } for (ContextEnvironment environment : webxml.getEnvEntries().values()) { context.getNamingResources().addEnvironment(environment); } for (ErrorPage errorPage : webxml.getErrorPages().values()) { context.addErrorPage(errorPage); } for (FilterDef filter : webxml.getFilters().values()) { if (filter.getAsyncSupported() == null) { filter.setAsyncSupported("false"); } context.addFilterDef(filter); } for (FilterMap filterMap : webxml.getFilterMappings()) { context.addFilterMap(filterMap); } for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) { JspPropertyGroupDescriptor descriptor = new ApplicationJspPropertyGroupDescriptor(jspPropertyGroup); context.getJspConfigDescriptor().getJspPropertyGroups().add( descriptor); } for (String listener : webxml.getListeners()) { context.addApplicationListener( new ApplicationListener(listener, false)); } for (Entry<String, String> entry : webxml.getLocaleEncodingMappings().entrySet()) { context.addLocaleEncodingMappingParameter(entry.getKey(), entry.getValue()); } // Prevents IAE if (webxml.getLoginConfig() != null) { context.setLoginConfig(webxml.getLoginConfig()); } for (MessageDestinationRef mdr : webxml.getMessageDestinationRefs().values()) { context.getNamingResources().addMessageDestinationRef(mdr); } // messageDestinations were ignored in Tomcat 6, so ignore here context.setIgnoreAnnotations(webxml.isMetadataComplete()); for (Entry<String, String> entry : webxml.getMimeMappings().entrySet()) { context.addMimeMapping(entry.getKey(), entry.getValue()); } // Name is just used for ordering for (ContextResourceEnvRef resource : webxml.getResourceEnvRefs().values()) { context.getNamingResources().addResourceEnvRef(resource); } for (ContextResource resource : webxml.getResourceRefs().values()) { context.getNamingResources().addResource(resource); } boolean allAuthenticatedUsersIsAppRole = webxml.getSecurityRoles().contains( SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS); for (SecurityConstraint constraint : webxml.getSecurityConstraints()) { if (allAuthenticatedUsersIsAppRole) { constraint.treatAllAuthenticatedUsersAsApplicationRole(); } context.addConstraint(constraint); } for (String role : webxml.getSecurityRoles()) { context.addSecurityRole(role); } for (ContextService service : webxml.getServiceRefs().values()) { context.getNamingResources().addService(service); } for (ServletDef servlet : webxml.getServlets().values()) { Wrapper wrapper = context.createWrapper(); // Description is ignored // Display name is ignored // Icons are ignored // jsp-file gets passed to the JSP Servlet as an init-param if (servlet.getLoadOnStartup() != null) { wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue()); } if (servlet.getEnabled() != null) { wrapper.setEnabled(servlet.getEnabled().booleanValue()); } wrapper.setName(servlet.getServletName()); Map<String,String> params = servlet.getParameterMap(); for (Entry<String, String> entry : params.entrySet()) { wrapper.addInitParameter(entry.getKey(), entry.getValue()); } wrapper.setRunAs(servlet.getRunAs()); Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs(); for (SecurityRoleRef roleRef : roleRefs) { wrapper.addSecurityReference( roleRef.getName(), roleRef.getLink()); } wrapper.setServletClass(servlet.getServletClass()); MultipartDef multipartdef = servlet.getMultipartDef(); if (multipartdef != null) { if (multipartdef.getMaxFileSize() != null && multipartdef.getMaxRequestSize()!= null && multipartdef.getFileSizeThreshold() != null) { wrapper.setMultipartConfigElement(new MultipartConfigElement( multipartdef.getLocation(), Long.parseLong(multipartdef.getMaxFileSize()), Long.parseLong(multipartdef.getMaxRequestSize()), Integer.parseInt( multipartdef.getFileSizeThreshold()))); } else { wrapper.setMultipartConfigElement(new MultipartConfigElement( multipartdef.getLocation())); } } if (servlet.getAsyncSupported() != null) { wrapper.setAsyncSupported( servlet.getAsyncSupported().booleanValue()); } wrapper.setOverridable(servlet.isOverridable()); context.addChild(wrapper); } for (Entry<String, String> entry : webxml.getServletMappings().entrySet()) { context.addServletMapping(entry.getKey(), entry.getValue()); } SessionConfig sessionConfig = webxml.getSessionConfig(); if (sessionConfig != null) { if (sessionConfig.getSessionTimeout() != null) { context.setSessionTimeout( sessionConfig.getSessionTimeout().intValue()); } SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig(); scc.setName(sessionConfig.getCookieName()); scc.setDomain(sessionConfig.getCookieDomain()); scc.setPath(sessionConfig.getCookiePath()); scc.setComment(sessionConfig.getCookieComment()); if (sessionConfig.getCookieHttpOnly() != null) { scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue()); } if (sessionConfig.getCookieSecure() != null) { scc.setSecure(sessionConfig.getCookieSecure().booleanValue()); } if (sessionConfig.getCookieMaxAge() != null) { scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue()); } if (sessionConfig.getSessionTrackingModes().size() > 0) { context.getServletContext().setSessionTrackingModes( sessionConfig.getSessionTrackingModes()); } } for (Entry<String, String> entry : webxml.getTaglibs().entrySet()) { TaglibDescriptor descriptor = new ApplicationTaglibDescriptor( entry.getValue(), entry.getKey()); context.getJspConfigDescriptor().getTaglibs().add(descriptor); } // Context doesn't use version directly for (String welcomeFile : webxml.getWelcomeFiles()) { /* * The following will result in a welcome file of "" so don't add * that to the context * <welcome-file-list> * <welcome-file/> * </welcome-file-list> */ if (welcomeFile != null && welcomeFile.length() > 0) { context.addWelcomeFile(welcomeFile); } } // Do this last as it depends on servlets for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) { String jspServletName = context.findServletMapping("*.jsp"); if (jspServletName == null) { jspServletName = "jsp"; } if (context.findChild(jspServletName) != null) { for (String urlPattern : jspPropertyGroup.getUrlPatterns()) { context.addServletMapping(urlPattern, jspServletName, true); } } else { if(log.isDebugEnabled()) { for (String urlPattern : jspPropertyGroup.getUrlPatterns()) { log.debug("Skiping " + urlPattern + " , no servlet " + jspServletName); } } } } for (Entry<String, String> entry : webxml.getPostConstructMethods().entrySet()) { context.addPostConstructMethod(entry.getKey(), entry.getValue()); } for (Entry<String, String> entry : webxml.getPreDestroyMethods().entrySet()) { context.addPreDestroyMethod(entry.getKey(), entry.getValue()); } } private WebXml getDefaultWebXmlFragment() { // Host should never be null Host host = (Host) context.getParent(); DefaultWebXmlCacheEntry entry = hostWebXmlCache.get(host); InputSource globalWebXml = getGlobalWebXmlSource(); InputSource hostWebXml = getHostWebXmlSource(); long globalTimeStamp = 0; long hostTimeStamp = 0; if (globalWebXml != null) { try { URL url = new URL(globalWebXml.getSystemId()); globalTimeStamp = url.openConnection().getLastModified(); } catch (MalformedURLException e) { globalTimeStamp = -1; } catch (IOException e) { globalTimeStamp = -1; } } if (hostWebXml != null) { try { URL url = new URL(hostWebXml.getSystemId()); hostTimeStamp = url.openConnection().getLastModified(); } catch (MalformedURLException e) { hostTimeStamp = -1; } catch (IOException e) { hostTimeStamp = -1; } } if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp && entry.getHostTimeStamp() == hostTimeStamp) { return entry.getWebXml(); } // Parsing global web.xml is relatively expensive. Use a sync block to // make sure it only happens once. Use the pipeline since a lock will // already be held on the host by another thread synchronized (host.getPipeline()) { entry = hostWebXmlCache.get(host); if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp && entry.getHostTimeStamp() == hostTimeStamp) { return entry.getWebXml(); } WebXml webXmlDefaultFragment = createWebXml(); webXmlDefaultFragment.setOverridable(true); // Set to distributable else every app will be prevented from being // distributable when the default fragment is merged with the main // web.xml webXmlDefaultFragment.setDistributable(true); // When merging, the default welcome files are only used if the app has // not defined any welcomes files. webXmlDefaultFragment.setAlwaysAddWelcomeFiles(false); // Parse global web.xml if present if (globalWebXml == null) { // This is unusual enough to log log.info(sm.getString("contextConfig.defaultMissing")); } else { parseWebXml(globalWebXml, webXmlDefaultFragment, false); } // Parse host level web.xml if present // Additive apart from welcome pages webXmlDefaultFragment.setReplaceWelcomeFiles(true); parseWebXml(hostWebXml, webXmlDefaultFragment, false); // Don't update the cache if an error occurs if (globalTimeStamp != -1 && hostTimeStamp != -1) { entry = new DefaultWebXmlCacheEntry(webXmlDefaultFragment, globalTimeStamp, hostTimeStamp); hostWebXmlCache.put(host, entry); } return webXmlDefaultFragment; } } private void convertJsps(WebXml webXml) { Map<String,String> jspInitParams; ServletDef jspServlet = webXml.getServlets().get("jsp"); if (jspServlet == null) { jspInitParams = new HashMap<>(); Wrapper w = (Wrapper) context.findChild("jsp"); if (w != null) { String[] params = w.findInitParameters(); for (String param : params) { jspInitParams.put(param, w.findInitParameter(param)); } } } else { jspInitParams = jspServlet.getParameterMap(); } for (ServletDef servletDef: webXml.getServlets().values()) { if (servletDef.getJspFile() != null) { convertJsp(servletDef, jspInitParams); } } } private void convertJsp(ServletDef servletDef, Map<String,String> jspInitParams) { servletDef.setServletClass(org.apache.catalina.core.Constants.JSP_SERVLET_CLASS); String jspFile = servletDef.getJspFile(); if ((jspFile != null) && !jspFile.startsWith("/")) { if (context.isServlet22()) { if(log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.jspFile.warning", jspFile)); } jspFile = "/" + jspFile; } else { throw new IllegalArgumentException (sm.getString("contextConfig.jspFile.error", jspFile)); } } servletDef.getParameterMap().put("jspFile", jspFile); servletDef.setJspFile(null); for (Map.Entry<String, String> initParam: jspInitParams.entrySet()) { servletDef.addInitParameter(initParam.getKey(), initParam.getValue()); } } protected WebXml createWebXml() { return new WebXml(); } /** * Scan JARs for ServletContainerInitializer implementations. * Implementations will be added in web-fragment.xml priority order. */ protected void processServletContainerInitializers( Set<WebXml> fragments) { for (WebXml fragment : fragments) { URL url = fragment.getURL(); Jar jar = null; InputStream is = null; ServletContainerInitializer sci = null; try { if ("jar".equals(url.getProtocol())) { jar = JarFactory.newInstance(url); is = jar.getInputStream(SCI_LOCATION); } else if ("file".equals(url.getProtocol())) { String path = url.getPath(); File file = new File(path, SCI_LOCATION); if (file.exists()) { is = new FileInputStream(file); } } if (is != null) { sci = getServletContainerInitializer(is); } } catch (IOException ioe) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", url, context.getName())); ok = false; return; } finally { if (is != null) { try { is.close(); } catch (IOException e) { // Ignore } } if (jar != null) { jar.close(); } } if (sci == null) { continue; } initializerClassMap.put(sci, new HashSet<Class<?>>()); HandlesTypes ht = null; try { ht = sci.getClass().getAnnotation(HandlesTypes.class); } catch (Exception e) { if (log.isDebugEnabled()) { log.info(sm.getString("contextConfig.sci.debug", url), e); } else { log.info(sm.getString("contextConfig.sci.info", url)); } } if (ht != null) { Class<?>[] types = ht.value(); if (types != null) { for (Class<?> type : types) { if (type.isAnnotation()) { handlesTypesAnnotations = true; } else { handlesTypesNonAnnotations = true; } Set<ServletContainerInitializer> scis = typeInitializerMap.get(type); if (scis == null) { scis = new HashSet<>(); typeInitializerMap.put(type, scis); } scis.add(sci); } } } } } /** * Extract the name of the ServletContainerInitializer. * * @param is The resource where the name is defined * @return The class name * @throws IOException */ protected ServletContainerInitializer getServletContainerInitializer( InputStream is) throws IOException { String className = null; if (is != null) { String line = null; try { BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); line = br.readLine(); if (line != null && line.trim().length() > 0) { className = line.trim(); } } catch (UnsupportedEncodingException e) { // Should never happen with UTF-8 // If it does - ignore & return null } } ServletContainerInitializer sci = null; try { Class<?> clazz = Class.forName(className,true, context.getLoader().getClassLoader()); sci = (ServletContainerInitializer) clazz.newInstance(); } catch (ClassNotFoundException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (InstantiationException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } catch (IllegalAccessException e) { log.error(sm.getString("contextConfig.invalidSci", className), e); throw new IOException(e); } return sci; } /** * Scan JARs that contain web-fragment.xml files that will be used to * configure this application to see if they also contain static resources. * If static resources are found, add them to the context. Resources are * added in web-fragment.xml priority order. */ protected void processResourceJARs(Set<WebXml> fragments) { for (WebXml fragment : fragments) { URL url = fragment.getURL(); Jar jar = null; try { // Note: Ignore file URLs for now since only jar URLs will be accepted if ("jar".equals(url.getProtocol())) { jar = JarFactory.newInstance(url); jar.nextEntry(); String entryName = jar.getEntryName(); while (entryName != null) { if (entryName.startsWith("META-INF/resources/")) { context.getResources().createWebResourceSet( WebResourceRoot.ResourceSetType.RESOURCE_JAR, url, "/", "/META-INF/resources"); break; } jar.nextEntry(); entryName = jar.getEntryName(); } } else if ("file".equals(url.getProtocol())) { File file = new File(url.toURI()); File resources = new File(file, "META-INF/resources/"); if (resources.isDirectory()) { context.getResources().createWebResourceSet( WebResourceRoot.ResourceSetType.RESOURCE_JAR, file.getAbsolutePath(), "/", "/"); } } } catch (IOException ioe) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); } catch (URISyntaxException e) { log.error(sm.getString("contextConfig.resourceJarFail", url, context.getName())); } finally { if (jar != null) { jar.close(); } } } } /** * Identify the default web.xml to be used and obtain an input source for * it. */ protected InputSource getGlobalWebXmlSource() { // Is a default web.xml specified for the Context? if (defaultWebXml == null && context instanceof StandardContext) { defaultWebXml = ((StandardContext) context).getDefaultWebXml(); } // Set the default if we don't have any overrides if (defaultWebXml == null) { getDefaultWebXml(); } // Is it explicitly suppressed, e.g. in embedded environment? if (Constants.NoDefaultWebXml.equals(defaultWebXml)) { return null; } return getWebXmlSource(defaultWebXml, context.getCatalinaBase().getPath()); } /** * Identify the host web.xml to be used and obtain an input source for * it. */ protected InputSource getHostWebXmlSource() { File hostConfigBase = getHostConfigBase(); if (hostConfigBase == null) return null; return getWebXmlSource(Constants.HostWebXml, hostConfigBase.getPath()); } /** * Identify the application web.xml to be used and obtain an input source * for it. */ @SuppressWarnings("resource") // stream is meant to be left open here protected InputSource getContextWebXmlSource() { InputStream stream = null; InputSource source = null; URL url = null; String altDDName = null; // Open the application web.xml file, if it exists ServletContext servletContext = context.getServletContext(); if (servletContext != null) { altDDName = (String)servletContext.getAttribute( Globals.ALT_DD_ATTR); if (altDDName != null) { try { stream = new FileInputStream(altDDName); url = new File(altDDName).toURI().toURL(); } catch (FileNotFoundException e) { log.error(sm.getString("contextConfig.altDDNotFound", altDDName)); } catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); } } else { stream = servletContext.getResourceAsStream (Constants.ApplicationWebXml); try { url = servletContext.getResource( Constants.ApplicationWebXml); } catch (MalformedURLException e) { log.error(sm.getString("contextConfig.applicationUrl")); } } } if (stream == null || url == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.applicationMissing") + " " + context); } if (stream != null) { try { stream.close(); } catch (IOException e) { // Ignore } } } else { source = new InputSource(url.toExternalForm()); source.setByteStream(stream); } return source; } /** * * @param filename Name of the file (possibly with one or more leading path * segments) to read * @param path Location that filename is relative to */ protected InputSource getWebXmlSource(String filename, String path) { File file = new File(filename); if (!file.isAbsolute()) { file = new File(path, filename); } InputStream stream = null; InputSource source = null; try { if (!file.exists()) { // Use getResource and getResourceAsStream stream = getClass().getClassLoader().getResourceAsStream(filename); if(stream != null) { source = new InputSource(getClass().getClassLoader().getResource( filename).toURI().toString()); } } else { source = new InputSource(file.getAbsoluteFile().toURI().toString()); stream = new FileInputStream(file); } if (stream != null && source != null) { source.setByteStream(stream); } } catch (Exception e) { log.error(sm.getString( "contextConfig.defaultError", filename, file), e); } return source; } /** * Parses the given source and stores the parsed data in the given web.xml * representation. The byte stream will be closed at the end of the parse * operation. * * @param source Input source containing the XML data to be parsed * @param dest The object representation of common elements of web.xml and * web-fragment.xml * @param fragment Specifies whether the source is web-fragment.xml or * web.xml */ protected void parseWebXml(InputSource source, WebXml dest, boolean fragment) { if (source == null) { return; } XmlErrorHandler handler = new XmlErrorHandler(); Digester digester; WebRuleSet ruleSet; if (fragment) { digester = webFragmentDigester; ruleSet = webFragmentRuleSet; } else { digester = webDigester; ruleSet = webRuleSet; } digester.push(dest); digester.setErrorHandler(handler); if(log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.applicationStart", source.getSystemId())); } try { digester.parse(source); if (handler.getWarnings().size() > 0 || handler.getErrors().size() > 0) { ok = false; handler.logFindings(log, source.getSystemId()); } } catch (SAXParseException e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); log.error(sm.getString("contextConfig.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; } catch (Exception e) { log.error(sm.getString("contextConfig.applicationParse", source.getSystemId()), e); ok = false; } finally { digester.reset(); ruleSet.recycle(); InputStream is = source.getByteStream(); if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } /** * Scan /WEB-INF/lib for JARs and for each one found add it and any * /META-INF/web-fragment.xml to the resulting Map. web-fragment.xml files * will be parsed before being added to the map. Every JAR will be added and * <code>null</code> will be used if no web-fragment.xml was found. Any JARs * known not contain fragments will be skipped. * * @return A map of JAR name to processed web fragment (if any) */ protected Map<String,WebXml> processJarsForWebFragments() { JarScanner jarScanner = context.getJarScanner(); FragmentJarScannerCallback callback = new FragmentJarScannerCallback(); jarScanner.scan(JarScanType.PLUGGABILITY, context.getServletContext(), callback); return callback.getFragments(); } protected void processAnnotations(Set<WebXml> fragments, boolean handlesTypesOnly) { for(WebXml fragment : fragments) { if (fragment.getWebappJar()) { // Only web application JARs should be scanned for deployment // annotations WebXml annotations = new WebXml(); // no impact on distributable annotations.setDistributable(true); URL url = fragment.getURL(); processAnnotationsUrl(url, annotations, (handlesTypesOnly || fragment.isMetadataComplete())); Set<WebXml> set = new HashSet<>(); set.add(annotations); // Merge annotations into fragment - fragment takes priority fragment.merge(set); } } } protected void processAnnotationsWebResource(WebResource webResource, WebXml fragment, boolean handlesTypesOnly) { if (webResource.isDirectory()) { WebResource[] webResources = webResource.getWebResourceRoot().listResources( webResource.getWebappPath()); for (WebResource r : webResources) { processAnnotationsWebResource(r, fragment, handlesTypesOnly); } } else if (webResource.isFile() && webResource.getName().endsWith(".class")) { InputStream is = null; try { is = webResource.getInputStream(); processAnnotationsStream(is, fragment, handlesTypesOnly); } catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamWebResource", webResource.getWebappPath()),e); } catch (ClassFormatException e) { log.error(sm.getString("contextConfig.inputStreamWebResource", webResource.getWebappPath()),e); } finally { if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } protected void processAnnotationsUrl(URL url, WebXml fragment, boolean handlesTypesOnly) { if (url == null) { // Nothing to do. return; } else if ("jar".equals(url.getProtocol())) { processAnnotationsJar(url, fragment, handlesTypesOnly); } else if ("file".equals(url.getProtocol())) { try { processAnnotationsFile( new File(url.toURI()), fragment, handlesTypesOnly); } catch (URISyntaxException e) { log.error(sm.getString("contextConfig.fileUrl", url), e); } } else { log.error(sm.getString("contextConfig.unknownUrlProtocol", url.getProtocol(), url)); } } protected void processAnnotationsJar(URL url, WebXml fragment, boolean handlesTypesOnly) { Jar jar = null; InputStream is; try { jar = JarFactory.newInstance(url); jar.nextEntry(); String entryName = jar.getEntryName(); while (entryName != null) { if (entryName.endsWith(".class")) { is = null; try { is = jar.getEntryInputStream(); processAnnotationsStream( is, fragment, handlesTypesOnly); } catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamJar", entryName, url),e); } catch (ClassFormatException e) { log.error(sm.getString("contextConfig.inputStreamJar", entryName, url),e); } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } } } jar.nextEntry(); entryName = jar.getEntryName(); } } catch (IOException e) { log.error(sm.getString("contextConfig.jarFile", url), e); } finally { if (jar != null) { jar.close(); } } } protected void processAnnotationsFile(File file, WebXml fragment, boolean handlesTypesOnly) { if (file.isDirectory()) { String[] dirs = file.list(); for (String dir : dirs) { processAnnotationsFile( new File(file,dir), fragment, handlesTypesOnly); } } else if (file.canRead() && file.getName().endsWith(".class")) { FileInputStream fis = null; try { fis = new FileInputStream(file); processAnnotationsStream(fis, fragment, handlesTypesOnly); } catch (IOException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); } catch (ClassFormatException e) { log.error(sm.getString("contextConfig.inputStreamFile", file.getAbsolutePath()),e); } finally { if (fis != null) { try { fis.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } } } protected void processAnnotationsStream(InputStream is, WebXml fragment, boolean handlesTypesOnly) throws ClassFormatException, IOException { ClassParser parser = new ClassParser(is, null); JavaClass clazz = parser.parse(); checkHandlesTypes(clazz); if (handlesTypesOnly) { return; } String className = clazz.getClassName(); AnnotationEntry[] annotationsEntries = clazz.getAnnotationEntries(); for (AnnotationEntry ae : annotationsEntries) { String type = ae.getAnnotationType(); if ("Ljavax/servlet/annotation/WebServlet;".equals(type)) { processAnnotationWebServlet(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebFilter;".equals(type)) { processAnnotationWebFilter(className, ae, fragment); }else if ("Ljavax/servlet/annotation/WebListener;".equals(type)) { fragment.addListener(className); } else { // Unknown annotation - ignore } } } /** * For classes packaged with the web application, the class and each * super class needs to be checked for a match with {@link HandlesTypes} or * for an annotation that matches {@link HandlesTypes}. * @param javaClass */ protected void checkHandlesTypes(JavaClass javaClass) { // Skip this if we can if (typeInitializerMap.size() == 0) { return; } if ((javaClass.getAccessFlags() & org.apache.tomcat.util.bcel.Constants.ACC_ANNOTATION) > 0) { // Skip annotations. return; } String className = javaClass.getClassName(); Class<?> clazz = null; if (handlesTypesNonAnnotations) { // This *might* be match for a HandlesType. populateJavaClassCache(className, javaClass); JavaClassCacheEntry entry = javaClassCache.get(className); if (entry.getSciSet() == null) { try { populateSCIsForCacheEntry(entry); } catch (StackOverflowError soe) { throw new IllegalStateException(sm.getString( "contextConfig.annotationsStackOverflow", context.getName(), classHierarchyToString(className, entry))); } } if (entry.getSciSet().size() > 0) { // Need to try and load the class clazz = Introspection.loadClass(context, className); if (clazz == null) { // Can't load the class so no point continuing return; } for (ServletContainerInitializer sci : entry.getSciSet()) { Set<Class<?>> classes = initializerClassMap.get(sci); if (classes == null) { classes = new HashSet<>(); initializerClassMap.put(sci, classes); } classes.add(clazz); } } } if (handlesTypesAnnotations) { for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry : typeInitializerMap.entrySet()) { if (entry.getKey().isAnnotation()) { AnnotationEntry[] annotationEntries = javaClass.getAnnotationEntries(); for (AnnotationEntry annotationEntry : annotationEntries) { if (entry.getKey().getName().equals( getClassName(annotationEntry.getAnnotationType()))) { if (clazz == null) { clazz = Introspection.loadClass( context, className); if (clazz == null) { // Can't load the class so no point // continuing return; } } for (ServletContainerInitializer sci : entry.getValue()) { initializerClassMap.get(sci).add(clazz); } break; } } } } } } private String classHierarchyToString(String className, JavaClassCacheEntry entry) { JavaClassCacheEntry start = entry; StringBuilder msg = new StringBuilder(className); msg.append("->"); String parentName = entry.getSuperclassName(); JavaClassCacheEntry parent = javaClassCache.get(parentName); int count = 0; while (count < 100 && parent != null && parent != start) { msg.append(parentName); msg.append("->"); count ++; parentName = parent.getSuperclassName(); parent = javaClassCache.get(parentName); } msg.append(parentName); return msg.toString(); } private void populateJavaClassCache(String className, JavaClass javaClass) { if (javaClassCache.containsKey(className)) { return; } // Add this class to the cache javaClassCache.put(className, new JavaClassCacheEntry(javaClass)); populateJavaClassCache(javaClass.getSuperclassName()); for (String iterface : javaClass.getInterfaceNames()) { populateJavaClassCache(iterface); } } private void populateJavaClassCache(String className) { if (!javaClassCache.containsKey(className)) { String name = className.replace('.', '/') + ".class"; InputStream is = context.getLoader().getClassLoader().getResourceAsStream(name); if (is == null) { return; } ClassParser parser = new ClassParser(is, null); try { JavaClass clazz = parser.parse(); populateJavaClassCache(clazz.getClassName(), clazz); } catch (ClassFormatException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); } catch (IOException e) { log.debug(sm.getString("contextConfig.invalidSciHandlesTypes", className), e); } } } private void populateSCIsForCacheEntry(JavaClassCacheEntry cacheEntry) { Set<ServletContainerInitializer> result = new HashSet<>(); // Super class String superClassName = cacheEntry.getSuperclassName(); JavaClassCacheEntry superClassCacheEntry = javaClassCache.get(superClassName); // Avoid an infinite loop with java.lang.Object if (cacheEntry.equals(superClassCacheEntry)) { cacheEntry.setSciSet(new HashSet<ServletContainerInitializer>()); return; } // May be null of the class is not present or could not be loaded. if (superClassCacheEntry != null) { if (superClassCacheEntry.getSciSet() == null) { populateSCIsForCacheEntry(superClassCacheEntry); } result.addAll(superClassCacheEntry.getSciSet()); } result.addAll(getSCIsForClass(superClassName)); // Interfaces for (String interfaceName : cacheEntry.getInterfaceNames()) { JavaClassCacheEntry interfaceEntry = javaClassCache.get(interfaceName); // A null could mean that the class not present in application or // that there is nothing of interest. Either way, nothing to do here // so move along if (interfaceEntry != null) { if (interfaceEntry.getSciSet() == null) { populateSCIsForCacheEntry(interfaceEntry); } result.addAll(interfaceEntry.getSciSet()); } result.addAll(getSCIsForClass(interfaceName)); } cacheEntry.setSciSet(result); } private Set<ServletContainerInitializer> getSCIsForClass(String className) { for (Map.Entry<Class<?>, Set<ServletContainerInitializer>> entry : typeInitializerMap.entrySet()) { Class<?> clazz = entry.getKey(); if (!clazz.isAnnotation()) { if (clazz.getName().equals(className)) { return entry.getValue(); } } } return Collections.emptySet(); } private static final String getClassName(String internalForm) { if (!internalForm.startsWith("L")) { return internalForm; } // Assume starts with L, ends with ; and uses / rather than . return internalForm.substring(1, internalForm.length() - 1).replace('/', '.'); } protected void processAnnotationWebServlet(String className, AnnotationEntry ae, WebXml fragment) { String servletName = null; // must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81 ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("name".equals(name)) { servletName = evp.getValue().stringifyValue(); break; } } if (servletName == null) { // classname is default servletName as annotation has no name! servletName = className; } ServletDef servletDef = fragment.getServlets().get(servletName); boolean isWebXMLservletDef; if (servletDef == null) { servletDef = new ServletDef(); servletDef.setServletName(servletName); servletDef.setServletClass(className); isWebXMLservletDef = false; } else { isWebXMLservletDef = true; } boolean urlPatternsSet = false; String[] urlPatterns = null; // ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("value".equals(name) || "urlPatterns".equals(name)) { if (urlPatternsSet) { throw new IllegalArgumentException(sm.getString( "contextConfig.urlPatternValue", className)); } urlPatternsSet = true; urlPatterns = processAnnotationsStringArray(evp.getValue()); } else if ("description".equals(name)) { if (servletDef.getDescription() == null) { servletDef.setDescription(evp.getValue().stringifyValue()); } } else if ("displayName".equals(name)) { if (servletDef.getDisplayName() == null) { servletDef.setDisplayName(evp.getValue().stringifyValue()); } } else if ("largeIcon".equals(name)) { if (servletDef.getLargeIcon() == null) { servletDef.setLargeIcon(evp.getValue().stringifyValue()); } } else if ("smallIcon".equals(name)) { if (servletDef.getSmallIcon() == null) { servletDef.setSmallIcon(evp.getValue().stringifyValue()); } } else if ("asyncSupported".equals(name)) { if (servletDef.getAsyncSupported() == null) { servletDef.setAsyncSupported(evp.getValue() .stringifyValue()); } } else if ("loadOnStartup".equals(name)) { if (servletDef.getLoadOnStartup() == null) { servletDef .setLoadOnStartup(evp.getValue().stringifyValue()); } } else if ("initParams".equals(name)) { Map<String, String> initParams = processAnnotationWebInitParams(evp .getValue()); if (isWebXMLservletDef) { Map<String, String> webXMLInitParams = servletDef .getParameterMap(); for (Map.Entry<String, String> entry : initParams .entrySet()) { if (webXMLInitParams.get(entry.getKey()) == null) { servletDef.addInitParameter(entry.getKey(), entry .getValue()); } } } else { for (Map.Entry<String, String> entry : initParams .entrySet()) { servletDef.addInitParameter(entry.getKey(), entry .getValue()); } } } } if (!isWebXMLservletDef && urlPatterns != null) { fragment.addServlet(servletDef); } if (urlPatterns != null) { if (!fragment.getServletMappings().containsValue(servletName)) { for (String urlPattern : urlPatterns) { fragment.addServletMapping(urlPattern, servletName); } } } } /** * process filter annotation and merge with existing one! * FIXME: refactoring method too long and has redundant subroutines with * processAnnotationWebServlet! * @param className * @param ae * @param fragment */ protected void processAnnotationWebFilter(String className, AnnotationEntry ae, WebXml fragment) { String filterName = null; // must search for name s. Spec Servlet API 3.0 - 8.2.3.3.n.ii page 81 ElementValuePair[] evps = ae.getElementValuePairs(); for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("filterName".equals(name)) { filterName = evp.getValue().stringifyValue(); break; } } if (filterName == null) { // classname is default filterName as annotation has no name! filterName = className; } FilterDef filterDef = fragment.getFilters().get(filterName); FilterMap filterMap = new FilterMap(); boolean isWebXMLfilterDef; if (filterDef == null) { filterDef = new FilterDef(); filterDef.setFilterName(filterName); filterDef.setFilterClass(className); isWebXMLfilterDef = false; } else { isWebXMLfilterDef = true; } boolean urlPatternsSet = false; boolean servletNamesSet = false; boolean dispatchTypesSet = false; String[] urlPatterns = null; for (ElementValuePair evp : evps) { String name = evp.getNameString(); if ("value".equals(name) || "urlPatterns".equals(name)) { if (urlPatternsSet) { throw new IllegalArgumentException(sm.getString( "contextConfig.urlPatternValue", className)); } urlPatterns = processAnnotationsStringArray(evp.getValue()); urlPatternsSet = urlPatterns.length > 0; for (String urlPattern : urlPatterns) { filterMap.addURLPattern(urlPattern); } } else if ("servletNames".equals(name)) { String[] servletNames = processAnnotationsStringArray(evp .getValue()); servletNamesSet = servletNames.length > 0; for (String servletName : servletNames) { filterMap.addServletName(servletName); } } else if ("dispatcherTypes".equals(name)) { String[] dispatcherTypes = processAnnotationsStringArray(evp .getValue()); dispatchTypesSet = dispatcherTypes.length > 0; for (String dispatcherType : dispatcherTypes) { filterMap.setDispatcher(dispatcherType); } } else if ("description".equals(name)) { if (filterDef.getDescription() == null) { filterDef.setDescription(evp.getValue().stringifyValue()); } } else if ("displayName".equals(name)) { if (filterDef.getDisplayName() == null) { filterDef.setDisplayName(evp.getValue().stringifyValue()); } } else if ("largeIcon".equals(name)) { if (filterDef.getLargeIcon() == null) { filterDef.setLargeIcon(evp.getValue().stringifyValue()); } } else if ("smallIcon".equals(name)) { if (filterDef.getSmallIcon() == null) { filterDef.setSmallIcon(evp.getValue().stringifyValue()); } } else if ("asyncSupported".equals(name)) { if (filterDef.getAsyncSupported() == null) { filterDef .setAsyncSupported(evp.getValue().stringifyValue()); } } else if ("initParams".equals(name)) { Map<String, String> initParams = processAnnotationWebInitParams(evp .getValue()); if (isWebXMLfilterDef) { Map<String, String> webXMLInitParams = filterDef .getParameterMap(); for (Map.Entry<String, String> entry : initParams .entrySet()) { if (webXMLInitParams.get(entry.getKey()) == null) { filterDef.addInitParameter(entry.getKey(), entry .getValue()); } } } else { for (Map.Entry<String, String> entry : initParams .entrySet()) { filterDef.addInitParameter(entry.getKey(), entry .getValue()); } } } } if (!isWebXMLfilterDef) { fragment.addFilter(filterDef); if (urlPatternsSet || servletNamesSet) { filterMap.setFilterName(filterName); fragment.addFilterMapping(filterMap); } } if (urlPatternsSet || dispatchTypesSet) { Set<FilterMap> fmap = fragment.getFilterMappings(); FilterMap descMap = null; for (FilterMap map : fmap) { if (filterName.equals(map.getFilterName())) { descMap = map; break; } } if (descMap != null) { String[] urlsPatterns = descMap.getURLPatterns(); if (urlPatternsSet && (urlsPatterns == null || urlsPatterns.length == 0)) { for (String urlPattern : filterMap.getURLPatterns()) { descMap.addURLPattern(urlPattern); } } String[] dispatcherNames = descMap.getDispatcherNames(); if (dispatchTypesSet && (dispatcherNames == null || dispatcherNames.length == 0)) { for (String dis : filterMap.getDispatcherNames()) { descMap.setDispatcher(dis); } } } } } protected String[] processAnnotationsStringArray(ElementValue ev) { ArrayList<String> values = new ArrayList<>(); if (ev instanceof ArrayElementValue) { ElementValue[] arrayValues = ((ArrayElementValue) ev).getElementValuesArray(); for (ElementValue value : arrayValues) { values.add(value.stringifyValue()); } } else { values.add(ev.stringifyValue()); } String[] result = new String[values.size()]; return values.toArray(result); } protected Map<String,String> processAnnotationWebInitParams( ElementValue ev) { Map<String, String> result = new HashMap<>(); if (ev instanceof ArrayElementValue) { ElementValue[] arrayValues = ((ArrayElementValue) ev).getElementValuesArray(); for (ElementValue value : arrayValues) { if (value instanceof AnnotationElementValue) { ElementValuePair[] evps = ((AnnotationElementValue) value).getAnnotationEntry().getElementValuePairs(); String initParamName = null; String initParamValue = null; for (ElementValuePair evp : evps) { if ("name".equals(evp.getNameString())) { initParamName = evp.getValue().stringifyValue(); } else if ("value".equals(evp.getNameString())) { initParamValue = evp.getValue().stringifyValue(); } else { // Ignore } } result.put(initParamName, initParamValue); } } } return result; } private class FragmentJarScannerCallback implements JarScannerCallback { private static final String FRAGMENT_LOCATION = "META-INF/web-fragment.xml"; private final Map<String,WebXml> fragments = new HashMap<>(); @Override public void scan(JarURLConnection jarConn, boolean isWebapp) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); fragment.setWebappJar(isWebapp); if (context instanceof StandardContext) { fragment.setDelegate(((StandardContext) context).getDelegate()); } try { // Only web application JARs are checked for web-fragment.xml // files if (isWebapp) { jar = JarFactory.newInstance(url); is = jar.getInputStream(FRAGMENT_LOCATION); } if (is == null) { // If there is no web.xml, normal JAR no impact on // distributable fragment.setDistributable(true); } else { InputSource source = new InputSource( resourceURL.toString() + "!/" + FRAGMENT_LOCATION); source.setByteStream(is); parseWebXml(source, fragment, true); } } finally { if (jar != null) { jar.close(); } fragment.setURL(url); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragment.setJarName(extractJarFileName(url)); fragments.put(fragment.getName(), fragment); } } private String extractJarFileName(URL input) { String url = input.toString(); if (url.endsWith("!/")) { // Remove it url = url.substring(0, url.length() - 2); } // File name will now be whatever is after the final / return url.substring(url.lastIndexOf('/') + 1); } @Override public void scan(File file, boolean isWebapp) throws IOException { InputStream stream = null; WebXml fragment = new WebXml(); try { File fragmentFile = new File(file, FRAGMENT_LOCATION); if (fragmentFile.isFile()) { stream = new FileInputStream(fragmentFile); InputSource source = new InputSource(fragmentFile.toURI().toURL().toString()); source.setByteStream(stream); parseWebXml(source, fragment, true); } else { // If there is no web.xml, normal folder no impact on // distributable fragment.setDistributable(true); } } finally { fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragment.setJarName(file.getName()); fragments.put(fragment.getName(), fragment); } } @Override public void scanWebInfClasses() { // NO-OP. Fragments unpacked in WEB-INF classes are not handled, // mainly because if there are multiple fragments there is no way to // handle multiple web-fragment.xml files. } public Map<String,WebXml> getFragments() { return fragments; } } private static class DefaultWebXmlCacheEntry { private final WebXml webXml; private final long globalTimeStamp; private final long hostTimeStamp; public DefaultWebXmlCacheEntry(WebXml webXml, long globalTimeStamp, long hostTimeStamp) { this.webXml = webXml; this.globalTimeStamp = globalTimeStamp; this.hostTimeStamp = hostTimeStamp; } public WebXml getWebXml() { return webXml; } public long getGlobalTimeStamp() { return globalTimeStamp; } public long getHostTimeStamp() { return hostTimeStamp; } } private static class JavaClassCacheEntry { public final String superclassName; public final String[] interfaceNames; private Set<ServletContainerInitializer> sciSet = null; public JavaClassCacheEntry(JavaClass javaClass) { superclassName = javaClass.getSuperclassName(); interfaceNames = javaClass.getInterfaceNames(); } public String getSuperclassName() { return superclassName; } public String[] getInterfaceNames() { return interfaceNames; } public Set<ServletContainerInitializer> getSciSet() { return sciSet; } public void setSciSet(Set<ServletContainerInitializer> sciSet) { this.sciSet = sciSet; } } }
55,166
Bug 55166 schemaLocation references between servlet and jsp XSDs are invalid
The javax/servlet/resources package does not contain the JSP specification XSDs. These are referenced from the web-app or web-common xsds and define elements like <jsp-config>.
resolved fixed
f554475
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-08T09:33:59Z
2013-07-01T00:53:20Z
java/org/apache/catalina/startup/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.startup; /** * String constants for the startup package. * * @author Craig R. McClanahan * @author Jean-Francois Arcand * @version $Id$ */ public final class Constants { public static final String Package = "org.apache.catalina.startup"; public static final String ApplicationContextXml = "META-INF/context.xml"; public static final String ApplicationWebXml = "/WEB-INF/web.xml"; public static final String DefaultContextXml = "conf/context.xml"; public static final String DefaultWebXml = "conf/web.xml"; public static final String HostContextXml = "context.xml.default"; public static final String HostWebXml = "web.xml.default"; /** * A dummy value used to suppress loading the default web.xml file. * * <p> * It is useful when embedding Tomcat, when the default configuration is * done programmatically, e.g. by calling * <code>Tomcat.initWebappDefaults(context)</code>. * * @see Tomcat */ public static final String NoDefaultWebXml = "org/apache/catalina/startup/NO_DEFAULT_XML"; // J2EE public static final String J2eeSchemaPublicId_14 = "j2ee_1_4.xsd"; public static final String J2eeSchemaResourcePath_14 = "/javax/servlet/resources/j2ee_1_4.xsd"; public static final String JavaeeSchemaPublicId_5 = "javaee_5.xsd"; public static final String JavaeeSchemaResourcePath_5 = "/javax/servlet/resources/javaee_5.xsd"; public static final String JavaeeSchemaPublicId_6 = "javaee_6.xsd"; public static final String JavaeeSchemaResourcePath_6 = "/javax/servlet/resources/javaee_6.xsd"; public static final String JavaeeSchemaPublicId_7 = "javaee_7.xsd"; public static final String JavaeeSchemaResourcePath_7 = "/javax/servlet/resources/javaee_7.xsd"; // W3C public static final String W3cSchemaPublicId_10 = "xml.xsd"; public static final String W3cSchemaResourcePath_10 = "/javax/servlet/resources/xml.xsd"; public static final String W3cSchemaDTDPublicId_10 = "XMLSchema.dtd"; public static final String W3cSchemaDTDResourcePath_10 = "/javax/servlet/resources/XMLSchema.dtd"; public static final String W3cDatatypesDTDPublicId_10 = "datatypes.dtd"; public static final String W3cDatatypesDTDResourcePath_10 = "/javax/servlet/resources/datatypes.dtd"; // JSP public static final String JspSchemaPublicId_20 = "jsp_2_0.xsd"; public static final String JspSchemaResourcePath_20 = "/javax/servlet/jsp/resources/jsp_2_0.xsd"; public static final String JspSchemaPublicId_21 = "jsp_2_1.xsd"; public static final String JspSchemaResourcePath_21 = "/javax/servlet/jsp/resources/jsp_2_1.xsd"; public static final String JspSchemaPublicId_22 = "jsp_2_2.xsd"; public static final String JspSchemaResourcePath_22 = "/javax/servlet/jsp/resources/jsp_2_2.xsd"; public static final String JspSchemaPublicId_23 = "jsp_2_3.xsd"; public static final String JspSchemaResourcePath_23 = "/javax/servlet/jsp/resources/jsp_2_3.xsd"; // TLD public static final String TldDtdPublicId_11 = "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"; public static final String TldDtdResourcePath_11 = "/javax/servlet/jsp/resources/web-jsptaglibrary_1_1.dtd"; public static final String TldDtdPublicId_12 = "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"; public static final String TldDtdResourcePath_12 = "/javax/servlet/jsp/resources/web-jsptaglibrary_1_2.dtd"; public static final String TldSchemaPublicId_20 = "web-jsptaglibrary_2_0.xsd"; public static final String TldSchemaResourcePath_20 = "/javax/servlet/jsp/resources/web-jsptaglibrary_2_0.xsd"; public static final String TldSchemaPublicId_21 = "web-jsptaglibrary_2_1.xsd"; public static final String TldSchemaResourcePath_21 = "/javax/servlet/jsp/resources/web-jsptaglibrary_2_1.xsd"; // web.xml public static final String WebDtdPublicId_22 = "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"; public static final String WebDtdResourcePath_22 = "/javax/servlet/resources/web-app_2_2.dtd"; public static final String WebDtdPublicId_23 = "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"; public static final String WebDtdResourcePath_23 = "/javax/servlet/resources/web-app_2_3.dtd"; public static final String WebSchemaPublicId_24 = "web-app_2_4.xsd"; public static final String WebSchemaResourcePath_24 = "/javax/servlet/resources/web-app_2_4.xsd"; public static final String WebSchemaPublicId_25 = "web-app_2_5.xsd"; public static final String WebSchemaResourcePath_25 = "/javax/servlet/resources/web-app_2_5.xsd"; public static final String WebSchemaPublicId_30 = "web-app_3_0.xsd"; public static final String WebSchemaResourcePath_30 = "/javax/servlet/resources/web-app_3_0.xsd"; public static final String WebCommonSchemaPublicId_30 = "web-common_3_0.xsd"; public static final String WebCommonSchemaResourcePath_30 = "/javax/servlet/resources/web-common_3_0.xsd"; public static final String WebFragmentSchemaPublicId_30 = "web-fragment_3_0.xsd"; public static final String WebFragmentSchemaResourcePath_30 = "/javax/servlet/resources/web-fragment_3_0.xsd"; public static final String WebSchemaPublicId_31 = "web-app_3_1.xsd"; public static final String WebSchemaResourcePath_31 = "/javax/servlet/resources/web-app_3_1.xsd"; public static final String WebCommonSchemaPublicId_31 = "web-common_3_1.xsd"; public static final String WebCommonSchemaResourcePath_31 = "/javax/servlet/resources/web-common_3_1.xsd"; public static final String WebFragmentSchemaPublicId_31 = "web-fragment_3_1.xsd"; public static final String WebFragmentSchemaResourcePath_31 = "/javax/servlet/resources/web-fragment_3_1.xsd"; // Web service public static final String J2eeWebServiceSchemaPublicId_11 = "j2ee_web_services_1_1.xsd"; public static final String J2eeWebServiceSchemaResourcePath_11 = "/javax/servlet/resources/j2ee_web_services_1_1.xsd"; public static final String J2eeWebServiceClientSchemaPublicId_11 = "j2ee_web_services_client_1_1.xsd"; public static final String J2eeWebServiceClientSchemaResourcePath_11 = "/javax/servlet/resources/j2ee_web_services_client_1_1.xsd"; public static final String JavaeeWebServiceSchemaPublicId_12 = "javaee_web_services_1_2.xsd"; public static final String JavaeeWebServiceSchemaResourcePath_12 = "/javax/servlet/resources/javaee_web_services_1_2.xsd"; public static final String JavaeeWebServiceClientSchemaPublicId_12 = "javaee_web_services_client_1_2.xsd"; public static final String JavaeeWebServiceClientSchemaResourcePath_12 = "/javax/servlet/resources/javaee_web_services_client_1_2.xsd"; public static final String JavaeeWebServiceSchemaPublicId_13 = "javaee_web_services_1_3.xsd"; public static final String JavaeeWebServiceSchemaResourcePath_13 = "/javax/servlet/resources/javaee_web_services_1_3.xsd"; public static final String JavaeeWebServiceClientSchemaPublicId_13 = "javaee_web_services_client_1_3.xsd"; public static final String JavaeeWebServiceClientSchemaResourcePath_13 = "/javax/servlet/resources/javaee_web_services_client_1_3.xsd"; public static final String JavaeeWebServiceSchemaPublicId_14 = "javaee_web_services_1_4.xsd"; public static final String JavaeeWebServiceSchemaResourcePath_14 = "/javax/servlet/resources/javaee_web_services_1_4.xsd"; public static final String JavaeeWebServiceClientSchemaPublicId_14 = "javaee_web_services_client_1_4.xsd"; public static final String JavaeeWebServiceClientSchemaResourcePath_14 = "/javax/servlet/resources/javaee_web_services_client_1_4.xsd"; }
55,217
Bug 55217 Common EntityResolver that can be used by Catalina and Jasper
Duplicate functionality exists in both SchemaResolver and ParserUtils.MyEntityResolver. There's also a basic version in Digester.
closed fixed
5344de0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T08:51:17Z
2013-07-09T11:40:00Z
java/org/apache/tomcat/util/descriptor/LocalResolver.java
55,217
Bug 55217 Common EntityResolver that can be used by Catalina and Jasper
Duplicate functionality exists in both SchemaResolver and ParserUtils.MyEntityResolver. There's also a basic version in Digester.
closed fixed
5344de0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T08:51:17Z
2013-07-09T11:40:00Z
java/org/apache/tomcat/util/descriptor/XmlIdentifiers.java
55,217
Bug 55217 Common EntityResolver that can be used by Catalina and Jasper
Duplicate functionality exists in both SchemaResolver and ParserUtils.MyEntityResolver. There's also a basic version in Digester.
closed fixed
5344de0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T08:51:17Z
2013-07-09T11:40:00Z
test/org/apache/tomcat/util/descriptor/TestLocalResolver.java
55,218
Bug 55218 Upgrade Digester to be based on DefaultHandler2 and use LexicalHandler to detect publicId
Digester uses SAX2 features but is still based the SAX1 DefaultHandler. By upgrading to DefaultHandler2 it would be able to handle baseURIs when resolving entities and would have a default implementation of a LexicalHandler. Using LexicalHandler would allow it to respond directly to the startDTD event that reports the DOCTYPE (if present) so that it would not need to infer that from the first attempt to resolve an entity.
closed fixed
aa7896b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T10:07:23Z
2013-07-09T11:40:00Z
java/org/apache/catalina/core/StandardContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.management.ListenerNotFoundException; import javax.management.MBeanNotificationInfo; import javax.management.Notification; import javax.management.NotificationBroadcasterSupport; import javax.management.NotificationEmitter; import javax.management.NotificationFilter; import javax.management.NotificationListener; import javax.naming.NamingException; import javax.servlet.Filter; import javax.servlet.FilterConfig; import javax.servlet.FilterRegistration; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.ServletRegistration.Dynamic; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.ServletSecurityElement; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionIdListener; import javax.servlet.http.HttpSessionListener; import org.apache.catalina.Authenticator; import org.apache.catalina.Cluster; import org.apache.catalina.Container; import org.apache.catalina.ContainerListener; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.InstanceListener; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.catalina.Loader; import org.apache.catalina.Manager; import org.apache.catalina.Pipeline; import org.apache.catalina.Realm; import org.apache.catalina.Valve; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.catalina.deploy.NamingResourcesImpl; import org.apache.catalina.loader.WebappLoader; import org.apache.catalina.session.StandardManager; import org.apache.catalina.startup.TldConfig; import org.apache.catalina.util.CharsetMapper; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.ExtensionValidator; import org.apache.catalina.util.URLEncoder; import org.apache.catalina.webresources.StandardRoot; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.naming.ContextBindings; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.JarScanner; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.buf.UDecoder; import org.apache.tomcat.util.descriptor.web.ApplicationListener; import org.apache.tomcat.util.descriptor.web.ApplicationParameter; import org.apache.tomcat.util.descriptor.web.ErrorPage; import org.apache.tomcat.util.descriptor.web.FilterDef; import org.apache.tomcat.util.descriptor.web.FilterMap; import org.apache.tomcat.util.descriptor.web.Injectable; import org.apache.tomcat.util.descriptor.web.InjectionTarget; import org.apache.tomcat.util.descriptor.web.LoginConfig; import org.apache.tomcat.util.descriptor.web.MessageDestination; import org.apache.tomcat.util.descriptor.web.MessageDestinationRef; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.apache.tomcat.util.scan.StandardJarScanner; /** * Standard implementation of the <b>Context</b> interface. Each * child container must be a Wrapper implementation to process the * requests directed to a particular servlet. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class StandardContext extends ContainerBase implements Context, NotificationEmitter { private static final Log log = LogFactory.getLog(StandardContext.class); // ----------------------------------------------------------- Constructors /** * Create a new StandardContext component with the default basic Valve. */ public StandardContext() { super(); pipeline.setBasic(new StandardContextValve()); broadcaster = new NotificationBroadcasterSupport(); // Set defaults if (!Globals.STRICT_SERVLET_COMPLIANCE) { // Strict servlet compliance requires all extension mapped servlets // to be checked against welcome files resourceOnlyServlets.add("jsp"); } } // ----------------------------------------------------- Class Variables /** * Array containing the safe characters set. */ protected static URLEncoder urlEncoder; /** * GMT timezone - all HTTP dates are on GMT */ static { urlEncoder = new URLEncoder(); urlEncoder.addSafeCharacter('~'); urlEncoder.addSafeCharacter('-'); urlEncoder.addSafeCharacter('_'); urlEncoder.addSafeCharacter('.'); urlEncoder.addSafeCharacter('*'); urlEncoder.addSafeCharacter('/'); } // ----------------------------------------------------- Instance Variables /** * Allow multipart/form-data requests to be parsed even when the * target servlet doesn't specify @MultipartConfig or have a * &lt;multipart-config&gt; element. */ protected boolean allowCasualMultipartParsing = false; /** * Control whether remaining request data will be read * (swallowed) even if the request violates a data size constraint. */ private boolean swallowAbortedUploads = true; /** * The alternate deployment descriptor name. */ private String altDDName = null; /** * Lifecycle provider. */ private InstanceManager instanceManager = null; /** * The antiJARLocking flag for this Context. */ private boolean antiJARLocking = false; /** * The antiResourceLocking flag for this Context. */ private boolean antiResourceLocking = false; /** * The set of application listener class names configured for this * application, in the order they were encountered in the resulting merged * web.xml file. */ private ApplicationListener applicationListeners[] = new ApplicationListener[0]; private final Object applicationListenersLock = new Object(); /** * The set of instantiated application event listener objects. Note that * SCIs and other code may use the pluggability APIs to add listener * instances directly to this list before the application starts. */ private Object applicationEventListenersObjects[] = new Object[0]; /** * The set of instantiated application lifecycle listener objects. Note that * SCIs and other code may use the pluggability APIs to add listener * instances directly to this list before the application starts. */ private Object applicationLifecycleListenersObjects[] = new Object[0]; /** * The ordered set of ServletContainerInitializers for this web application. */ private Map<ServletContainerInitializer,Set<Class<?>>> initializers = new LinkedHashMap<>(); /** * The set of application parameters defined for this application. */ private ApplicationParameter applicationParameters[] = new ApplicationParameter[0]; private final Object applicationParametersLock = new Object(); /** * The broadcaster that sends j2ee notifications. */ private NotificationBroadcasterSupport broadcaster = null; /** * The Locale to character set mapper for this application. */ private CharsetMapper charsetMapper = null; /** * The Java class name of the CharsetMapper class to be created. */ private String charsetMapperClass = "org.apache.catalina.util.CharsetMapper"; /** * The URL of the XML descriptor for this context. */ private URL configFile = null; /** * The "correctly configured" flag for this Context. */ private boolean configured = false; /** * The security constraints for this web application. */ private volatile SecurityConstraint constraints[] = new SecurityConstraint[0]; private final Object constraintsLock = new Object(); /** * The ServletContext implementation associated with this Context. */ protected ApplicationContext context = null; /** * Should we attempt to use cookies for session id communication? */ private boolean cookies = true; /** * Should we allow the <code>ServletContext.getContext()</code> method * to access the context of other web applications in this server? */ private boolean crossContext = false; /** * Encoded path. */ private String encodedPath = null; /** * Unencoded path for this web application. */ private String path = null; /** * The "follow standard delegation model" flag that will be used to * configure our ClassLoader. */ private boolean delegate = false; private boolean denyUncoveredHttpMethods; /** * The display name of this web application. */ private String displayName = null; /** * Override the default context xml location. */ private String defaultContextXml; /** * Override the default web xml location. */ private String defaultWebXml; /** * The distributable flag for this web application. */ private boolean distributable = false; /** * The document root for this web application. */ private String docBase = null; /** * The exception pages for this web application, keyed by fully qualified * class name of the Java exception. */ private HashMap<String, ErrorPage> exceptionPages = new HashMap<>(); /** * The set of filter configurations (and associated filter instances) we * have initialized, keyed by filter name. */ private HashMap<String, ApplicationFilterConfig> filterConfigs = new HashMap<>(); /** * The set of filter definitions for this application, keyed by * filter name. */ private HashMap<String, FilterDef> filterDefs = new HashMap<>(); /** * The set of filter mappings for this application, in the order * they were defined in the deployment descriptor with additional mappings * added via the {@link ServletContext} possibly both before and after those * defined in the deployment descriptor. */ private final ContextFilterMaps filterMaps = new ContextFilterMaps(); /** * Ignore annotations. */ private boolean ignoreAnnotations = false; /** * The set of classnames of InstanceListeners that will be added * to each newly created Wrapper by <code>createWrapper()</code>. */ private String instanceListeners[] = new String[0]; private final Object instanceListenersLock = new Object(); /** * The Loader implementation with which this Container is associated. */ private Loader loader = null; private final ReadWriteLock loaderLock = new ReentrantReadWriteLock(); /** * The login configuration descriptor for this web application. */ private LoginConfig loginConfig = null; /** * The Manager implementation with which this Container is associated. */ protected Manager manager = null; private final ReadWriteLock managerLock = new ReentrantReadWriteLock(); /** * The naming context listener for this web application. */ private NamingContextListener namingContextListener = null; /** * The naming resources for this web application. */ private NamingResourcesImpl namingResources = null; /** * The message destinations for this web application. */ private HashMap<String, MessageDestination> messageDestinations = new HashMap<>(); /** * The MIME mappings for this web application, keyed by extension. */ private HashMap<String, String> mimeMappings = new HashMap<>(); /** * The context initialization parameters for this web application, * keyed by name. */ private HashMap<String, String> parameters = new HashMap<>(); /** * The request processing pause flag (while reloading occurs) */ private boolean paused = false; /** * The public identifier of the DTD for the web application deployment * descriptor version we are currently parsing. This is used to support * relaxed validation rules when processing version 2.2 web.xml files. */ private String publicId = null; /** * The reloadable flag for this web application. */ private boolean reloadable = false; /** * Unpack WAR property. */ private boolean unpackWAR = true; /** * Context level override for default {@link StandardHost#isCopyXML()}. */ private boolean copyXML = false; /** * The default context override flag for this web application. */ private boolean override = false; /** * The original document root for this web application. */ private String originalDocBase = null; /** * The privileged flag for this web application. */ private boolean privileged = false; /** * Should the next call to <code>addWelcomeFile()</code> cause replacement * of any existing welcome files? This will be set before processing the * web application's deployment descriptor, so that application specified * choices <strong>replace</strong>, rather than append to, those defined * in the global descriptor. */ private boolean replaceWelcomeFiles = false; /** * The security role mappings for this application, keyed by role * name (as used within the application). */ private HashMap<String, String> roleMappings = new HashMap<>(); /** * The security roles for this application, keyed by role name. */ private String securityRoles[] = new String[0]; private final Object securityRolesLock = new Object(); /** * The servlet mappings for this web application, keyed by * matching pattern. */ private HashMap<String, String> servletMappings = new HashMap<>(); private final Object servletMappingsLock = new Object(); /** * The session timeout (in minutes) for this web application. */ private int sessionTimeout = 30; /** * The notification sequence number. */ private AtomicLong sequenceNumber = new AtomicLong(0); /** * The status code error pages for this web application, keyed by * HTTP status code (as an Integer). Note status code zero is used for the * default error page. */ private HashMap<Integer, ErrorPage> statusPages = new HashMap<>(); /** * Set flag to true to cause the system.out and system.err to be redirected * to the logger when executing a servlet. */ private boolean swallowOutput = false; /** * Amount of ms that the container will wait for servlets to unload. */ private long unloadDelay = 2000; /** * The watched resources for this application. */ private String watchedResources[] = new String[0]; private final Object watchedResourcesLock = new Object(); /** * The welcome files for this application. */ private String welcomeFiles[] = new String[0]; private final Object welcomeFilesLock = new Object(); /** * The set of classnames of LifecycleListeners that will be added * to each newly created Wrapper by <code>createWrapper()</code>. */ private String wrapperLifecycles[] = new String[0]; private final Object wrapperLifecyclesLock = new Object(); /** * The set of classnames of ContainerListeners that will be added * to each newly created Wrapper by <code>createWrapper()</code>. */ private String wrapperListeners[] = new String[0]; private final Object wrapperListenersLock = new Object(); /** * The pathname to the work directory for this context (relative to * the server's home if not absolute). */ private String workDir = null; /** * Java class name of the Wrapper class implementation we use. */ private String wrapperClassName = StandardWrapper.class.getName(); private Class<?> wrapperClass = null; /** * JNDI use flag. */ private boolean useNaming = true; /** * Name of the associated naming context. */ private String namingContextName = null; /** * Caching allowed flag. */ private boolean cachingAllowed = true; /** * Allow linking. */ protected boolean allowLinking = false; /** * Cache max size in KB. */ protected int cacheMaxSize = 10240; // 10 MB /** * Cache object max size in KB. */ protected int cacheObjectMaxSize = 512; // 512K /** * Cache TTL in ms. */ protected int cacheTTL = 5000; private WebResourceRoot resources; private final ReadWriteLock resourcesLock = new ReentrantReadWriteLock(); private long startupTime; private long startTime; private long tldScanTime; /** * Name of the engine. If null, the domain is used. */ private String j2EEApplication="none"; private String j2EEServer="none"; /** * Attribute value used to turn on/off XML validation */ private boolean webXmlValidation = Globals.STRICT_SERVLET_COMPLIANCE; /** * Attribute value used to turn on/off XML namespace validation */ private boolean webXmlNamespaceAware = Globals.STRICT_SERVLET_COMPLIANCE; /** * Attribute value used to turn on/off TLD processing */ private boolean processTlds = true; /** * Attribute value used to turn on/off XML validation */ private boolean tldValidation = Globals.STRICT_SERVLET_COMPLIANCE; /** * Attribute value used to turn on/off TLD XML namespace validation */ private boolean tldNamespaceAware = Globals.STRICT_SERVLET_COMPLIANCE; /** * The name to use for session cookies. <code>null</code> indicates that * the name is controlled by the application. */ private String sessionCookieName; /** * The flag that indicates that session cookies should use HttpOnly */ private boolean useHttpOnly = true; /** * The domain to use for session cookies. <code>null</code> indicates that * the domain is controlled by the application. */ private String sessionCookieDomain; /** * The path to use for session cookies. <code>null</code> indicates that * the path is controlled by the application. */ private String sessionCookiePath; /** * Is a / added to the end of the session cookie path to ensure browsers, * particularly IE, don't send a session cookie for context /foo with * requests intended for context /foobar. */ private boolean sessionCookiePathUsesTrailingSlash = true; /** * The Jar scanner to use to search for Jars that might contain * configuration information such as TLDs or web-fragment.xml files. */ private JarScanner jarScanner = null; /** * Should Tomcat attempt to null out any static or final fields from loaded * classes when a web application is stopped as a work around for apparent * garbage collection bugs and application coding errors? There have been * some issues reported with log4j when this option is true. Applications * without memory leaks using recent JVMs should operate correctly with this * option set to <code>false</code>. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStatic = false; /** * Should Tomcat attempt to terminate threads that have been started by the * web application? Stopping threads is performed via the deprecated (for * good reason) <code>Thread.stop()</code> method and is likely to result in * instability. As such, enabling this should be viewed as an option of last * resort in a development environment and is not recommended in a * production environment. If not specified, the default value of * <code>false</code> will be used. */ private boolean clearReferencesStopThreads = false; /** * Should Tomcat attempt to terminate any {@link java.util.TimerThread}s * that have been started by the web application? If not specified, the * default value of <code>false</code> will be used. */ private boolean clearReferencesStopTimerThreads = false; /** * If an HttpClient keep-alive timer thread has been started by this web * application and is still running, should Tomcat change the context class * loader from the current {@link WebappClassLoader} to * {@link WebappClassLoader#parent} to prevent a memory leak? Note that the * keep-alive timer thread will stop on its own once the keep-alives all * expire however, on a busy system that might not happen for some time. */ private boolean clearReferencesHttpClientKeepAliveThread = true; /** * Should Tomcat renew the threads of the thread pool when the application * is stopped to avoid memory leaks because of uncleaned ThreadLocal * variables. This also requires that the threadRenewalDelay property of the * StandardThreadExecutor of ThreadPoolExecutor be set to a positive value. */ private boolean renewThreadsWhenStoppingContext = true; /** * Should the effective web.xml be logged when the context starts? */ private boolean logEffectiveWebXml = false; private int effectiveMajorVersion = 3; private int effectiveMinorVersion = 0; private JspConfigDescriptor jspConfigDescriptor = new ApplicationJspConfigDescriptor(); private Set<String> resourceOnlyServlets = new HashSet<>(); private String webappVersion = ""; private boolean addWebinfClassesResources = false; private boolean fireRequestListenersOnForwards = false; /** * Servlets created via {@link ApplicationContext#createServlet(Class)} for * tracking purposes. */ private Set<Servlet> createdServlets = new HashSet<>(); private boolean preemptiveAuthentication = false; private boolean sendRedirectBody = false; private boolean jndiExceptionOnFailedWrite = true; private Map<String, String> postConstructMethods = new HashMap<>(); private Map<String, String> preDestroyMethods = new HashMap<>(); // ----------------------------------------------------- Context Properties @Override public boolean getSendRedirectBody() { return sendRedirectBody; } @Override public void setSendRedirectBody(boolean sendRedirectBody) { this.sendRedirectBody = sendRedirectBody; } @Override public boolean getPreemptiveAuthentication() { return preemptiveAuthentication; } @Override public void setPreemptiveAuthentication(boolean preemptiveAuthentication) { this.preemptiveAuthentication = preemptiveAuthentication; } @Override public void setFireRequestListenersOnForwards(boolean enable) { fireRequestListenersOnForwards = enable; } @Override public boolean getFireRequestListenersOnForwards() { return fireRequestListenersOnForwards; } @Override public void setAddWebinfClassesResources( boolean addWebinfClassesResources) { this.addWebinfClassesResources = addWebinfClassesResources; } @Override public boolean getAddWebinfClassesResources() { return addWebinfClassesResources; } @Override public void setWebappVersion(String webappVersion) { if (null == webappVersion) { this.webappVersion = ""; } else { this.webappVersion = webappVersion; } } @Override public String getWebappVersion() { return webappVersion; } @Override public String getBaseName() { return new ContextName(path, webappVersion).getBaseName(); } @Override public String getResourceOnlyServlets() { StringBuilder result = new StringBuilder(); boolean first = true; for (String servletName : resourceOnlyServlets) { if (!first) { result.append(','); } result.append(servletName); } return result.toString(); } @Override public void setResourceOnlyServlets(String resourceOnlyServlets) { this.resourceOnlyServlets.clear(); if (resourceOnlyServlets == null) { return; } for (String servletName : resourceOnlyServlets.split(",")) { servletName = servletName.trim(); if (servletName.length()>0) { this.resourceOnlyServlets.add(servletName); } } } @Override public boolean isResourceOnlyServlet(String servletName) { return resourceOnlyServlets.contains(servletName); } @Override public int getEffectiveMajorVersion() { return effectiveMajorVersion; } @Override public void setEffectiveMajorVersion(int effectiveMajorVersion) { this.effectiveMajorVersion = effectiveMajorVersion; } @Override public int getEffectiveMinorVersion() { return effectiveMinorVersion; } @Override public void setEffectiveMinorVersion(int effectiveMinorVersion) { this.effectiveMinorVersion = effectiveMinorVersion; } @Override public void setLogEffectiveWebXml(boolean logEffectiveWebXml) { this.logEffectiveWebXml = logEffectiveWebXml; } @Override public boolean getLogEffectiveWebXml() { return logEffectiveWebXml; } @Override public Authenticator getAuthenticator() { if (this instanceof Authenticator) return (Authenticator) this; Pipeline pipeline = getPipeline(); if (pipeline != null) { Valve basic = pipeline.getBasic(); if ((basic != null) && (basic instanceof Authenticator)) return (Authenticator) basic; Valve valves[] = pipeline.getValves(); for (int i = 0; i < valves.length; i++) { if (valves[i] instanceof Authenticator) return (Authenticator) valves[i]; } } return null; } @Override public JarScanner getJarScanner() { if (jarScanner == null) { jarScanner = new StandardJarScanner(); } return jarScanner; } @Override public void setJarScanner(JarScanner jarScanner) { this.jarScanner = jarScanner; } @Override public InstanceManager getInstanceManager() { return instanceManager; } @Override public void setInstanceManager(InstanceManager instanceManager) { this.instanceManager = instanceManager; } @Override public String getEncodedPath() { return encodedPath; } /** * Is caching allowed ? */ public boolean isCachingAllowed() { return cachingAllowed; } /** * Set caching allowed flag. */ public void setCachingAllowed(boolean cachingAllowed) { this.cachingAllowed = cachingAllowed; } /** * Set allow linking. */ public void setAllowLinking(boolean allowLinking) { this.allowLinking = allowLinking; } /** * Is linking allowed. */ public boolean isAllowLinking() { return allowLinking; } /** * Set to <code>true</code> to allow requests mapped to servlets that * do not explicitly declare @MultipartConfig or have * &lt;multipart-config&gt; specified in web.xml to parse * multipart/form-data requests. * * @param allowCasualMultipartParsing <code>true</code> to allow such * casual parsing, <code>false</code> otherwise. */ @Override public void setAllowCasualMultipartParsing( boolean allowCasualMultipartParsing) { this.allowCasualMultipartParsing = allowCasualMultipartParsing; } /** * Returns <code>true</code> if requests mapped to servlets without * "multipart config" to parse multipart/form-data requests anyway. * * @return <code>true</code> if requests mapped to servlets without * "multipart config" to parse multipart/form-data requests, * <code>false</code> otherwise. */ @Override public boolean getAllowCasualMultipartParsing() { return this.allowCasualMultipartParsing; } /** * Set to <code>false</code> to disable request data swallowing * after an upload was aborted due to size constraints. * * @param swallowAbortedUploads <code>false</code> to disable * swallowing, <code>true</code> otherwise (default). */ @Override public void setSwallowAbortedUploads(boolean swallowAbortedUploads) { this.swallowAbortedUploads = swallowAbortedUploads; } /** * Returns <code>true</code> if remaining request data will be read * (swallowed) even the request violates a data size constraint. * * @return <code>true</code> if data will be swallowed (default), * <code>false</code> otherwise. */ @Override public boolean getSwallowAbortedUploads() { return this.swallowAbortedUploads; } /** * Set cache TTL. */ public void setCacheTTL(int cacheTTL) { this.cacheTTL = cacheTTL; } /** * Get cache TTL. */ public int getCacheTTL() { return cacheTTL; } /** * Return the maximum size of the cache in KB. */ public int getCacheMaxSize() { return cacheMaxSize; } /** * Set the maximum size of the cache in KB. */ public void setCacheMaxSize(int cacheMaxSize) { this.cacheMaxSize = cacheMaxSize; } /** * Return the maximum size of objects to be cached in KB. */ public int getCacheObjectMaxSize() { return cacheObjectMaxSize; } /** * Set the maximum size of objects to be placed the cache in KB. */ public void setCacheObjectMaxSize(int cacheObjectMaxSize) { this.cacheObjectMaxSize = cacheObjectMaxSize; } /** * Add a ServletContainerInitializer instance to this web application. * * @param sci The instance to add * @param classes The classes in which the initializer expressed an * interest */ @Override public void addServletContainerInitializer( ServletContainerInitializer sci, Set<Class<?>> classes) { initializers.put(sci, classes); } /** * Return the "follow standard delegation model" flag used to configure * our ClassLoader. */ public boolean getDelegate() { return (this.delegate); } /** * Set the "follow standard delegation model" flag used to configure * our ClassLoader. * * @param delegate The new flag */ public void setDelegate(boolean delegate) { boolean oldDelegate = this.delegate; this.delegate = delegate; support.firePropertyChange("delegate", oldDelegate, this.delegate); } /** * Returns true if the internal naming support is used. */ public boolean isUseNaming() { return (useNaming); } /** * Enables or disables naming. */ public void setUseNaming(boolean useNaming) { this.useNaming = useNaming; } /** * Return the set of initialized application event listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @exception IllegalStateException if this method is called before * this application has started, or after it has been stopped */ @Override public Object[] getApplicationEventListeners() { return (applicationEventListenersObjects); } /** * Store the set of initialized application event listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @param listeners The set of instantiated listener objects. */ @Override public void setApplicationEventListeners(Object listeners[]) { applicationEventListenersObjects = listeners; } /** * Add a listener to the end of the list of initialized application event * listeners. */ public void addApplicationEventListener(Object listener) { int len = applicationEventListenersObjects.length; Object[] newListeners = Arrays.copyOf(applicationEventListenersObjects, len + 1); newListeners[len] = listener; applicationEventListenersObjects = newListeners; } /** * Return the set of initialized application lifecycle listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @exception IllegalStateException if this method is called before * this application has started, or after it has been stopped */ @Override public Object[] getApplicationLifecycleListeners() { return (applicationLifecycleListenersObjects); } /** * Store the set of initialized application lifecycle listener objects, * in the order they were specified in the web application deployment * descriptor, for this application. * * @param listeners The set of instantiated listener objects. */ @Override public void setApplicationLifecycleListeners(Object listeners[]) { applicationLifecycleListenersObjects = listeners; } /** * Add a listener to the end of the list of initialized application * lifecycle listeners. */ public void addApplicationLifecycleListener(Object listener) { int len = applicationLifecycleListenersObjects.length; Object[] newListeners = Arrays.copyOf( applicationLifecycleListenersObjects, len + 1); newListeners[len] = listener; applicationLifecycleListenersObjects = newListeners; } /** * Return the antiJARLocking flag for this Context. */ public boolean getAntiJARLocking() { return (this.antiJARLocking); } /** * Return the antiResourceLocking flag for this Context. */ public boolean getAntiResourceLocking() { return (this.antiResourceLocking); } /** * Set the antiJARLocking feature for this Context. * * @param antiJARLocking The new flag value */ public void setAntiJARLocking(boolean antiJARLocking) { boolean oldAntiJARLocking = this.antiJARLocking; this.antiJARLocking = antiJARLocking; support.firePropertyChange("antiJARLocking", oldAntiJARLocking, this.antiJARLocking); } /** * Set the antiResourceLocking feature for this Context. * * @param antiResourceLocking The new flag value */ public void setAntiResourceLocking(boolean antiResourceLocking) { boolean oldAntiResourceLocking = this.antiResourceLocking; this.antiResourceLocking = antiResourceLocking; support.firePropertyChange("antiResourceLocking", oldAntiResourceLocking, this.antiResourceLocking); } /** * Return the Locale to character set mapper for this Context. */ public CharsetMapper getCharsetMapper() { // Create a mapper the first time it is requested if (this.charsetMapper == null) { try { Class<?> clazz = Class.forName(charsetMapperClass); this.charsetMapper = (CharsetMapper) clazz.newInstance(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); this.charsetMapper = new CharsetMapper(); } } return (this.charsetMapper); } /** * Set the Locale to character set mapper for this Context. * * @param mapper The new mapper */ public void setCharsetMapper(CharsetMapper mapper) { CharsetMapper oldCharsetMapper = this.charsetMapper; this.charsetMapper = mapper; if( mapper != null ) this.charsetMapperClass= mapper.getClass().getName(); support.firePropertyChange("charsetMapper", oldCharsetMapper, this.charsetMapper); } @Override public String getCharset(Locale locale) { return getCharsetMapper().getCharset(locale); } /** * Return the URL of the XML descriptor for this context. */ @Override public URL getConfigFile() { return (this.configFile); } /** * Set the URL of the XML descriptor for this context. * * @param configFile The URL of the XML descriptor for this context. */ @Override public void setConfigFile(URL configFile) { this.configFile = configFile; } /** * Return the "correctly configured" flag for this Context. */ @Override public boolean getConfigured() { return (this.configured); } /** * Set the "correctly configured" flag for this Context. This can be * set to false by startup listeners that detect a fatal configuration * error to avoid the application from being made available. * * @param configured The new correctly configured flag */ @Override public void setConfigured(boolean configured) { boolean oldConfigured = this.configured; this.configured = configured; support.firePropertyChange("configured", oldConfigured, this.configured); } /** * Return the "use cookies for session ids" flag. */ @Override public boolean getCookies() { return (this.cookies); } /** * Set the "use cookies for session ids" flag. * * @param cookies The new flag */ @Override public void setCookies(boolean cookies) { boolean oldCookies = this.cookies; this.cookies = cookies; support.firePropertyChange("cookies", oldCookies, this.cookies); } /** * Gets the name to use for session cookies. Overrides any setting that * may be specified by the application. * * @return The value of the default session cookie name or null if not * specified */ @Override public String getSessionCookieName() { return sessionCookieName; } /** * Sets the name to use for session cookies. Overrides any setting that * may be specified by the application. * * @param sessionCookieName The name to use */ @Override public void setSessionCookieName(String sessionCookieName) { String oldSessionCookieName = this.sessionCookieName; this.sessionCookieName = sessionCookieName; support.firePropertyChange("sessionCookieName", oldSessionCookieName, sessionCookieName); } /** * Gets the value of the use HttpOnly cookies for session cookies flag. * * @return <code>true</code> if the HttpOnly flag should be set on session * cookies */ @Override public boolean getUseHttpOnly() { return useHttpOnly; } /** * Sets the use HttpOnly cookies for session cookies flag. * * @param useHttpOnly Set to <code>true</code> to use HttpOnly cookies * for session cookies */ @Override public void setUseHttpOnly(boolean useHttpOnly) { boolean oldUseHttpOnly = this.useHttpOnly; this.useHttpOnly = useHttpOnly; support.firePropertyChange("useHttpOnly", oldUseHttpOnly, this.useHttpOnly); } /** * Gets the domain to use for session cookies. Overrides any setting that * may be specified by the application. * * @return The value of the default session cookie domain or null if not * specified */ @Override public String getSessionCookieDomain() { return sessionCookieDomain; } /** * Sets the domain to use for session cookies. Overrides any setting that * may be specified by the application. * * @param sessionCookieDomain The domain to use */ @Override public void setSessionCookieDomain(String sessionCookieDomain) { String oldSessionCookieDomain = this.sessionCookieDomain; this.sessionCookieDomain = sessionCookieDomain; support.firePropertyChange("sessionCookieDomain", oldSessionCookieDomain, sessionCookieDomain); } /** * Gets the path to use for session cookies. Overrides any setting that * may be specified by the application. * * @return The value of the default session cookie path or null if not * specified */ @Override public String getSessionCookiePath() { return sessionCookiePath; } /** * Sets the path to use for session cookies. Overrides any setting that * may be specified by the application. * * @param sessionCookiePath The path to use */ @Override public void setSessionCookiePath(String sessionCookiePath) { String oldSessionCookiePath = this.sessionCookiePath; this.sessionCookiePath = sessionCookiePath; support.firePropertyChange("sessionCookiePath", oldSessionCookiePath, sessionCookiePath); } @Override public boolean getSessionCookiePathUsesTrailingSlash() { return sessionCookiePathUsesTrailingSlash; } @Override public void setSessionCookiePathUsesTrailingSlash( boolean sessionCookiePathUsesTrailingSlash) { this.sessionCookiePathUsesTrailingSlash = sessionCookiePathUsesTrailingSlash; } /** * Return the "allow crossing servlet contexts" flag. */ @Override public boolean getCrossContext() { return (this.crossContext); } /** * Set the "allow crossing servlet contexts" flag. * * @param crossContext The new cross contexts flag */ @Override public void setCrossContext(boolean crossContext) { boolean oldCrossContext = this.crossContext; this.crossContext = crossContext; support.firePropertyChange("crossContext", oldCrossContext, this.crossContext); } public String getDefaultContextXml() { return defaultContextXml; } /** * Set the location of the default context xml that will be used. * If not absolute, it'll be made relative to the engine's base dir * ( which defaults to catalina.base system property ). * * @param defaultContextXml The default web xml */ public void setDefaultContextXml(String defaultContextXml) { this.defaultContextXml = defaultContextXml; } public String getDefaultWebXml() { return defaultWebXml; } /** * Set the location of the default web xml that will be used. * If not absolute, it'll be made relative to the engine's base dir * ( which defaults to catalina.base system property ). * * @param defaultWebXml The default web xml */ public void setDefaultWebXml(String defaultWebXml) { this.defaultWebXml = defaultWebXml; } /** * Gets the time (in milliseconds) it took to start this context. * * @return Time (in milliseconds) it took to start this context. */ public long getStartupTime() { return startupTime; } public void setStartupTime(long startupTime) { this.startupTime = startupTime; } public long getTldScanTime() { return tldScanTime; } public void setTldScanTime(long tldScanTime) { this.tldScanTime = tldScanTime; } @Override public boolean getDenyUncoveredHttpMethods() { return denyUncoveredHttpMethods; } @Override public void setDenyUncoveredHttpMethods(boolean denyUncoveredHttpMethods) { this.denyUncoveredHttpMethods = denyUncoveredHttpMethods; } /** * Return the display name of this web application. */ @Override public String getDisplayName() { return (this.displayName); } /** * Return the alternate Deployment Descriptor name. */ @Override public String getAltDDName(){ return altDDName; } /** * Set an alternate Deployment Descriptor name. */ @Override public void setAltDDName(String altDDName) { this.altDDName = altDDName; if (context != null) { context.setAttribute(Globals.ALT_DD_ATTR,altDDName); } } /** * Set the display name of this web application. * * @param displayName The new display name */ @Override public void setDisplayName(String displayName) { String oldDisplayName = this.displayName; this.displayName = displayName; support.firePropertyChange("displayName", oldDisplayName, this.displayName); } /** * Return the distributable flag for this web application. */ @Override public boolean getDistributable() { return (this.distributable); } /** * Set the distributable flag for this web application. * * @param distributable The new distributable flag */ @Override public void setDistributable(boolean distributable) { boolean oldDistributable = this.distributable; this.distributable = distributable; support.firePropertyChange("distributable", oldDistributable, this.distributable); // Bugzilla 32866 if(getManager() != null) { if(log.isDebugEnabled()) { log.debug("Propagating distributable=" + distributable + " to manager"); } getManager().setDistributable(distributable); } } /** * Return the document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. */ @Override public String getDocBase() { return (this.docBase); } /** * Set the document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. * * @param docBase The new document root */ @Override public void setDocBase(String docBase) { this.docBase = docBase; } public String getJ2EEApplication() { return j2EEApplication; } public void setJ2EEApplication(String j2EEApplication) { this.j2EEApplication = j2EEApplication; } public String getJ2EEServer() { return j2EEServer; } public void setJ2EEServer(String j2EEServer) { this.j2EEServer = j2EEServer; } @Override public Loader getLoader() { Lock readLock = loaderLock.readLock(); readLock.lock(); try { return loader; } finally { readLock.unlock(); } } @Override public void setLoader(Loader loader) { Lock writeLock = loaderLock.writeLock(); writeLock.lock(); Loader oldLoader = null; try { // Change components if necessary oldLoader = this.loader; if (oldLoader == loader) return; this.loader = loader; // Stop the old component if necessary if (getState().isAvailable() && (oldLoader != null) && (oldLoader instanceof Lifecycle)) { try { ((Lifecycle) oldLoader).stop(); } catch (LifecycleException e) { log.error("StandardContext.setLoader: stop: ", e); } } // Start the new component if necessary if (loader != null) loader.setContext(this); if (getState().isAvailable() && (loader != null) && (loader instanceof Lifecycle)) { try { ((Lifecycle) loader).start(); } catch (LifecycleException e) { log.error("StandardContext.setLoader: start: ", e); } } } finally { writeLock.unlock(); } // Report this property change to interested listeners support.firePropertyChange("loader", oldLoader, loader); } @Override public Manager getManager() { Lock readLock = managerLock.readLock(); readLock.lock(); try { return manager; } finally { readLock.unlock(); } } @Override public void setManager(Manager manager) { Lock writeLock = managerLock.writeLock(); writeLock.lock(); Manager oldManager = null; try { // Change components if necessary oldManager = this.manager; if (oldManager == manager) return; this.manager = manager; // Stop the old component if necessary if (getState().isAvailable() && (oldManager != null) && (oldManager instanceof Lifecycle)) { try { ((Lifecycle) oldManager).stop(); } catch (LifecycleException e) { log.error("StandardContext.setManager: stop: ", e); } } // Start the new component if necessary if (manager != null) manager.setContext(this); if (getState().isAvailable() && (manager != null) && (manager instanceof Lifecycle)) { try { ((Lifecycle) manager).start(); } catch (LifecycleException e) { log.error("StandardContext.setManager: start: ", e); } } } finally { writeLock.unlock(); } // Report this property change to interested listeners support.firePropertyChange("manager", oldManager, manager); } /** * Return the boolean on the annotations parsing. */ @Override public boolean getIgnoreAnnotations() { return this.ignoreAnnotations; } /** * Set the boolean on the annotations parsing for this web * application. * * @param ignoreAnnotations The boolean on the annotations parsing */ @Override public void setIgnoreAnnotations(boolean ignoreAnnotations) { boolean oldIgnoreAnnotations = this.ignoreAnnotations; this.ignoreAnnotations = ignoreAnnotations; support.firePropertyChange("ignoreAnnotations", oldIgnoreAnnotations, this.ignoreAnnotations); } /** * Return the login configuration descriptor for this web application. */ @Override public LoginConfig getLoginConfig() { return (this.loginConfig); } /** * Set the login configuration descriptor for this web application. * * @param config The new login configuration */ @Override public void setLoginConfig(LoginConfig config) { // Validate the incoming property value if (config == null) throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.required")); String loginPage = config.getLoginPage(); if ((loginPage != null) && !loginPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.loginWarning", loginPage)); config.setLoginPage("/" + loginPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.loginPage", loginPage)); } } String errorPage = config.getErrorPage(); if ((errorPage != null) && !errorPage.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.loginConfig.errorWarning", errorPage)); config.setErrorPage("/" + errorPage); } else { throw new IllegalArgumentException (sm.getString("standardContext.loginConfig.errorPage", errorPage)); } } // Process the property setting change LoginConfig oldLoginConfig = this.loginConfig; this.loginConfig = config; support.firePropertyChange("loginConfig", oldLoginConfig, this.loginConfig); } /** * Return the naming resources associated with this web application. */ @Override public NamingResourcesImpl getNamingResources() { if (namingResources == null) { setNamingResources(new NamingResourcesImpl()); } return (namingResources); } /** * Set the naming resources for this web application. * * @param namingResources The new naming resources */ @Override public void setNamingResources(NamingResourcesImpl namingResources) { // Process the property setting change NamingResourcesImpl oldNamingResources = this.namingResources; this.namingResources = namingResources; if (namingResources != null) { namingResources.setContainer(this); } support.firePropertyChange("namingResources", oldNamingResources, this.namingResources); if (getState() == LifecycleState.NEW || getState() == LifecycleState.INITIALIZING || getState() == LifecycleState.INITIALIZED) { // NEW will occur if Context is defined in server.xml // At this point getObjectKeyPropertiesNameOnly() will trigger an // NPE. // INITIALIZED will occur if the Context is defined in a context.xml // file // If started now, a second start will be attempted when the context // starts // In both cases, return and let context init the namingResources // when it starts return; } if (oldNamingResources != null) { try { oldNamingResources.stop(); oldNamingResources.destroy(); } catch (LifecycleException e) { log.warn("standardContext.namingResource.destroy.fail", e); } } if (namingResources != null) { try { namingResources.init(); namingResources.start(); } catch (LifecycleException e) { log.warn("standardContext.namingResource.init.fail", e); } } } /** * Return the context path for this Context. */ @Override public String getPath() { return (path); } /** * Set the context path for this Context. * * @param path The new context path */ @Override public void setPath(String path) { if (path == null || (!path.equals("") && !path.startsWith("/"))) { this.path = "/" + path; log.warn(sm.getString( "standardContext.pathInvalid", path, this.path)); } else { this.path = path; } encodedPath = urlEncoder.encode(this.path); if (getName() == null) { setName(this.path); } } /** * Return the public identifier of the deployment descriptor DTD that is * currently being parsed. */ @Override public String getPublicId() { return (this.publicId); } /** * Set the public identifier of the deployment descriptor DTD that is * currently being parsed. * * @param publicId The public identifier */ @Override public void setPublicId(String publicId) { if (log.isDebugEnabled()) log.debug("Setting deployment descriptor public ID to '" + publicId + "'"); String oldPublicId = this.publicId; this.publicId = publicId; support.firePropertyChange("publicId", oldPublicId, publicId); } /** * Return the reloadable flag for this web application. */ @Override public boolean getReloadable() { return (this.reloadable); } /** * Return the default context override flag for this web application. */ @Override public boolean getOverride() { return (this.override); } /** * Return the original document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. * Is only set as deployment has change docRoot! */ public String getOriginalDocBase() { return (this.originalDocBase); } /** * Set the original document root for this Context. This can be an absolute * pathname, a relative pathname, or a URL. * * @param docBase The original document root */ public void setOriginalDocBase(String docBase) { this.originalDocBase = docBase; } /** * Return the parent class loader (if any) for this web application. * This call is meaningful only <strong>after</strong> a Loader has * been configured. */ @Override public ClassLoader getParentClassLoader() { if (parentClassLoader != null) return (parentClassLoader); if (getPrivileged()) { return this.getClass().getClassLoader(); } else if (parent != null) { return (parent.getParentClassLoader()); } return (ClassLoader.getSystemClassLoader()); } /** * Return the privileged flag for this web application. */ @Override public boolean getPrivileged() { return (this.privileged); } /** * Set the privileged flag for this web application. * * @param privileged The new privileged flag */ @Override public void setPrivileged(boolean privileged) { boolean oldPrivileged = this.privileged; this.privileged = privileged; support.firePropertyChange("privileged", oldPrivileged, this.privileged); } /** * Set the reloadable flag for this web application. * * @param reloadable The new reloadable flag */ @Override public void setReloadable(boolean reloadable) { boolean oldReloadable = this.reloadable; this.reloadable = reloadable; support.firePropertyChange("reloadable", oldReloadable, this.reloadable); } /** * Set the default context override flag for this web application. * * @param override The new override flag */ @Override public void setOverride(boolean override) { boolean oldOverride = this.override; this.override = override; support.firePropertyChange("override", oldOverride, this.override); } /** * Set the "replace welcome files" property. * * @param replaceWelcomeFiles The new property value */ public void setReplaceWelcomeFiles(boolean replaceWelcomeFiles) { boolean oldReplaceWelcomeFiles = this.replaceWelcomeFiles; this.replaceWelcomeFiles = replaceWelcomeFiles; support.firePropertyChange("replaceWelcomeFiles", oldReplaceWelcomeFiles, this.replaceWelcomeFiles); } /** * Return the servlet context for which this Context is a facade. */ @Override public ServletContext getServletContext() { if (context == null) { context = new ApplicationContext(this); if (altDDName != null) context.setAttribute(Globals.ALT_DD_ATTR,altDDName); } return (context.getFacade()); } /** * Return the default session timeout (in minutes) for this * web application. */ @Override public int getSessionTimeout() { return (this.sessionTimeout); } /** * Set the default session timeout (in minutes) for this * web application. * * @param timeout The new default session timeout */ @Override public void setSessionTimeout(int timeout) { int oldSessionTimeout = this.sessionTimeout; /* * SRV.13.4 ("Deployment Descriptor"): * If the timeout is 0 or less, the container ensures the default * behaviour of sessions is never to time out. */ this.sessionTimeout = (timeout == 0) ? -1 : timeout; support.firePropertyChange("sessionTimeout", oldSessionTimeout, this.sessionTimeout); } /** * Return the value of the swallowOutput flag. */ @Override public boolean getSwallowOutput() { return (this.swallowOutput); } /** * Set the value of the swallowOutput flag. If set to true, the system.out * and system.err will be redirected to the logger during a servlet * execution. * * @param swallowOutput The new value */ @Override public void setSwallowOutput(boolean swallowOutput) { boolean oldSwallowOutput = this.swallowOutput; this.swallowOutput = swallowOutput; support.firePropertyChange("swallowOutput", oldSwallowOutput, this.swallowOutput); } /** * Return the value of the unloadDelay flag. */ public long getUnloadDelay() { return (this.unloadDelay); } /** * Set the value of the unloadDelay flag, which represents the amount * of ms that the container will wait when unloading servlets. * Setting this to a small value may cause more requests to fail * to complete when stopping a web application. * * @param unloadDelay The new value */ public void setUnloadDelay(long unloadDelay) { long oldUnloadDelay = this.unloadDelay; this.unloadDelay = unloadDelay; support.firePropertyChange("unloadDelay", Long.valueOf(oldUnloadDelay), Long.valueOf(this.unloadDelay)); } /** * Unpack WAR flag accessor. */ public boolean getUnpackWAR() { return (unpackWAR); } /** * Unpack WAR flag mutator. */ public void setUnpackWAR(boolean unpackWAR) { this.unpackWAR = unpackWAR; } public boolean getCopyXML() { return copyXML; } public void setCopyXML(boolean copyXML) { this.copyXML = copyXML; } /** * Return the Java class name of the Wrapper implementation used * for servlets registered in this Context. */ @Override public String getWrapperClass() { return (this.wrapperClassName); } /** * Set the Java class name of the Wrapper implementation used * for servlets registered in this Context. * * @param wrapperClassName The new wrapper class name * * @throws IllegalArgumentException if the specified wrapper class * cannot be found or is not a subclass of StandardWrapper */ @Override public void setWrapperClass(String wrapperClassName) { this.wrapperClassName = wrapperClassName; try { wrapperClass = Class.forName(wrapperClassName); if (!StandardWrapper.class.isAssignableFrom(wrapperClass)) { throw new IllegalArgumentException( sm.getString("standardContext.invalidWrapperClass", wrapperClassName)); } } catch (ClassNotFoundException cnfe) { throw new IllegalArgumentException(cnfe.getMessage()); } } @Override public WebResourceRoot getResources() { Lock readLock = resourcesLock.readLock(); readLock.lock(); try { return resources; } finally { readLock.unlock(); } } @Override public void setResources(WebResourceRoot resources) { Lock writeLock = resourcesLock.writeLock(); writeLock.lock(); WebResourceRoot oldResources = null; try { if (getState().isAvailable()) { throw new IllegalStateException (sm.getString("standardContext.resources.started")); } oldResources = this.resources; if (oldResources == resources) return; this.resources = resources; if (oldResources != null) { oldResources.setContext(null); } if (resources != null) { resources.setContext(this); } support.firePropertyChange("resources", oldResources, resources); } finally { writeLock.unlock(); } } @Override public JspConfigDescriptor getJspConfigDescriptor() { return jspConfigDescriptor; } // ------------------------------------------------------ Public Properties /** * Returns whether or not an attempt to modify the JNDI context will trigger * an exception or if the request will be ignored. */ public boolean getJndiExceptionOnFailedWrite() { return jndiExceptionOnFailedWrite; } /** * Controls whether or not an attempt to modify the JNDI context will * trigger an exception or if the request will be ignored. * * @param jndiExceptionOnFailedWrite */ public void setJndiExceptionOnFailedWrite( boolean jndiExceptionOnFailedWrite) { this.jndiExceptionOnFailedWrite = jndiExceptionOnFailedWrite; } /** * Return the Locale to character set mapper class for this Context. */ public String getCharsetMapperClass() { return (this.charsetMapperClass); } /** * Set the Locale to character set mapper class for this Context. * * @param mapper The new mapper class */ public void setCharsetMapperClass(String mapper) { String oldCharsetMapperClass = this.charsetMapperClass; this.charsetMapperClass = mapper; support.firePropertyChange("charsetMapperClass", oldCharsetMapperClass, this.charsetMapperClass); } /** Get the absolute path to the work dir. * To avoid duplication. * * @return The work path */ public String getWorkPath() { if (getWorkDir() == null) { return null; } File workDir = new File(getWorkDir()); if (!workDir.isAbsolute()) { try { workDir = new File(getCatalinaBase().getCanonicalFile(), getWorkDir()); } catch (IOException e) { log.warn(sm.getString("standardContext.workPath", getName()), e); } } return workDir.getAbsolutePath(); } /** * Return the work directory for this Context. */ public String getWorkDir() { return (this.workDir); } /** * Set the work directory for this Context. * * @param workDir The new work directory */ public void setWorkDir(String workDir) { this.workDir = workDir; if (getState().isAvailable()) { postWorkDirectory(); } } /** * Return the clearReferencesStatic flag for this Context. */ public boolean getClearReferencesStatic() { return (this.clearReferencesStatic); } /** * Set the clearReferencesStatic feature for this Context. * * @param clearReferencesStatic The new flag value */ public void setClearReferencesStatic(boolean clearReferencesStatic) { boolean oldClearReferencesStatic = this.clearReferencesStatic; this.clearReferencesStatic = clearReferencesStatic; support.firePropertyChange("clearReferencesStatic", oldClearReferencesStatic, this.clearReferencesStatic); } /** * Return the clearReferencesStopThreads flag for this Context. */ public boolean getClearReferencesStopThreads() { return (this.clearReferencesStopThreads); } /** * Set the clearReferencesStopThreads feature for this Context. * * @param clearReferencesStopThreads The new flag value */ public void setClearReferencesStopThreads( boolean clearReferencesStopThreads) { boolean oldClearReferencesStopThreads = this.clearReferencesStopThreads; this.clearReferencesStopThreads = clearReferencesStopThreads; support.firePropertyChange("clearReferencesStopThreads", oldClearReferencesStopThreads, this.clearReferencesStopThreads); } /** * Return the clearReferencesStopTimerThreads flag for this Context. */ public boolean getClearReferencesStopTimerThreads() { return (this.clearReferencesStopTimerThreads); } /** * Set the clearReferencesStopTimerThreads feature for this Context. * * @param clearReferencesStopTimerThreads The new flag value */ public void setClearReferencesStopTimerThreads( boolean clearReferencesStopTimerThreads) { boolean oldClearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads; this.clearReferencesStopTimerThreads = clearReferencesStopTimerThreads; support.firePropertyChange("clearReferencesStopTimerThreads", oldClearReferencesStopTimerThreads, this.clearReferencesStopTimerThreads); } /** * Return the clearReferencesHttpClientKeepAliveThread flag for this * Context. */ public boolean getClearReferencesHttpClientKeepAliveThread() { return (this.clearReferencesHttpClientKeepAliveThread); } /** * Set the clearReferencesHttpClientKeepAliveThread feature for this * Context. * * @param clearReferencesHttpClientKeepAliveThread The new flag value */ public void setClearReferencesHttpClientKeepAliveThread( boolean clearReferencesHttpClientKeepAliveThread) { this.clearReferencesHttpClientKeepAliveThread = clearReferencesHttpClientKeepAliveThread; } public boolean getRenewThreadsWhenStoppingContext() { return this.renewThreadsWhenStoppingContext; } public void setRenewThreadsWhenStoppingContext( boolean renewThreadsWhenStoppingContext) { boolean oldRenewThreadsWhenStoppingContext = this.renewThreadsWhenStoppingContext; this.renewThreadsWhenStoppingContext = renewThreadsWhenStoppingContext; support.firePropertyChange("renewThreadsWhenStoppingContext", oldRenewThreadsWhenStoppingContext, this.renewThreadsWhenStoppingContext); } // -------------------------------------------------------- Context Methods /** * Add a new Listener class name to the set of Listeners * configured for this application. * * @param listener Java class name of a listener class */ @Override public void addApplicationListener(ApplicationListener listener) { synchronized (applicationListenersLock) { ApplicationListener results[] = new ApplicationListener[applicationListeners.length + 1]; for (int i = 0; i < applicationListeners.length; i++) { if (listener.equals(applicationListeners[i])) { log.info(sm.getString( "standardContext.duplicateListener",listener)); return; } results[i] = applicationListeners[i]; } results[applicationListeners.length] = listener; applicationListeners = results; } fireContainerEvent("addApplicationListener", listener); // FIXME - add instance if already started? } /** * Add a new application parameter for this application. * * @param parameter The new application parameter */ @Override public void addApplicationParameter(ApplicationParameter parameter) { synchronized (applicationParametersLock) { String newName = parameter.getName(); for (ApplicationParameter p : applicationParameters) { if (newName.equals(p.getName()) && !p.getOverride()) return; } ApplicationParameter results[] = Arrays.copyOf( applicationParameters, applicationParameters.length + 1); results[applicationParameters.length] = parameter; applicationParameters = results; } fireContainerEvent("addApplicationParameter", parameter); } /** * Add a child Container, only if the proposed child is an implementation * of Wrapper. * * @param child Child container to be added * * @exception IllegalArgumentException if the proposed container is * not an implementation of Wrapper */ @Override public void addChild(Container child) { // Global JspServlet Wrapper oldJspServlet = null; if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } boolean isJspServlet = "jsp".equals(child.getName()); // Allow webapp to override JspServlet inherited from global web.xml. if (isJspServlet) { oldJspServlet = (Wrapper) findChild("jsp"); if (oldJspServlet != null) { removeChild(oldJspServlet); } } super.addChild(child); if (isJspServlet && oldJspServlet != null) { /* * The webapp-specific JspServlet inherits all the mappings * specified in the global web.xml, and may add additional ones. */ String[] jspMappings = oldJspServlet.findMappings(); for (int i=0; jspMappings!=null && i<jspMappings.length; i++) { addServletMapping(jspMappings[i], child.getName()); } } } /** * Add a security constraint to the set for this web application. */ @Override public void addConstraint(SecurityConstraint constraint) { // Validate the proposed constraint SecurityCollection collections[] = constraint.findCollections(); for (int i = 0; i < collections.length; i++) { String patterns[] = collections[i].findPatterns(); for (int j = 0; j < patterns.length; j++) { patterns[j] = adjustURLPattern(patterns[j]); if (!validateURLPattern(patterns[j])) throw new IllegalArgumentException (sm.getString ("standardContext.securityConstraint.pattern", patterns[j])); } if (collections[i].findMethods().length > 0 && collections[i].findOmittedMethods().length > 0) { throw new IllegalArgumentException(sm.getString( "standardContext.securityConstraint.mixHttpMethod")); } } // Add this constraint to the set for our web application synchronized (constraintsLock) { SecurityConstraint results[] = new SecurityConstraint[constraints.length + 1]; for (int i = 0; i < constraints.length; i++) results[i] = constraints[i]; results[constraints.length] = constraint; constraints = results; } } /** * Add an error page for the specified error or Java exception. * * @param errorPage The error page definition to be added */ @Override public void addErrorPage(ErrorPage errorPage) { // Validate the input parameters if (errorPage == null) throw new IllegalArgumentException (sm.getString("standardContext.errorPage.required")); String location = errorPage.getLocation(); if ((location != null) && !location.startsWith("/")) { if (isServlet22()) { if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.errorPage.warning", location)); errorPage.setLocation("/" + location); } else { throw new IllegalArgumentException (sm.getString("standardContext.errorPage.error", location)); } } // Add the specified error page to our internal collections String exceptionType = errorPage.getExceptionType(); if (exceptionType != null) { synchronized (exceptionPages) { exceptionPages.put(exceptionType, errorPage); } } else { synchronized (statusPages) { statusPages.put(Integer.valueOf(errorPage.getErrorCode()), errorPage); } } fireContainerEvent("addErrorPage", errorPage); } /** * Add a filter definition to this Context. * * @param filterDef The filter definition to be added */ @Override public void addFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.put(filterDef.getFilterName(), filterDef); } fireContainerEvent("addFilterDef", filterDef); } /** * Add a filter mapping to this Context at the end of the current set * of filter mappings. * * @param filterMap The filter mapping to be added * * @exception IllegalArgumentException if the specified filter name * does not match an existing filter definition, or the filter mapping * is malformed */ @Override public void addFilterMap(FilterMap filterMap) { validateFilterMap(filterMap); // Add this filter mapping to our registered set filterMaps.add(filterMap); fireContainerEvent("addFilterMap", filterMap); } /** * Add a filter mapping to this Context before the mappings defined in the * deployment descriptor but after any other mappings added via this method. * * @param filterMap The filter mapping to be added * * @exception IllegalArgumentException if the specified filter name * does not match an existing filter definition, or the filter mapping * is malformed */ @Override public void addFilterMapBefore(FilterMap filterMap) { validateFilterMap(filterMap); // Add this filter mapping to our registered set filterMaps.addBefore(filterMap); fireContainerEvent("addFilterMap", filterMap); } /** * Validate the supplied FilterMap. */ private void validateFilterMap(FilterMap filterMap) { // Validate the proposed filter mapping String filterName = filterMap.getFilterName(); String[] servletNames = filterMap.getServletNames(); String[] urlPatterns = filterMap.getURLPatterns(); if (findFilterDef(filterName) == null) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.name", filterName)); if (!filterMap.getMatchAllServletNames() && !filterMap.getMatchAllUrlPatterns() && (servletNames.length == 0) && (urlPatterns.length == 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); // FIXME: Older spec revisions may still check this /* if ((servletNames.length != 0) && (urlPatterns.length != 0)) throw new IllegalArgumentException (sm.getString("standardContext.filterMap.either")); */ for (int i = 0; i < urlPatterns.length; i++) { if (!validateURLPattern(urlPatterns[i])) { throw new IllegalArgumentException (sm.getString("standardContext.filterMap.pattern", urlPatterns[i])); } } } /** * Add the classname of an InstanceListener to be added to each * Wrapper appended to this Context. * * @param listener Java class name of an InstanceListener class */ @Override public void addInstanceListener(String listener) { synchronized (instanceListenersLock) { String results[] =new String[instanceListeners.length + 1]; for (int i = 0; i < instanceListeners.length; i++) results[i] = instanceListeners[i]; results[instanceListeners.length] = listener; instanceListeners = results; } fireContainerEvent("addInstanceListener", listener); } /** * Add a Locale Encoding Mapping (see Sec 5.4 of Servlet spec 2.4) * * @param locale locale to map an encoding for * @param encoding encoding to be used for a give locale */ @Override public void addLocaleEncodingMappingParameter(String locale, String encoding){ getCharsetMapper().addCharsetMappingFromDeploymentDescriptor(locale, encoding); } /** * Add a message destination for this web application. * * @param md New message destination */ public void addMessageDestination(MessageDestination md) { synchronized (messageDestinations) { messageDestinations.put(md.getName(), md); } fireContainerEvent("addMessageDestination", md.getName()); } /** * Add a message destination reference for this web application. * * @param mdr New message destination reference */ public void addMessageDestinationRef (MessageDestinationRef mdr) { namingResources.addMessageDestinationRef(mdr); fireContainerEvent("addMessageDestinationRef", mdr.getName()); } /** * Add a new MIME mapping, replacing any existing mapping for * the specified extension. * * @param extension Filename extension being mapped * @param mimeType Corresponding MIME type */ @Override public void addMimeMapping(String extension, String mimeType) { synchronized (mimeMappings) { mimeMappings.put(extension.toLowerCase(Locale.ENGLISH), mimeType); } fireContainerEvent("addMimeMapping", extension); } /** * Add a new context initialization parameter. * * @param name Name of the new parameter * @param value Value of the new parameter * * @exception IllegalArgumentException if the name or value is missing, * or if this context initialization parameter has already been * registered */ @Override public void addParameter(String name, String value) { // Validate the proposed context initialization parameter if ((name == null) || (value == null)) throw new IllegalArgumentException (sm.getString("standardContext.parameter.required")); if (parameters.get(name) != null) throw new IllegalArgumentException (sm.getString("standardContext.parameter.duplicate", name)); // Add this parameter to our defined set synchronized (parameters) { parameters.put(name, value); } fireContainerEvent("addParameter", name); } /** * Add a security role reference for this web application. * * @param role Security role used in the application * @param link Actual security role to check for */ @Override public void addRoleMapping(String role, String link) { synchronized (roleMappings) { roleMappings.put(role, link); } fireContainerEvent("addRoleMapping", role); } /** * Add a new security role for this web application. * * @param role New security role */ @Override public void addSecurityRole(String role) { synchronized (securityRolesLock) { String results[] =new String[securityRoles.length + 1]; for (int i = 0; i < securityRoles.length; i++) results[i] = securityRoles[i]; results[securityRoles.length] = role; securityRoles = results; } fireContainerEvent("addSecurityRole", role); } /** * Add a new servlet mapping, replacing any existing mapping for * the specified pattern. * * @param pattern URL pattern to be mapped * @param name Name of the corresponding servlet to execute * * @exception IllegalArgumentException if the specified servlet name * is not known to this Context */ @Override public void addServletMapping(String pattern, String name) { addServletMapping(pattern, name, false); } /** * Add a new servlet mapping, replacing any existing mapping for * the specified pattern. * * @param pattern URL pattern to be mapped * @param name Name of the corresponding servlet to execute * @param jspWildCard true if name identifies the JspServlet * and pattern contains a wildcard; false otherwise * * @exception IllegalArgumentException if the specified servlet name * is not known to this Context */ @Override public void addServletMapping(String pattern, String name, boolean jspWildCard) { // Validate the proposed mapping if (findChild(name) == null) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.name", name)); String decodedPattern = adjustURLPattern(UDecoder.URLDecode(pattern)); if (!validateURLPattern(decodedPattern)) throw new IllegalArgumentException (sm.getString("standardContext.servletMap.pattern", decodedPattern)); // Add this mapping to our registered set synchronized (servletMappingsLock) { String name2 = servletMappings.get(decodedPattern); if (name2 != null) { // Don't allow more than one servlet on the same pattern Wrapper wrapper = (Wrapper) findChild(name2); wrapper.removeMapping(decodedPattern); } servletMappings.put(decodedPattern, name); } Wrapper wrapper = (Wrapper) findChild(name); wrapper.addMapping(decodedPattern); fireContainerEvent("addServletMapping", decodedPattern); } /** * Add a new watched resource to the set recognized by this Context. * * @param name New watched resource file name */ @Override public void addWatchedResource(String name) { synchronized (watchedResourcesLock) { String results[] = new String[watchedResources.length + 1]; for (int i = 0; i < watchedResources.length; i++) results[i] = watchedResources[i]; results[watchedResources.length] = name; watchedResources = results; } fireContainerEvent("addWatchedResource", name); } /** * Add a new welcome file to the set recognized by this Context. * * @param name New welcome file name */ @Override public void addWelcomeFile(String name) { synchronized (welcomeFilesLock) { // Welcome files from the application deployment descriptor // completely replace those from the default conf/web.xml file if (replaceWelcomeFiles) { fireContainerEvent(CLEAR_WELCOME_FILES_EVENT, null); welcomeFiles = new String[0]; setReplaceWelcomeFiles(false); } String results[] =new String[welcomeFiles.length + 1]; for (int i = 0; i < welcomeFiles.length; i++) results[i] = welcomeFiles[i]; results[welcomeFiles.length] = name; welcomeFiles = results; } if(this.getState().equals(LifecycleState.STARTED)) fireContainerEvent(ADD_WELCOME_FILE_EVENT, name); } /** * Add the classname of a LifecycleListener to be added to each * Wrapper appended to this Context. * * @param listener Java class name of a LifecycleListener class */ @Override public void addWrapperLifecycle(String listener) { synchronized (wrapperLifecyclesLock) { String results[] =new String[wrapperLifecycles.length + 1]; for (int i = 0; i < wrapperLifecycles.length; i++) results[i] = wrapperLifecycles[i]; results[wrapperLifecycles.length] = listener; wrapperLifecycles = results; } fireContainerEvent("addWrapperLifecycle", listener); } /** * Add the classname of a ContainerListener to be added to each * Wrapper appended to this Context. * * @param listener Java class name of a ContainerListener class */ @Override public void addWrapperListener(String listener) { synchronized (wrapperListenersLock) { String results[] =new String[wrapperListeners.length + 1]; for (int i = 0; i < wrapperListeners.length; i++) results[i] = wrapperListeners[i]; results[wrapperListeners.length] = listener; wrapperListeners = results; } fireContainerEvent("addWrapperListener", listener); } /** * Factory method to create and return a new Wrapper instance, of * the Java implementation class appropriate for this Context * implementation. The constructor of the instantiated Wrapper * will have been called, but no properties will have been set. */ @Override public Wrapper createWrapper() { Wrapper wrapper = null; if (wrapperClass != null) { try { wrapper = (Wrapper) wrapperClass.newInstance(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } else { wrapper = new StandardWrapper(); } synchronized (instanceListenersLock) { for (int i = 0; i < instanceListeners.length; i++) { try { Class<?> clazz = Class.forName(instanceListeners[i]); InstanceListener listener = (InstanceListener) clazz.newInstance(); wrapper.addInstanceListener(listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } } synchronized (wrapperLifecyclesLock) { for (int i = 0; i < wrapperLifecycles.length; i++) { try { Class<?> clazz = Class.forName(wrapperLifecycles[i]); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); wrapper.addLifecycleListener(listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } } synchronized (wrapperListenersLock) { for (int i = 0; i < wrapperListeners.length; i++) { try { Class<?> clazz = Class.forName(wrapperListeners[i]); ContainerListener listener = (ContainerListener) clazz.newInstance(); wrapper.addContainerListener(listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("createWrapper", t); return (null); } } } return (wrapper); } /** * Return the set of application listener class names configured * for this application. */ @Override public ApplicationListener[] findApplicationListeners() { return (applicationListeners); } /** * Return the set of application parameters for this application. */ @Override public ApplicationParameter[] findApplicationParameters() { synchronized (applicationParametersLock) { return (applicationParameters); } } /** * Return the security constraints for this web application. * If there are none, a zero-length array is returned. */ @Override public SecurityConstraint[] findConstraints() { return (constraints); } /** * Return the error page entry for the specified HTTP error code, * if any; otherwise return <code>null</code>. * * @param errorCode Error code to look up */ @Override public ErrorPage findErrorPage(int errorCode) { return statusPages.get(Integer.valueOf(errorCode)); } /** * Return the error page entry for the specified Java exception type, * if any; otherwise return <code>null</code>. * * @param exceptionType Exception type to look up */ @Override public ErrorPage findErrorPage(String exceptionType) { synchronized (exceptionPages) { return (exceptionPages.get(exceptionType)); } } /** * Return the set of defined error pages for all specified error codes * and exception types. */ @Override public ErrorPage[] findErrorPages() { synchronized(exceptionPages) { synchronized(statusPages) { ErrorPage results1[] = new ErrorPage[exceptionPages.size()]; results1 = exceptionPages.values().toArray(results1); ErrorPage results2[] = new ErrorPage[statusPages.size()]; results2 = statusPages.values().toArray(results2); ErrorPage results[] = new ErrorPage[results1.length + results2.length]; for (int i = 0; i < results1.length; i++) results[i] = results1[i]; for (int i = results1.length; i < results.length; i++) results[i] = results2[i - results1.length]; return (results); } } } /** * Return the filter definition for the specified filter name, if any; * otherwise return <code>null</code>. * * @param filterName Filter name to look up */ @Override public FilterDef findFilterDef(String filterName) { synchronized (filterDefs) { return (filterDefs.get(filterName)); } } /** * Return the set of defined filters for this Context. */ @Override public FilterDef[] findFilterDefs() { synchronized (filterDefs) { FilterDef results[] = new FilterDef[filterDefs.size()]; return (filterDefs.values().toArray(results)); } } /** * Return the set of filter mappings for this Context. */ @Override public FilterMap[] findFilterMaps() { return filterMaps.asArray(); } /** * Return the set of InstanceListener classes that will be added to * newly created Wrappers automatically. */ @Override public String[] findInstanceListeners() { synchronized (instanceListenersLock) { return (instanceListeners); } } /** * Return the message destination with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired message destination */ public MessageDestination findMessageDestination(String name) { synchronized (messageDestinations) { return (messageDestinations.get(name)); } } /** * Return the set of defined message destinations for this web * application. If none have been defined, a zero-length array * is returned. */ public MessageDestination[] findMessageDestinations() { synchronized (messageDestinations) { MessageDestination results[] = new MessageDestination[messageDestinations.size()]; return (messageDestinations.values().toArray(results)); } } /** * Return the message destination ref with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired message destination ref */ public MessageDestinationRef findMessageDestinationRef(String name) { return namingResources.findMessageDestinationRef(name); } /** * Return the set of defined message destination refs for this web * application. If none have been defined, a zero-length array * is returned. */ public MessageDestinationRef[] findMessageDestinationRefs() { return namingResources.findMessageDestinationRefs(); } /** * Return the MIME type to which the specified extension is mapped, * if any; otherwise return <code>null</code>. * * @param extension Extension to map to a MIME type */ @Override public String findMimeMapping(String extension) { return (mimeMappings.get(extension.toLowerCase(Locale.ENGLISH))); } /** * Return the extensions for which MIME mappings are defined. If there * are none, a zero-length array is returned. */ @Override public String[] findMimeMappings() { synchronized (mimeMappings) { String results[] = new String[mimeMappings.size()]; return (mimeMappings.keySet().toArray(results)); } } /** * Return the value for the specified context initialization * parameter name, if any; otherwise return <code>null</code>. * * @param name Name of the parameter to return */ @Override public String findParameter(String name) { synchronized (parameters) { return (parameters.get(name)); } } /** * Return the names of all defined context initialization parameters * for this Context. If no parameters are defined, a zero-length * array is returned. */ @Override public String[] findParameters() { synchronized (parameters) { String results[] = new String[parameters.size()]; return (parameters.keySet().toArray(results)); } } /** * For the given security role (as used by an application), return the * corresponding role name (as defined by the underlying Realm) if there * is one. Otherwise, return the specified role unchanged. * * @param role Security role to map */ @Override public String findRoleMapping(String role) { String realRole = null; synchronized (roleMappings) { realRole = roleMappings.get(role); } if (realRole != null) return (realRole); else return (role); } /** * Return <code>true</code> if the specified security role is defined * for this application; otherwise return <code>false</code>. * * @param role Security role to verify */ @Override public boolean findSecurityRole(String role) { synchronized (securityRolesLock) { for (int i = 0; i < securityRoles.length; i++) { if (role.equals(securityRoles[i])) return (true); } } return (false); } /** * Return the security roles defined for this application. If none * have been defined, a zero-length array is returned. */ @Override public String[] findSecurityRoles() { synchronized (securityRolesLock) { return (securityRoles); } } /** * Return the servlet name mapped by the specified pattern (if any); * otherwise return <code>null</code>. * * @param pattern Pattern for which a mapping is requested */ @Override public String findServletMapping(String pattern) { synchronized (servletMappingsLock) { return (servletMappings.get(pattern)); } } /** * Return the patterns of all defined servlet mappings for this * Context. If no mappings are defined, a zero-length array is returned. */ @Override public String[] findServletMappings() { synchronized (servletMappingsLock) { String results[] = new String[servletMappings.size()]; return (servletMappings.keySet().toArray(results)); } } /** * Return the context-relative URI of the error page for the specified * HTTP status code, if any; otherwise return <code>null</code>. * * @param status HTTP status code to look up */ @Override public String findStatusPage(int status) { ErrorPage errorPage = statusPages.get(Integer.valueOf(status)); if (errorPage!=null) { return errorPage.getLocation(); } return null; } /** * Return the set of HTTP status codes for which error pages have * been specified. If none are specified, a zero-length array * is returned. */ @Override public int[] findStatusPages() { synchronized (statusPages) { int results[] = new int[statusPages.size()]; Iterator<Integer> elements = statusPages.keySet().iterator(); int i = 0; while (elements.hasNext()) results[i++] = elements.next().intValue(); return (results); } } /** * Return <code>true</code> if the specified welcome file is defined * for this Context; otherwise return <code>false</code>. * * @param name Welcome file to verify */ @Override public boolean findWelcomeFile(String name) { synchronized (welcomeFilesLock) { for (int i = 0; i < welcomeFiles.length; i++) { if (name.equals(welcomeFiles[i])) return (true); } } return (false); } /** * Return the set of watched resources for this Context. If none are * defined, a zero length array will be returned. */ @Override public String[] findWatchedResources() { synchronized (watchedResourcesLock) { return watchedResources; } } /** * Return the set of welcome files defined for this Context. If none are * defined, a zero-length array is returned. */ @Override public String[] findWelcomeFiles() { synchronized (welcomeFilesLock) { return (welcomeFiles); } } /** * Return the set of LifecycleListener classes that will be added to * newly created Wrappers automatically. */ @Override public String[] findWrapperLifecycles() { synchronized (wrapperLifecyclesLock) { return (wrapperLifecycles); } } /** * Return the set of ContainerListener classes that will be added to * newly created Wrappers automatically. */ @Override public String[] findWrapperListeners() { synchronized (wrapperListenersLock) { return (wrapperListeners); } } /** * Reload this web application, if reloading is supported. * <p> * <b>IMPLEMENTATION NOTE</b>: This method is designed to deal with * reloads required by changes to classes in the underlying repositories * of our class loader and changes to the web.xml file. It does not handle * changes to any context.xml file. If the context.xml has changed, you * should stop this Context and create (and start) a new Context instance * instead. Note that there is additional code in * <code>CoyoteAdapter#postParseRequest()</code> to handle mapping requests * to paused Contexts. * * @exception IllegalStateException if the <code>reloadable</code> * property is set to <code>false</code>. */ @Override public synchronized void reload() { // Validate our current component state if (!getState().isAvailable()) throw new IllegalStateException (sm.getString("standardContext.notStarted", getName())); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingStarted", getName())); // Stop accepting requests temporarily. setPaused(true); try { stop(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.stoppingContext", getName()), e); } try { start(); } catch (LifecycleException e) { log.error( sm.getString("standardContext.startingContext", getName()), e); } setPaused(false); if(log.isInfoEnabled()) log.info(sm.getString("standardContext.reloadingCompleted", getName())); } /** * Remove the specified application listener class from the set of * listeners for this application. * * @param listener Java class name of the listener to be removed */ @Override public void removeApplicationListener(String listener) { synchronized (applicationListenersLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < applicationListeners.length; i++) { if (applicationListeners[i].getClassName().equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; ApplicationListener results[] = new ApplicationListener[applicationListeners.length - 1]; for (int i = 0; i < applicationListeners.length; i++) { if (i != n) results[j++] = applicationListeners[i]; } applicationListeners = results; } // Inform interested listeners fireContainerEvent("removeApplicationListener", listener); // FIXME - behavior if already started? } /** * Remove the application parameter with the specified name from * the set for this application. * * @param name Name of the application parameter to remove */ @Override public void removeApplicationParameter(String name) { synchronized (applicationParametersLock) { // Make sure this parameter is currently present int n = -1; for (int i = 0; i < applicationParameters.length; i++) { if (name.equals(applicationParameters[i].getName())) { n = i; break; } } if (n < 0) return; // Remove the specified parameter int j = 0; ApplicationParameter results[] = new ApplicationParameter[applicationParameters.length - 1]; for (int i = 0; i < applicationParameters.length; i++) { if (i != n) results[j++] = applicationParameters[i]; } applicationParameters = results; } // Inform interested listeners fireContainerEvent("removeApplicationParameter", name); } /** * Add a child Container, only if the proposed child is an implementation * of Wrapper. * * @param child Child container to be added * * @exception IllegalArgumentException if the proposed container is * not an implementation of Wrapper */ @Override public void removeChild(Container child) { if (!(child instanceof Wrapper)) { throw new IllegalArgumentException (sm.getString("standardContext.notWrapper")); } super.removeChild(child); } /** * Remove the specified security constraint from this web application. * * @param constraint Constraint to be removed */ @Override public void removeConstraint(SecurityConstraint constraint) { synchronized (constraintsLock) { // Make sure this constraint is currently present int n = -1; for (int i = 0; i < constraints.length; i++) { if (constraints[i].equals(constraint)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; SecurityConstraint results[] = new SecurityConstraint[constraints.length - 1]; for (int i = 0; i < constraints.length; i++) { if (i != n) results[j++] = constraints[i]; } constraints = results; } // Inform interested listeners fireContainerEvent("removeConstraint", constraint); } /** * Remove the error page for the specified error code or * Java language exception, if it exists; otherwise, no action is taken. * * @param errorPage The error page definition to be removed */ @Override public void removeErrorPage(ErrorPage errorPage) { String exceptionType = errorPage.getExceptionType(); if (exceptionType != null) { synchronized (exceptionPages) { exceptionPages.remove(exceptionType); } } else { synchronized (statusPages) { statusPages.remove(Integer.valueOf(errorPage.getErrorCode())); } } fireContainerEvent("removeErrorPage", errorPage); } /** * Remove the specified filter definition from this Context, if it exists; * otherwise, no action is taken. * * @param filterDef Filter definition to be removed */ @Override public void removeFilterDef(FilterDef filterDef) { synchronized (filterDefs) { filterDefs.remove(filterDef.getFilterName()); } fireContainerEvent("removeFilterDef", filterDef); } /** * Remove a filter mapping from this Context. * * @param filterMap The filter mapping to be removed */ @Override public void removeFilterMap(FilterMap filterMap) { filterMaps.remove(filterMap); // Inform interested listeners fireContainerEvent("removeFilterMap", filterMap); } /** * Remove a class name from the set of InstanceListener classes that * will be added to newly created Wrappers. * * @param listener Class name of an InstanceListener class to be removed */ @Override public void removeInstanceListener(String listener) { synchronized (instanceListenersLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < instanceListeners.length; i++) { if (instanceListeners[i].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[instanceListeners.length - 1]; for (int i = 0; i < instanceListeners.length; i++) { if (i != n) results[j++] = instanceListeners[i]; } instanceListeners = results; } // Inform interested listeners fireContainerEvent("removeInstanceListener", listener); } /** * Remove any message destination with the specified name. * * @param name Name of the message destination to remove */ public void removeMessageDestination(String name) { synchronized (messageDestinations) { messageDestinations.remove(name); } fireContainerEvent("removeMessageDestination", name); } /** * Remove any message destination ref with the specified name. * * @param name Name of the message destination ref to remove */ public void removeMessageDestinationRef(String name) { namingResources.removeMessageDestinationRef(name); fireContainerEvent("removeMessageDestinationRef", name); } /** * Remove the MIME mapping for the specified extension, if it exists; * otherwise, no action is taken. * * @param extension Extension to remove the mapping for */ @Override public void removeMimeMapping(String extension) { synchronized (mimeMappings) { mimeMappings.remove(extension); } fireContainerEvent("removeMimeMapping", extension); } /** * Remove the context initialization parameter with the specified * name, if it exists; otherwise, no action is taken. * * @param name Name of the parameter to remove */ @Override public void removeParameter(String name) { synchronized (parameters) { parameters.remove(name); } fireContainerEvent("removeParameter", name); } /** * Remove any security role reference for the specified name * * @param role Security role (as used in the application) to remove */ @Override public void removeRoleMapping(String role) { synchronized (roleMappings) { roleMappings.remove(role); } fireContainerEvent("removeRoleMapping", role); } /** * Remove any security role with the specified name. * * @param role Security role to remove */ @Override public void removeSecurityRole(String role) { synchronized (securityRolesLock) { // Make sure this security role is currently present int n = -1; for (int i = 0; i < securityRoles.length; i++) { if (role.equals(securityRoles[i])) { n = i; break; } } if (n < 0) return; // Remove the specified security role int j = 0; String results[] = new String[securityRoles.length - 1]; for (int i = 0; i < securityRoles.length; i++) { if (i != n) results[j++] = securityRoles[i]; } securityRoles = results; } // Inform interested listeners fireContainerEvent("removeSecurityRole", role); } /** * Remove any servlet mapping for the specified pattern, if it exists; * otherwise, no action is taken. * * @param pattern URL pattern of the mapping to remove */ @Override public void removeServletMapping(String pattern) { String name = null; synchronized (servletMappingsLock) { name = servletMappings.remove(pattern); } Wrapper wrapper = (Wrapper) findChild(name); if( wrapper != null ) { wrapper.removeMapping(pattern); } fireContainerEvent("removeServletMapping", pattern); } /** * Remove the specified watched resource name from the list associated * with this Context. * * @param name Name of the watched resource to be removed */ @Override public void removeWatchedResource(String name) { synchronized (watchedResourcesLock) { // Make sure this watched resource is currently present int n = -1; for (int i = 0; i < watchedResources.length; i++) { if (watchedResources[i].equals(name)) { n = i; break; } } if (n < 0) return; // Remove the specified watched resource int j = 0; String results[] = new String[watchedResources.length - 1]; for (int i = 0; i < watchedResources.length; i++) { if (i != n) results[j++] = watchedResources[i]; } watchedResources = results; } fireContainerEvent("removeWatchedResource", name); } /** * Remove the specified welcome file name from the list recognized * by this Context. * * @param name Name of the welcome file to be removed */ @Override public void removeWelcomeFile(String name) { synchronized (welcomeFilesLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < welcomeFiles.length; i++) { if (welcomeFiles[i].equals(name)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[welcomeFiles.length - 1]; for (int i = 0; i < welcomeFiles.length; i++) { if (i != n) results[j++] = welcomeFiles[i]; } welcomeFiles = results; } // Inform interested listeners if(this.getState().equals(LifecycleState.STARTED)) fireContainerEvent(REMOVE_WELCOME_FILE_EVENT, name); } /** * Remove a class name from the set of LifecycleListener classes that * will be added to newly created Wrappers. * * @param listener Class name of a LifecycleListener class to be removed */ @Override public void removeWrapperLifecycle(String listener) { synchronized (wrapperLifecyclesLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < wrapperLifecycles.length; i++) { if (wrapperLifecycles[i].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[wrapperLifecycles.length - 1]; for (int i = 0; i < wrapperLifecycles.length; i++) { if (i != n) results[j++] = wrapperLifecycles[i]; } wrapperLifecycles = results; } // Inform interested listeners fireContainerEvent("removeWrapperLifecycle", listener); } /** * Remove a class name from the set of ContainerListener classes that * will be added to newly created Wrappers. * * @param listener Class name of a ContainerListener class to be removed */ @Override public void removeWrapperListener(String listener) { synchronized (wrapperListenersLock) { // Make sure this welcome file is currently present int n = -1; for (int i = 0; i < wrapperListeners.length; i++) { if (wrapperListeners[i].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[wrapperListeners.length - 1]; for (int i = 0; i < wrapperListeners.length; i++) { if (i != n) results[j++] = wrapperListeners[i]; } wrapperListeners = results; } // Inform interested listeners fireContainerEvent("removeWrapperListener", listener); } /** * Gets the cumulative processing times of all servlets in this * StandardContext. * * @return Cumulative processing times of all servlets in this * StandardContext */ public long getProcessingTime() { long result = 0; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { result += ((StandardWrapper)children[i]).getProcessingTime(); } } return result; } /** * Gets the maximum processing time of all servlets in this * StandardContext. * * @return Maximum processing time of all servlets in this * StandardContext */ public long getMaxTime() { long result = 0; long time; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { time = ((StandardWrapper)children[i]).getMaxTime(); if (time > result) result = time; } } return result; } /** * Gets the minimum processing time of all servlets in this * StandardContext. * * @return Minimum processing time of all servlets in this * StandardContext */ public long getMinTime() { long result = -1; long time; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { time = ((StandardWrapper)children[i]).getMinTime(); if (result < 0 || time < result) result = time; } } return result; } /** * Gets the cumulative request count of all servlets in this * StandardContext. * * @return Cumulative request count of all servlets in this * StandardContext */ public int getRequestCount() { int result = 0; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { result += ((StandardWrapper)children[i]).getRequestCount(); } } return result; } /** * Gets the cumulative error count of all servlets in this * StandardContext. * * @return Cumulative error count of all servlets in this * StandardContext */ public int getErrorCount() { int result = 0; Container[] children = findChildren(); if (children != null) { for( int i=0; i< children.length; i++ ) { result += ((StandardWrapper)children[i]).getErrorCount(); } } return result; } /** * Return the real path for a given virtual path, if possible; otherwise * return <code>null</code>. * * @param path The path to the desired resource */ @Override public String getRealPath(String path) { if (resources != null) { return resources.getResource(path).getCanonicalPath(); } return null; } /** * hook to register that we need to scan for security annotations. * @param wrapper The wrapper for the Servlet that was added */ public ServletRegistration.Dynamic dynamicServletAdded(Wrapper wrapper) { Servlet s = wrapper.getServlet(); if (s != null && createdServlets.contains(s)) { // Mark the wrapper to indicate annotations need to be scanned wrapper.setServletSecurityAnnotationScanRequired(true); } return new ApplicationServletRegistration(wrapper, this); } /** * hook to track which registrations need annotation scanning * @param servlet */ public void dynamicServletCreated(Servlet servlet) { createdServlets.add(servlet); } /** * A helper class to manage the filter mappings in a Context. */ private static final class ContextFilterMaps { private final Object lock = new Object(); /** * The set of filter mappings for this application, in the order they * were defined in the deployment descriptor with additional mappings * added via the {@link ServletContext} possibly both before and after * those defined in the deployment descriptor. */ private FilterMap[] array = new FilterMap[0]; /** * Filter mappings added via {@link ServletContext} may have to be * inserted before the mappings in the deployment descriptor but must be * inserted in the order the {@link ServletContext} methods are called. * This isn't an issue for the mappings added after the deployment * descriptor - they are just added to the end - but correctly the * adding mappings before the deployment descriptor mappings requires * knowing where the last 'before' mapping was added. */ private int insertPoint = 0; /** * Return the set of filter mappings. */ public FilterMap[] asArray() { synchronized (lock) { return array; } } /** * Add a filter mapping at the end of the current set of filter * mappings. * * @param filterMap * The filter mapping to be added */ public void add(FilterMap filterMap) { synchronized (lock) { FilterMap results[] = Arrays.copyOf(array, array.length + 1); results[array.length] = filterMap; array = results; } } /** * Add a filter mapping before the mappings defined in the deployment * descriptor but after any other mappings added via this method. * * @param filterMap * The filter mapping to be added */ public void addBefore(FilterMap filterMap) { synchronized (lock) { FilterMap results[] = new FilterMap[array.length + 1]; System.arraycopy(array, 0, results, 0, insertPoint); System.arraycopy(array, insertPoint, results, insertPoint + 1, array.length - insertPoint); results[insertPoint] = filterMap; array = results; insertPoint++; } } /** * Remove a filter mapping. * * @param filterMap The filter mapping to be removed */ public void remove(FilterMap filterMap) { synchronized (lock) { // Make sure this filter mapping is currently present int n = -1; for (int i = 0; i < array.length; i++) { if (array[i] == filterMap) { n = i; break; } } if (n < 0) return; // Remove the specified filter mapping FilterMap results[] = new FilterMap[array.length - 1]; System.arraycopy(array, 0, results, 0, n); System.arraycopy(array, n + 1, results, n, (array.length - 1) - n); array = results; if (n < insertPoint) { insertPoint--; } } } } // --------------------------------------------------------- Public Methods /** * Configure and initialize the set of filters for this Context. * Return <code>true</code> if all filter initialization completed * successfully, or <code>false</code> otherwise. */ public boolean filterStart() { if (getLogger().isDebugEnabled()) getLogger().debug("Starting filters"); // Instantiate and record a FilterConfig for each defined filter boolean ok = true; synchronized (filterConfigs) { filterConfigs.clear(); Iterator<String> names = filterDefs.keySet().iterator(); while (names.hasNext()) { String name = names.next(); if (getLogger().isDebugEnabled()) getLogger().debug(" Starting filter '" + name + "'"); ApplicationFilterConfig filterConfig = null; try { filterConfig = new ApplicationFilterConfig(this, filterDefs.get(name)); filterConfigs.put(name, filterConfig); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.filterStart", name), t); ok = false; } } } return (ok); } /** * Finalize and release the set of filters for this Context. * Return <code>true</code> if all filter finalization completed * successfully, or <code>false</code> otherwise. */ public boolean filterStop() { if (getLogger().isDebugEnabled()) getLogger().debug("Stopping filters"); // Release all Filter and FilterConfig instances synchronized (filterConfigs) { Iterator<String> names = filterConfigs.keySet().iterator(); while (names.hasNext()) { String name = names.next(); if (getLogger().isDebugEnabled()) getLogger().debug(" Stopping filter '" + name + "'"); ApplicationFilterConfig filterConfig = filterConfigs.get(name); filterConfig.release(); } filterConfigs.clear(); } return (true); } /** * Find and return the initialized <code>FilterConfig</code> for the * specified filter name, if any; otherwise return <code>null</code>. * * @param name Name of the desired filter */ public FilterConfig findFilterConfig(String name) { return (filterConfigs.get(name)); } /** * Configure the set of instantiated application event listeners * for this Context. Return <code>true</code> if all listeners wre * initialized successfully, or <code>false</code> otherwise. */ public boolean listenerStart() { if (log.isDebugEnabled()) log.debug("Configuring application event listeners"); // Instantiate the required listeners ApplicationListener listeners[] = findApplicationListeners(); Object results[] = new Object[listeners.length]; boolean ok = true; Set<Object> noPluggabilityListeners = new HashSet<>(); for (int i = 0; i < results.length; i++) { if (getLogger().isDebugEnabled()) getLogger().debug(" Configuring event listener class '" + listeners[i] + "'"); try { ApplicationListener listener = listeners[i]; results[i] = instanceManager.newInstance( listener.getClassName()); if (listener.isPluggabilityBlocked()) { noPluggabilityListeners.add(results[i]); } } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.applicationListener", listeners[i]), t); ok = false; } } if (!ok) { getLogger().error(sm.getString("standardContext.applicationSkipped")); return (false); } // Sort listeners in two arrays ArrayList<Object> eventListeners = new ArrayList<>(); ArrayList<Object> lifecycleListeners = new ArrayList<>(); for (int i = 0; i < results.length; i++) { if ((results[i] instanceof ServletContextAttributeListener) || (results[i] instanceof ServletRequestAttributeListener) || (results[i] instanceof ServletRequestListener) || (results[i] instanceof HttpSessionIdListener) || (results[i] instanceof HttpSessionAttributeListener)) { eventListeners.add(results[i]); } if ((results[i] instanceof ServletContextListener) || (results[i] instanceof HttpSessionListener)) { lifecycleListeners.add(results[i]); } } // Listener instances may have been added directly to this Context by // ServletContextInitializers and other code via the pluggability APIs. // Put them these listeners after the ones defined in web.xml and/or // annotations then overwrite the list of instances with the new, full // list. for (Object eventListener: getApplicationEventListeners()) { eventListeners.add(eventListener); } setApplicationEventListeners(eventListeners.toArray()); for (Object lifecycleListener: getApplicationLifecycleListeners()) { lifecycleListeners.add(lifecycleListener); if (lifecycleListener instanceof ServletContextListener) { noPluggabilityListeners.add(lifecycleListener); } } setApplicationLifecycleListeners(lifecycleListeners.toArray()); // Send application start events if (getLogger().isDebugEnabled()) getLogger().debug("Sending application start events"); // Ensure context is not null getServletContext(); context.setNewServletContextListenerAllowed(false); Object instances[] = getApplicationLifecycleListeners(); if (instances == null || instances.length == 0) { return ok; } ServletContextEvent event = new ServletContextEvent(getServletContext()); ServletContextEvent tldEvent = null; if (noPluggabilityListeners.size() > 0) { tldEvent = new ServletContextEvent(new NoPluggabilityServletContext( getServletContext())); } for (int i = 0; i < instances.length; i++) { if (instances[i] == null) continue; if (!(instances[i] instanceof ServletContextListener)) continue; ServletContextListener listener = (ServletContextListener) instances[i]; try { fireContainerEvent("beforeContextInitialized", listener); if (noPluggabilityListeners.contains(listener)) { listener.contextInitialized(tldEvent); } else { listener.contextInitialized(event); } fireContainerEvent("afterContextInitialized", listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextInitialized", listener); getLogger().error (sm.getString("standardContext.listenerStart", instances[i].getClass().getName()), t); ok = false; } } return (ok); } /** * Send an application stop event to all interested listeners. * Return <code>true</code> if all events were sent successfully, * or <code>false</code> otherwise. */ public boolean listenerStop() { if (log.isDebugEnabled()) log.debug("Sending application stop events"); boolean ok = true; Object listeners[] = getApplicationLifecycleListeners(); if (listeners != null && listeners.length > 0) { ServletContextEvent event = new ServletContextEvent(getServletContext()); for (int i = 0; i < listeners.length; i++) { int j = (listeners.length - 1) - i; if (listeners[j] == null) continue; if (listeners[j] instanceof ServletContextListener) { ServletContextListener listener = (ServletContextListener) listeners[j]; try { fireContainerEvent("beforeContextDestroyed", listener); listener.contextDestroyed(event); fireContainerEvent("afterContextDestroyed", listener); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); fireContainerEvent("afterContextDestroyed", listener); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; } } try { getInstanceManager().destroyInstance(listeners[j]); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; } } } // Annotation processing listeners = getApplicationEventListeners(); if (listeners != null) { for (int i = 0; i < listeners.length; i++) { int j = (listeners.length - 1) - i; if (listeners[j] == null) continue; try { getInstanceManager().destroyInstance(listeners[j]); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); getLogger().error (sm.getString("standardContext.listenerStop", listeners[j].getClass().getName()), t); ok = false; } } } setApplicationEventListeners(null); setApplicationLifecycleListeners(null); return (ok); } /** * Allocate resources, including proxy. * Return <code>true</code> if initialization was successfull, * or <code>false</code> otherwise. */ public boolean resourcesStart() throws LifecycleException { boolean ok = true; resources.setAllowLinking(isAllowLinking()); resources.setCachingAllowed(isCachingAllowed()); resources.setCacheTtl(getCacheTTL()); resources.setCacheMaxSize(getCacheMaxSize()); resources.setCacheMaxObjectSize(getCacheObjectMaxSize()); // May have been started (but not fully configured) in init() so no need // to start the resources if they are already available if (!resources.getState().isAvailable()) { resources.start(); } if (effectiveMajorVersion >=3 && addWebinfClassesResources) { WebResource webinfClassesResource = resources.getResource( "/WEB-INF/classes/META-INF/resources"); if (webinfClassesResource.isDirectory()) { getResources().createWebResourceSet( WebResourceRoot.ResourceSetType.RESOURCE_JAR, webinfClassesResource.getURL(), "/", "/"); } } return ok; } /** * Deallocate resources and destroy proxy. */ public boolean resourcesStop() { boolean ok = true; Lock writeLock = resourcesLock.writeLock(); writeLock.lock(); try { if (resources != null) { resources.stop(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("standardContext.resourcesStop"), t); ok = false; } finally { writeLock.unlock(); } return ok; } /** * Load and initialize all servlets marked "load on startup" in the * web application deployment descriptor. * * @param children Array of wrappers for all currently defined * servlets (including those not declared load on startup) */ public void loadOnStartup(Container children[]) { // Collect "load on startup" servlets that need to be initialized TreeMap<Integer, ArrayList<Wrapper>> map = new TreeMap<>(); for (int i = 0; i < children.length; i++) { Wrapper wrapper = (Wrapper) children[i]; int loadOnStartup = wrapper.getLoadOnStartup(); if (loadOnStartup < 0) continue; Integer key = Integer.valueOf(loadOnStartup); ArrayList<Wrapper> list = map.get(key); if (list == null) { list = new ArrayList<>(); map.put(key, list); } list.add(wrapper); } // Load the collected "load on startup" servlets for (ArrayList<Wrapper> list : map.values()) { for (Wrapper wrapper : list) { try { wrapper.load(); } catch (ServletException e) { getLogger().error(sm.getString("standardWrapper.loadException", getName()), StandardWrapper.getRootCause(e)); // NOTE: load errors (including a servlet that throws // UnavailableException from tht init() method) are NOT // fatal to application startup } } } } /** * Start this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void startInternal() throws LifecycleException { if(log.isDebugEnabled()) log.debug("Starting " + getBaseName()); // Send j2ee.state.starting notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.starting", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setConfigured(false); boolean ok = true; // Currently this is effectively a NO-OP but needs to be called to // ensure the NamingResources follows the correct lifecycle if (namingResources != null) { namingResources.start(); } // Add missing components as necessary if (getResources() == null) { // (1) Required by Loader if (log.isDebugEnabled()) log.debug("Configuring default Resources"); try { setResources(new StandardRoot(this)); } catch (IllegalArgumentException e) { log.error("Error initializing resources: " + e.getMessage()); ok = false; } } if (ok) { if (!resourcesStart()) { log.error( "Error in resourceStart()"); ok = false; } } if (getLoader() == null) { WebappLoader webappLoader = new WebappLoader(getParentClassLoader()); webappLoader.setDelegate(getDelegate()); setLoader(webappLoader); } // Initialize character set mapper getCharsetMapper(); // Post work directory postWorkDirectory(); // Validate required extensions boolean dependencyCheck = true; try { dependencyCheck = ExtensionValidator.validateApplication (getResources(), this); } catch (IOException ioe) { log.error("Error in dependencyCheck", ioe); dependencyCheck = false; } if (!dependencyCheck) { // do not make application available if depency check fails ok = false; } // Reading the "catalina.useNaming" environment variable String useNamingProperty = System.getProperty("catalina.useNaming"); if ((useNamingProperty != null) && (useNamingProperty.equals("false"))) { useNaming = false; } if (ok && isUseNaming()) { if (getNamingContextListener() == null) { NamingContextListener ncl = new NamingContextListener(); ncl.setName(getNamingContextName()); ncl.setExceptionOnFailedWrite(getJndiExceptionOnFailedWrite()); addLifecycleListener(ncl); setNamingContextListener(ncl); } } // Standard container startup if (log.isDebugEnabled()) log.debug("Processing standard container startup"); // Binding thread ClassLoader oldCCL = bindThread(); try { if (ok) { // Start our subordinate components, if any Loader loader = getLoader(); if ((loader != null) && (loader instanceof Lifecycle)) ((Lifecycle) loader).start(); // since the loader just started, the webapp classloader is now // created. setClassLoaderProperty("antiJARLocking", getAntiJARLocking()); setClassLoaderProperty("clearReferencesStatic", getClearReferencesStatic()); setClassLoaderProperty("clearReferencesStopThreads", getClearReferencesStopThreads()); setClassLoaderProperty("clearReferencesStopTimerThreads", getClearReferencesStopTimerThreads()); setClassLoaderProperty("clearReferencesHttpClientKeepAliveThread", getClearReferencesHttpClientKeepAliveThread()); // By calling unbindThread and bindThread in a row, we setup the // current Thread CCL to be the webapp classloader unbindThread(oldCCL); oldCCL = bindThread(); // Initialize logger again. Other components might have used it // too early, so it should be reset. logger = null; getLogger(); Cluster cluster = getClusterInternal(); if ((cluster != null) && (cluster instanceof Lifecycle)) ((Lifecycle) cluster).start(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) ((Lifecycle) realm).start(); // Notify our interested LifecycleListeners fireLifecycleEvent(Lifecycle.CONFIGURE_START_EVENT, null); // Start our child containers, if not already started for (Container child : findChildren()) { if (!child.getState().isAvailable()) { child.start(); } } // Start the Valves in our pipeline (including the basic), // if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).start(); } // Acquire clustered manager Manager contextManager = null; Manager manager = getManager(); if (manager == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.cluster.noManager", Boolean.valueOf((getCluster() != null)), Boolean.valueOf(distributable))); } if ( (getCluster() != null) && distributable) { try { contextManager = getCluster().createManager(getName()); } catch (Exception ex) { log.error("standardContext.clusterFail", ex); ok = false; } } else { contextManager = new StandardManager(); } } // Configure default manager if none was specified if (contextManager != null) { if (log.isDebugEnabled()) { log.debug(sm.getString("standardContext.manager", contextManager.getClass().getName())); } setManager(contextManager); } if (manager!=null && (getCluster() != null) && distributable) { //let the cluster know that there is a context that is distributable //and that it has its own manager getCluster().registerManager(manager); } } } finally { // Unbinding thread unbindThread(oldCCL); } if (!getConfigured()) { log.error( "Error getConfigured"); ok = false; } // We put the resources into the servlet context if (ok) getServletContext().setAttribute (Globals.RESOURCES_ATTR, getResources()); // Binding thread oldCCL = bindThread(); if (ok ) { if (getInstanceManager() == null) { javax.naming.Context context = null; if (isUseNaming() && getNamingContextListener() != null) { context = getNamingContextListener().getEnvContext(); } Map<String, Map<String, String>> injectionMap = buildInjectionMap( getIgnoreAnnotations() ? new NamingResourcesImpl(): getNamingResources()); setInstanceManager(new DefaultInstanceManager(context, injectionMap, this, this.getClass().getClassLoader())); getServletContext().setAttribute( InstanceManager.class.getName(), getInstanceManager()); } } try { // Create context attributes that will be required if (ok) { getServletContext().setAttribute( JarScanner.class.getName(), getJarScanner()); } // Set up the context init params mergeParameters(); // Call ServletContainerInitializers for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializers.entrySet()) { try { entry.getKey().onStartup(entry.getValue(), getServletContext()); } catch (ServletException e) { log.error(sm.getString("standardContext.sciFail"), e); ok = false; break; } } // Configure and call application event listeners if (ok) { if (!listenerStart()) { log.error( "Error listenerStart"); ok = false; } } // Check constraints for uncovered HTTP methods // Needs to be after SCIs and listeners as they may programatically // change constraints if (ok) { checkConstraintsForUncoveredMethods(findConstraints()); } try { // Start manager Manager manager = getManager(); if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) getManager()).start(); } } catch(Exception e) { log.error("Error manager.start()", e); ok = false; } // Configure and call application filters if (ok) { if (!filterStart()) { log.error("Error filterStart"); ok = false; } } // Load and initialize all "load on startup" servlets if (ok) { loadOnStartup(findChildren()); } // Start ContainerBackgroundProcessor thread super.threadStart(); } finally { // Unbinding thread unbindThread(oldCCL); } // Set available status depending upon startup success if (ok) { if (log.isDebugEnabled()) log.debug("Starting completed"); } else { log.error(sm.getString("standardContext.startFailed", getName())); } startTime=System.currentTimeMillis(); // Send j2ee.state.running notification if (ok && (this.getObjectName() != null)) { Notification notification = new Notification("j2ee.state.running", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Close all JARs right away to avoid always opening a peak number // of files on startup if (getLoader() instanceof WebappLoader) { ((WebappLoader) getLoader()).closeJARs(true); } // Reinitializing if something went wrong if (!ok) { setState(LifecycleState.FAILED); } else { setState(LifecycleState.STARTING); } } private void checkConstraintsForUncoveredMethods( SecurityConstraint[] constraints) { SecurityConstraint[] newConstraints = SecurityConstraint.findUncoveredHttpMethods(constraints, getDenyUncoveredHttpMethods(), getLogger()); for (SecurityConstraint constraint : newConstraints) { addConstraint(constraint); } } private void setClassLoaderProperty(String name, boolean value) { ClassLoader cl = getLoader().getClassLoader(); if (!IntrospectionUtils.setProperty(cl, name, Boolean.toString(value))) { // Failed to set log.info(sm.getString( "standardContext.webappClassLoader.missingProperty", name, Boolean.toString(value))); } } private Map<String, Map<String, String>> buildInjectionMap(NamingResourcesImpl namingResources) { Map<String, Map<String, String>> injectionMap = new HashMap<>(); for (Injectable resource: namingResources.findLocalEjbs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findEjbs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findEnvironments()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findMessageDestinationRefs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findResourceEnvRefs()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findResources()) { addInjectionTarget(resource, injectionMap); } for (Injectable resource: namingResources.findServices()) { addInjectionTarget(resource, injectionMap); } return injectionMap; } private void addInjectionTarget(Injectable resource, Map<String, Map<String, String>> injectionMap) { List<InjectionTarget> injectionTargets = resource.getInjectionTargets(); if (injectionTargets != null && injectionTargets.size() > 0) { String jndiName = resource.getName(); for (InjectionTarget injectionTarget: injectionTargets) { String clazz = injectionTarget.getTargetClass(); Map<String, String> injections = injectionMap.get(clazz); if (injections == null) { injections = new HashMap<>(); injectionMap.put(clazz, injections); } injections.put(injectionTarget.getTargetName(), jndiName); } } } /** * Merge the context initialization parameters specified in the application * deployment descriptor with the application parameters described in the * server configuration, respecting the <code>override</code> property of * the application parameters appropriately. */ private void mergeParameters() { Map<String,String> mergedParams = new HashMap<>(); String names[] = findParameters(); for (int i = 0; i < names.length; i++) { mergedParams.put(names[i], findParameter(names[i])); } ApplicationParameter params[] = findApplicationParameters(); for (int i = 0; i < params.length; i++) { if (params[i].getOverride()) { if (mergedParams.get(params[i].getName()) == null) { mergedParams.put(params[i].getName(), params[i].getValue()); } } else { mergedParams.put(params[i].getName(), params[i].getValue()); } } ServletContext sc = getServletContext(); for (Map.Entry<String,String> entry : mergedParams.entrySet()) { sc.setInitParameter(entry.getKey(), entry.getValue()); } } /** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { // Send j2ee.state.stopping notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopping", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } setState(LifecycleState.STOPPING); // Binding thread ClassLoader oldCCL = bindThread(); try { // Stop our child containers, if any final Container[] children = findChildren(); ClassLoader old = bindThread(); try { // Stop ContainerBackgroundProcessor thread threadStop(); for (int i = 0; i < children.length; i++) { children[i].stop(); } // Stop our filters filterStop(); Manager manager = getManager(); if (manager != null && manager instanceof Lifecycle && ((Lifecycle) manager).getState().isAvailable()) { ((Lifecycle) manager).stop(); } // Stop our application listeners listenerStop(); } finally{ unbindThread(old); } // Finalize our character set mapper setCharsetMapper(null); // Normal container shutdown processing if (log.isDebugEnabled()) log.debug("Processing standard container shutdown"); // JNDI resources are unbound in CONFIGURE_STOP_EVENT so stop // naming resoucres before they are unbound since NamingResoucres // does a JNDI lookup to retrieve the resource. This needs to be // after the application has finished with the resource if (namingResources != null) { namingResources.stop(); } fireLifecycleEvent(Lifecycle.CONFIGURE_STOP_EVENT, null); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Clear all application-originated servlet context attributes if (context != null) context.clearAttributes(); Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } Cluster cluster = getClusterInternal(); if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } Loader loader = getLoader(); if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).stop(); } // Stop resources resourcesStop(); } finally { // Unbinding thread unbindThread(oldCCL); } // Send j2ee.state.stopped notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.state.stopped", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } // Reset application context context = null; // This object will no longer be visible or used. try { resetContext(); } catch( Exception ex ) { log.error( "Error reseting context " + this + " " + ex, ex ); } //reset the instance manager instanceManager = null; if (log.isDebugEnabled()) log.debug("Stopping complete"); } /** Destroy needs to clean up the context completely. * * The problem is that undoing all the config in start() and restoring * a 'fresh' state is impossible. After stop()/destroy()/init()/start() * we should have the same state as if a fresh start was done - i.e * read modified web.xml, etc. This can only be done by completely * removing the context object and remapping a new one, or by cleaning * up everything. * * XXX Should this be done in stop() ? * */ @Override protected void destroyInternal() throws LifecycleException { // If in state NEW when destroy is called, the object name will never // have been set so the notification can't be created if (getObjectName() != null) { // Send j2ee.object.deleted notification Notification notification = new Notification("j2ee.object.deleted", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } if (namingResources != null) { namingResources.destroy(); } synchronized (instanceListenersLock) { instanceListeners = new String[0]; } Loader loader = getLoader(); if ((loader != null) && (loader instanceof Lifecycle)) { ((Lifecycle) loader).destroy(); } Manager manager = getManager(); if ((manager != null) && (manager instanceof Lifecycle)) { ((Lifecycle) manager).destroy(); } if (resources != null) { resources.destroy(); } super.destroyInternal(); } @Override public void backgroundProcess() { if (!getState().isAvailable()) return; Loader loader = getLoader(); if (loader != null) { try { loader.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString( "standardContext.backgroundProcess.loader", loader), e); } } Manager manager = getManager(); if (manager != null) { try { manager.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString( "standardContext.backgroundProcess.manager", manager), e); } } WebResourceRoot resources = getResources(); if (resources != null) { try { resources.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString( "standardContext.backgroundProcess.resources", resources), e); } } super.backgroundProcess(); } private void resetContext() throws Exception { // Restore the original state ( pre reading web.xml in start ) // If you extend this - override this method and make sure to clean up // Don't reset anything that is read from a <Context.../> element since // <Context .../> elements are read at initialisation will not be read // again for this object for (Container child : findChildren()) { removeChild(child); } startupTime = 0; startTime = 0; tldScanTime = 0; // Bugzilla 32867 distributable = false; applicationListeners = new ApplicationListener[0]; applicationEventListenersObjects = new Object[0]; applicationLifecycleListenersObjects = new Object[0]; jspConfigDescriptor = new ApplicationJspConfigDescriptor(); initializers.clear(); createdServlets.clear(); postConstructMethods.clear(); preDestroyMethods.clear(); if(log.isDebugEnabled()) log.debug("resetContext " + getObjectName()); } /** * Return a String representation of this component. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); if (getParent() != null) { sb.append(getParent().toString()); sb.append("."); } sb.append("StandardContext["); sb.append(getName()); sb.append("]"); return (sb.toString()); } // ------------------------------------------------------ Protected Methods /** * Adjust the URL pattern to begin with a leading slash, if appropriate * (i.e. we are running a servlet 2.2 application). Otherwise, return * the specified URL pattern unchanged. * * @param urlPattern The URL pattern to be adjusted (if needed) * and returned */ protected String adjustURLPattern(String urlPattern) { if (urlPattern == null) return (urlPattern); if (urlPattern.startsWith("/") || urlPattern.startsWith("*.")) return (urlPattern); if (!isServlet22()) return (urlPattern); if(log.isDebugEnabled()) log.debug(sm.getString("standardContext.urlPattern.patternWarning", urlPattern)); return ("/" + urlPattern); } /** * Are we processing a version 2.2 deployment descriptor? */ @Override public boolean isServlet22() { if (this.publicId == null) return (false); if (this.publicId.equals (org.apache.catalina.startup.Constants.WebDtdPublicId_22)) return (true); else return (false); } @Override public Set<String> addServletSecurity( ServletRegistration.Dynamic registration, ServletSecurityElement servletSecurityElement) { Set<String> conflicts = new HashSet<>(); Collection<String> urlPatterns = registration.getMappings(); for (String urlPattern : urlPatterns) { boolean foundConflict = false; SecurityConstraint[] securityConstraints = findConstraints(); for (SecurityConstraint securityConstraint : securityConstraints) { SecurityCollection[] collections = securityConstraint.findCollections(); for (SecurityCollection collection : collections) { if (collection.findPattern(urlPattern)) { // First pattern found will indicate if there is a // conflict since for any given pattern all matching // constraints will be from either the descriptor or // not. It is not permitted to have a mixture if (collection.isFromDescriptor()) { // Skip this pattern foundConflict = true; conflicts.add(urlPattern); break; } else { // Need to overwrite constraint for this pattern collection.removePattern(urlPattern); // If the collection is now empty, remove it if (collection.findPatterns().length == 0) { securityConstraint.removeCollection(collection); } } } } // If the constraint now has no collections - remove it if (securityConstraint.findCollections().length == 0) { removeConstraint(securityConstraint); } // No need to check other constraints for the current pattern // once a conflict has been found if (foundConflict) { break; } } // Note: For progammatically added Servlets this may not be the // complete set of security constraints since additional // URL patterns can be added after the application has called // setSecurity. For all programmatically added servilets, the // #dynamicServletAdded() method sets a flag that ensures that // the constraints are re-evaluated before the servlet is // first used // If the pattern did not conflict, add the new constraint(s). if (!foundConflict) { SecurityConstraint[] newSecurityConstraints = SecurityConstraint.createConstraints( servletSecurityElement, urlPattern); for (SecurityConstraint securityConstraint : newSecurityConstraints) { addConstraint(securityConstraint); } checkConstraintsForUncoveredMethods(newSecurityConstraints); } } return conflicts; } /** * Bind current thread, both for CL purposes and for JNDI ENC support * during : startup, shutdown and realoading of the context. * * @return the previous context class loader */ protected ClassLoader bindThread() { ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); if (getLoader() != null && getLoader().getClassLoader() != null) { Thread.currentThread().setContextClassLoader (getLoader().getClassLoader()); } if (isUseNaming()) { try { ContextBindings.bindThread(this, this); } catch (NamingException e) { // Silent catch, as this is a normal case during the early // startup stages } } return oldContextClassLoader; } /** * Unbind thread. */ protected void unbindThread(ClassLoader oldContextClassLoader) { if (isUseNaming()) { ContextBindings.unbindThread(this, this); } Thread.currentThread().setContextClassLoader(oldContextClassLoader); } /** * Get base path. */ protected String getBasePath() { String docBase = null; Container container = this; while (container != null) { if (container instanceof Host) break; container = container.getParent(); } File file = new File(getDocBase()); if (!file.isAbsolute()) { if (container == null) { docBase = (new File(getCatalinaBase(), getDocBase())).getPath(); } else { // Use the "appBase" property of this container file = ((Host) container).getAppBaseFile(); docBase = (new File(file, getDocBase())).getPath(); } } else { docBase = file.getPath(); } return docBase; } /** * Get naming context full name. */ private String getNamingContextName() { if (namingContextName == null) { Container parent = getParent(); if (parent == null) { namingContextName = getName(); } else { Stack<String> stk = new Stack<>(); StringBuilder buff = new StringBuilder(); while (parent != null) { stk.push(parent.getName()); parent = parent.getParent(); } while (!stk.empty()) { buff.append("/" + stk.pop()); } buff.append(getName()); namingContextName = buff.toString(); } } return namingContextName; } /** * Naming context listener accessor. */ public NamingContextListener getNamingContextListener() { return namingContextListener; } /** * Naming context listener setter. */ public void setNamingContextListener(NamingContextListener namingContextListener) { this.namingContextListener = namingContextListener; } /** * Return the request processing paused flag for this Context. */ @Override public boolean getPaused() { return (this.paused); } @Override public boolean fireRequestInitEvent(ServletRequest request) { Object instances[] = getApplicationEventListeners(); if ((instances != null) && (instances.length > 0)) { ServletRequestEvent event = new ServletRequestEvent(getServletContext(), request); for (int i = 0; i < instances.length; i++) { if (instances[i] == null) continue; if (!(instances[i] instanceof ServletRequestListener)) continue; ServletRequestListener listener = (ServletRequestListener) instances[i]; try { listener.requestInitialized(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[i].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; } } } return true; } @Override public boolean fireRequestDestroyEvent(ServletRequest request) { Object instances[] = getApplicationEventListeners(); if ((instances != null) && (instances.length > 0)) { ServletRequestEvent event = new ServletRequestEvent(getServletContext(), request); for (int i = 0; i < instances.length; i++) { int j = (instances.length -1) -i; if (instances[j] == null) continue; if (!(instances[j] instanceof ServletRequestListener)) continue; ServletRequestListener listener = (ServletRequestListener) instances[j]; try { listener.requestDestroyed(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLogger().error(sm.getString( "standardContext.requestListener.requestInit", instances[j].getClass().getName()), t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); return false; } } } return true; } @Override public void addPostConstructMethod(String clazz, String method) { if (clazz == null || method == null) throw new IllegalArgumentException( sm.getString("standardContext.postconstruct.required")); if (postConstructMethods.get(clazz) != null) throw new IllegalArgumentException(sm.getString( "standardContext.postconstruct.duplicate", clazz)); postConstructMethods.put(clazz, method); fireContainerEvent("addPostConstructMethod", clazz); } @Override public void removePostConstructMethod(String clazz) { postConstructMethods.remove(clazz); fireContainerEvent("removePostConstructMethod", clazz); } @Override public void addPreDestroyMethod(String clazz, String method) { if (clazz == null || method == null) throw new IllegalArgumentException( sm.getString("standardContext.predestroy.required")); if (preDestroyMethods.get(clazz) != null) throw new IllegalArgumentException(sm.getString( "standardContext.predestroy.duplicate", clazz)); preDestroyMethods.put(clazz, method); fireContainerEvent("addPreDestroyMethod", clazz); } @Override public void removePreDestroyMethod(String clazz) { preDestroyMethods.remove(clazz); fireContainerEvent("removePreDestroyMethod", clazz); } @Override public String findPostConstructMethod(String clazz) { return postConstructMethods.get(clazz); } @Override public String findPreDestroyMethod(String clazz) { return preDestroyMethods.get(clazz); } @Override public Map<String, String> findPostConstructMethods() { return postConstructMethods; } @Override public Map<String, String> findPreDestroyMethods() { return preDestroyMethods; } /** * Set the appropriate context attribute for our work directory. */ private void postWorkDirectory() { // Acquire (or calculate) the work directory path String workDir = getWorkDir(); if (workDir == null || workDir.length() == 0) { // Retrieve our parent (normally a host) name String hostName = null; String engineName = null; String hostWorkDir = null; Container parentHost = getParent(); if (parentHost != null) { hostName = parentHost.getName(); if (parentHost instanceof StandardHost) { hostWorkDir = ((StandardHost)parentHost).getWorkDir(); } Container parentEngine = parentHost.getParent(); if (parentEngine != null) { engineName = parentEngine.getName(); } } if ((hostName == null) || (hostName.length() < 1)) hostName = "_"; if ((engineName == null) || (engineName.length() < 1)) engineName = "_"; String temp = getBaseName(); if (temp.startsWith("/")) temp = temp.substring(1); temp = temp.replace('/', '_'); temp = temp.replace('\\', '_'); if (temp.length() < 1) temp = ContextName.ROOT_NAME; if (hostWorkDir != null ) { workDir = hostWorkDir + File.separator + temp; } else { workDir = "work" + File.separator + engineName + File.separator + hostName + File.separator + temp; } setWorkDir(workDir); } // Create this directory if necessary File dir = new File(workDir); if (!dir.isAbsolute()) { String catalinaHomePath = null; try { catalinaHomePath = getCatalinaBase().getCanonicalPath(); dir = new File(catalinaHomePath, workDir); } catch (IOException e) { log.warn(sm.getString("standardContext.workCreateException", workDir, catalinaHomePath, getName()), e); } } if (!dir.mkdirs() && !dir.isDirectory()) { log.warn(sm.getString("standardContext.workCreateFail", dir, getName())); } // Set the appropriate servlet context attribute if (context == null) { getServletContext(); } context.setAttribute(ServletContext.TEMPDIR, dir); context.setAttributeReadOnly(ServletContext.TEMPDIR); } /** * Set the request processing paused flag for this Context. * * @param paused The new request processing paused flag */ private void setPaused(boolean paused) { this.paused = paused; } /** * Validate the syntax of a proposed <code>&lt;url-pattern&gt;</code> * for conformance with specification requirements. * * @param urlPattern URL pattern to be validated */ private boolean validateURLPattern(String urlPattern) { if (urlPattern == null) return (false); if (urlPattern.indexOf('\n') >= 0 || urlPattern.indexOf('\r') >= 0) { return (false); } if (urlPattern.equals("")) { return true; } if (urlPattern.startsWith("*.")) { if (urlPattern.indexOf('/') < 0) { checkUnusualURLPattern(urlPattern); return (true); } else return (false); } if ( (urlPattern.startsWith("/")) && (urlPattern.indexOf("*.") < 0)) { checkUnusualURLPattern(urlPattern); return (true); } else return (false); } /** * Check for unusual but valid <code>&lt;url-pattern&gt;</code>s. * See Bugzilla 34805, 43079 & 43080 */ private void checkUnusualURLPattern(String urlPattern) { if (log.isInfoEnabled()) { if(urlPattern.endsWith("*") && (urlPattern.length() < 2 || urlPattern.charAt(urlPattern.length()-2) != '/')) { log.info("Suspicious url pattern: \"" + urlPattern + "\"" + " in context [" + getName() + "] - see" + " section SRV.11.2 of the Servlet specification" ); } } } // ------------------------------------------------------------- Operations /** * JSR77 deploymentDescriptor attribute * * @return string deployment descriptor */ public String getDeploymentDescriptor() { InputStream stream = null; ServletContext servletContext = getServletContext(); if (servletContext != null) { stream = servletContext.getResourceAsStream( org.apache.catalina.startup.Constants.ApplicationWebXml); } if (stream == null) { return ""; } StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new InputStreamReader(stream)); String strRead = ""; while (strRead != null) { sb.append(strRead); strRead = br.readLine(); } } catch (IOException e) { return ""; } finally { if (br != null) { try { br.close(); } catch (IOException ioe) {/*Ignore*/} } } return sb.toString(); } /** * JSR77 servlets attribute * * @return list of all servlets ( we know about ) */ public String[] getServlets() { String[] result = null; Container[] children = findChildren(); if (children != null) { result = new String[children.length]; for( int i=0; i< children.length; i++ ) { result[i] = children[i].getObjectName().toString(); } } return result; } @Override protected String getObjectNameKeyProperties() { StringBuilder keyProperties = new StringBuilder("j2eeType=WebModule,"); keyProperties.append(getObjectKeyPropertiesNameOnly()); keyProperties.append(",J2EEApplication="); keyProperties.append(getJ2EEApplication()); keyProperties.append(",J2EEServer="); keyProperties.append(getJ2EEServer()); return keyProperties.toString(); } private String getObjectKeyPropertiesNameOnly() { StringBuilder result = new StringBuilder("name=//"); String hostname = getParent().getName(); if (hostname == null) { result.append("DEFAULT"); } else { result.append(hostname); } String contextName = getName(); if (!contextName.startsWith("/")) { result.append('/'); } result.append(contextName); return result.toString(); } @Override protected void initInternal() throws LifecycleException { super.initInternal(); if (processTlds) { this.addLifecycleListener(new TldConfig()); } // Register the naming resources if (namingResources != null) { namingResources.init(); } if (resources != null) { resources.start(); } // Send j2ee.object.created notification if (this.getObjectName() != null) { Notification notification = new Notification("j2ee.object.created", this.getObjectName(), sequenceNumber.getAndIncrement()); broadcaster.sendNotification(notification); } } /* Remove a JMX notficationListener * @see javax.management.NotificationEmitter#removeNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object) */ @Override public void removeNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener,filter,object); } private MBeanNotificationInfo[] notificationInfo; /* Get JMX Broadcaster Info * @TODO use StringManager for international support! * @TODO This two events we not send j2ee.state.failed and j2ee.attribute.changed! * @see javax.management.NotificationBroadcaster#getNotificationInfo() */ @Override public MBeanNotificationInfo[] getNotificationInfo() { // FIXME: i18n if(notificationInfo == null) { notificationInfo = new MBeanNotificationInfo[]{ new MBeanNotificationInfo(new String[] { "j2ee.object.created"}, Notification.class.getName(), "web application is created" ), new MBeanNotificationInfo(new String[] { "j2ee.state.starting"}, Notification.class.getName(), "change web application is starting" ), new MBeanNotificationInfo(new String[] { "j2ee.state.running"}, Notification.class.getName(), "web application is running" ), new MBeanNotificationInfo(new String[] { "j2ee.state.stopping"}, Notification.class.getName(), "web application start to stopped" ), new MBeanNotificationInfo(new String[] { "j2ee.object.stopped"}, Notification.class.getName(), "web application is stopped" ), new MBeanNotificationInfo(new String[] { "j2ee.object.deleted"}, Notification.class.getName(), "web application is deleted" ) }; } return notificationInfo; } /* Add a JMX-NotificationListener * @see javax.management.NotificationBroadcaster#addNotificationListener(javax.management.NotificationListener, javax.management.NotificationFilter, java.lang.Object) */ @Override public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object object) throws IllegalArgumentException { broadcaster.addNotificationListener(listener,filter,object); } /** * Remove a JMX-NotificationListener * @see javax.management.NotificationBroadcaster#removeNotificationListener(javax.management.NotificationListener) */ @Override public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException { broadcaster.removeNotificationListener(listener); } // ------------------------------------------------------------- Attributes /** * Return the naming resources associated with this web application. */ public String[] getWelcomeFiles() { return findWelcomeFiles(); } /** * Set the validation feature of the XML parser used when * parsing xml instances. * @param webXmlValidation true to enable xml instance validation */ @Override public void setXmlValidation(boolean webXmlValidation){ this.webXmlValidation = webXmlValidation; } /** * Get the server.xml <context> attribute's xmlValidation. * @return true if validation is enabled. * */ @Override public boolean getXmlValidation(){ return webXmlValidation; } /** * Get the server.xml <context> attribute's xmlNamespaceAware. * @return true if namespace awarenes is enabled. */ @Override public boolean getXmlNamespaceAware(){ return webXmlNamespaceAware; } /** * Set the namespace aware feature of the XML parser used when * parsing xml instances. * @param webXmlNamespaceAware true to enable namespace awareness */ @Override public void setXmlNamespaceAware(boolean webXmlNamespaceAware){ this.webXmlNamespaceAware= webXmlNamespaceAware; } /** * Set the validation feature of the XML parser used when * parsing tlds files. * @param tldValidation true to enable xml instance validation */ @Override public void setTldValidation(boolean tldValidation){ this.tldValidation = tldValidation; } /** * Get the server.xml <context> attribute's webXmlValidation. * @return true if validation is enabled. * */ @Override public boolean getTldValidation(){ return tldValidation; } /** * Sets the process TLDs attribute. * * @param newProcessTlds The new value */ public void setProcessTlds(boolean newProcessTlds) { processTlds = newProcessTlds; } /** * Returns the processTlds attribute value. */ public boolean getProcessTlds() { return processTlds; } /** * Get the server.xml &lt;host&gt; attribute's xmlNamespaceAware. * @return true if namespace awarenes is enabled. */ @Override public boolean getTldNamespaceAware(){ return tldNamespaceAware; } /** * Set the namespace aware feature of the XML parser used when * parsing xml instances. * @param tldNamespaceAware true to enable namespace awareness */ @Override public void setTldNamespaceAware(boolean tldNamespaceAware){ this.tldNamespaceAware= tldNamespaceAware; } /** * Support for "stateManageable" JSR77 */ public boolean isStateManageable() { return true; } /** * The J2EE Server ObjectName this module is deployed on. */ private String server = null; /** * The Java virtual machines on which this module is running. */ private String[] javaVMs = null; public String getServer() { return server; } public String setServer(String server) { return this.server=server; } public String[] getJavaVMs() { return javaVMs; } public String[] setJavaVMs(String[] javaVMs) { return this.javaVMs = javaVMs; } /** * Gets the time this context was started. * * @return Time (in milliseconds since January 1, 1970, 00:00:00) when this * context was started */ public long getStartTime() { return startTime; } private static class NoPluggabilityServletContext implements ServletContext { private final ServletContext sc; public NoPluggabilityServletContext(ServletContext sc) { this.sc = sc; } @Override public String getContextPath() { return sc.getContextPath(); } @Override public ServletContext getContext(String uripath) { return sc.getContext(uripath); } @Override public int getMajorVersion() { return sc.getMajorVersion(); } @Override public int getMinorVersion() { return sc.getMinorVersion(); } @Override public int getEffectiveMajorVersion() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public int getEffectiveMinorVersion() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public String getMimeType(String file) { return sc.getMimeType(file); } @Override public Set<String> getResourcePaths(String path) { return sc.getResourcePaths(path); } @Override public URL getResource(String path) throws MalformedURLException { return sc.getResource(path); } @Override public InputStream getResourceAsStream(String path) { return sc.getResourceAsStream(path); } @Override public RequestDispatcher getRequestDispatcher(String path) { return sc.getRequestDispatcher(path); } @Override public RequestDispatcher getNamedDispatcher(String name) { return sc.getNamedDispatcher(name); } @Override @Deprecated public Servlet getServlet(String name) throws ServletException { return sc.getServlet(name); } @Override @Deprecated public Enumeration<Servlet> getServlets() { return sc.getServlets(); } @Override @Deprecated public Enumeration<String> getServletNames() { return sc.getServletNames(); } @Override public void log(String msg) { sc.log(msg); } @Override @Deprecated public void log(Exception exception, String msg) { sc.log(exception, msg); } @Override public void log(String message, Throwable throwable) { sc.log(message, throwable); } @Override public String getRealPath(String path) { return sc.getRealPath(path); } @Override public String getServerInfo() { return sc.getServerInfo(); } @Override public String getInitParameter(String name) { return sc.getInitParameter(name); } @Override public Enumeration<String> getInitParameterNames() { return sc.getInitParameterNames(); } @Override public boolean setInitParameter(String name, String value) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Object getAttribute(String name) { return sc.getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { return sc.getAttributeNames(); } @Override public void setAttribute(String name, Object object) { sc.setAttribute(name, object); } @Override public void removeAttribute(String name) { sc.removeAttribute(name); } @Override public String getServletContextName() { return sc.getServletContextName(); } @Override public Dynamic addServlet(String servletName, String className) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Dynamic addServlet(String servletName, Servlet servlet) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public ServletRegistration getServletRegistration(String servletName) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Map<String,? extends ServletRegistration> getServletRegistrations() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, String className) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, Filter filter) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public javax.servlet.FilterRegistration.Dynamic addFilter( String filterName, Class<? extends Filter> filterClass) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public FilterRegistration getFilterRegistration(String filterName) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Map<String,? extends FilterRegistration> getFilterRegistrations() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public SessionCookieConfig getSessionCookieConfig() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void addListener(String className) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends EventListener> void addListener(T t) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void addListener(Class<? extends EventListener> listenerClass) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public JspConfigDescriptor getJspConfigDescriptor() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public ClassLoader getClassLoader() { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public void declareRoles(String... roleNames) { throw new UnsupportedOperationException( sm.getString("noPluggabilityServletContext.notAllowed")); } @Override public String getVirtualServerName() { return sc.getVirtualServerName(); } } }
55,218
Bug 55218 Upgrade Digester to be based on DefaultHandler2 and use LexicalHandler to detect publicId
Digester uses SAX2 features but is still based the SAX1 DefaultHandler. By upgrading to DefaultHandler2 it would be able to handle baseURIs when resolving entities and would have a default implementation of a LexicalHandler. Using LexicalHandler would allow it to respond directly to the startDTD event that reports the DOCTYPE (if present) so that it would not need to infer that from the first attempt to resolve an entity.
closed fixed
aa7896b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T10:07:23Z
2013-07-09T11:40:00Z
java/org/apache/tomcat/util/descriptor/web/WebXml.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.descriptor.web; import java.net.URL; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.SessionTrackingMode; import org.apache.tomcat.util.res.StringManager; /** * Representation of common elements of web.xml and web-fragment.xml. Provides * a repository for parsed data before the elements are merged. * Validation is spread between multiple classes: * The digester checks for structural correctness (eg single login-config) * This class checks for invalid duplicates (eg filter/servlet names) * StandardContext will check validity of values (eg URL formats etc) */ public class WebXml { protected static final String ORDER_OTHERS = "org.apache.catalina.order.others"; private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog(WebXml.class); // Global defaults are overridable but Servlets and Servlet mappings need to // be unique. Duplicates normally trigger an error. This flag indicates if // newly added Servlet elements are marked as overridable. private boolean overridable = false; public boolean isOverridable() { return overridable; } public void setOverridable(boolean overridable) { this.overridable = overridable; } // web.xml only elements // Absolute Ordering private Set<String> absoluteOrdering = null; public void createAbsoluteOrdering() { if (absoluteOrdering == null) { absoluteOrdering = new LinkedHashSet<>(); } } public void addAbsoluteOrdering(String fragmentName) { createAbsoluteOrdering(); absoluteOrdering.add(fragmentName); } public void addAbsoluteOrderingOthers() { createAbsoluteOrdering(); absoluteOrdering.add(ORDER_OTHERS); } public Set<String> getAbsoluteOrdering() { return absoluteOrdering; } // web-fragment.xml only elements // Relative ordering private final Set<String> after = new LinkedHashSet<>(); public void addAfterOrdering(String fragmentName) { after.add(fragmentName); } public void addAfterOrderingOthers() { if (before.contains(ORDER_OTHERS)) { throw new IllegalArgumentException(sm.getString( "webXml.multipleOther")); } after.add(ORDER_OTHERS); } public Set<String> getAfterOrdering() { return after; } private final Set<String> before = new LinkedHashSet<>(); public void addBeforeOrdering(String fragmentName) { before.add(fragmentName); } public void addBeforeOrderingOthers() { if (after.contains(ORDER_OTHERS)) { throw new IllegalArgumentException(sm.getString( "webXml.multipleOther")); } before.add(ORDER_OTHERS); } public Set<String> getBeforeOrdering() { return before; } // Common elements and attributes // Required attribute of web-app element public String getVersion() { StringBuilder sb = new StringBuilder(3); sb.append(majorVersion); sb.append('.'); sb.append(minorVersion); return sb.toString(); } /** * Set the version for this web.xml file * @param version Values of <code>null</code> will be ignored */ public void setVersion(String version) { if (version == null) return; // Update major and minor version // Expected format is n.n - allow for any number of digits just in case String major = null; String minor = null; int split = version.indexOf('.'); if (split < 0) { // Major only major = version; } else { major = version.substring(0, split); minor = version.substring(split + 1); } if (major == null || major.length() == 0) { majorVersion = 0; } else { try { majorVersion = Integer.parseInt(major); } catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", major, version), nfe); majorVersion = 0; } } if (minor == null || minor.length() == 0) { minorVersion = 0; } else { try { minorVersion = Integer.parseInt(minor); } catch (NumberFormatException nfe) { log.warn(sm.getString("webXml.version.nfe", minor, version), nfe); minorVersion = 0; } } } // Optional publicId attribute private String publicId = null; public String getPublicId() { return publicId; } public void setPublicId(String publicId) { // Update major and minor version if (publicId == null) { // skip } else if (org.apache.catalina.startup.Constants.WebSchemaPublicId_31. equalsIgnoreCase(publicId) || org.apache.catalina.startup.Constants.WebFragmentSchemaPublicId_31. equalsIgnoreCase(publicId)) { majorVersion = 3; minorVersion = 1; this.publicId = publicId; } else if (org.apache.catalina.startup.Constants.WebSchemaPublicId_30. equalsIgnoreCase(publicId) || org.apache.catalina.startup.Constants.WebFragmentSchemaPublicId_30. equalsIgnoreCase(publicId)) { majorVersion = 3; minorVersion = 0; this.publicId = publicId; } else if (org.apache.catalina.startup.Constants.WebSchemaPublicId_25. equalsIgnoreCase(publicId)) { majorVersion = 2; minorVersion = 5; this.publicId = publicId; } else if (org.apache.catalina.startup.Constants.WebSchemaPublicId_24. equalsIgnoreCase(publicId)) { majorVersion = 2; minorVersion = 4; this.publicId = publicId; } else if (org.apache.catalina.startup.Constants.WebDtdPublicId_23. equalsIgnoreCase(publicId)) { majorVersion = 2; minorVersion = 3; this.publicId = publicId; } else if (org.apache.catalina.startup.Constants.WebDtdPublicId_22. equalsIgnoreCase(publicId)) { majorVersion = 2; minorVersion = 2; this.publicId = publicId; } else if ("datatypes".equals(publicId)) { // Will occur when validation is enabled and dependencies are // traced back. Ignore it. } else { // Unrecognised publicId log.warn(sm.getString("webXml.unrecognisedPublicId", publicId)); } } // Optional metadata-complete attribute private boolean metadataComplete = false; public boolean isMetadataComplete() { return metadataComplete; } public void setMetadataComplete(boolean metadataComplete) { this.metadataComplete = metadataComplete; } // Optional name element private String name = null; public String getName() { return name; } public void setName(String name) { if (ORDER_OTHERS.equalsIgnoreCase(name)) { // This is unusual. This name will be ignored. Log the fact. log.warn(sm.getString("webXml.reservedName", name)); } else { this.name = name; } } // Derived major and minor version attributes // Default to 3.0 until we know otherwise private int majorVersion = 3; private int minorVersion = 0; public int getMajorVersion() { return majorVersion; } public int getMinorVersion() { return minorVersion; } // web-app elements // TODO: Ignored elements: // - description // - icon // display-name - TODO should support multiple with language private String displayName = null; public String getDisplayName() { return displayName; } public void setDisplayName(String displayName) { this.displayName = displayName; } // distributable private boolean distributable = false; public boolean isDistributable() { return distributable; } public void setDistributable(boolean distributable) { this.distributable = distributable; } // deny-uncovered-http-methods private boolean denyUncoveredHttpMethods = false; public boolean getDenyUncoveredHttpMethods() { return denyUncoveredHttpMethods; } public void setDenyUncoveredHttpMethods(boolean denyUncoveredHttpMethods) { this.denyUncoveredHttpMethods = denyUncoveredHttpMethods; } // context-param // TODO: description (multiple with language) is ignored private final Map<String,String> contextParams = new HashMap<>(); public void addContextParam(String param, String value) { contextParams.put(param, value); } public Map<String,String> getContextParams() { return contextParams; } // filter // TODO: Should support multiple description elements with language // TODO: Should support multiple display-name elements with language // TODO: Should support multiple icon elements // TODO: Description for init-param is ignored private final Map<String,FilterDef> filters = new LinkedHashMap<>(); public void addFilter(FilterDef filter) { if (filters.containsKey(filter.getFilterName())) { // Filter names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateFilter", filter.getFilterName())); } filters.put(filter.getFilterName(), filter); } public Map<String,FilterDef> getFilters() { return filters; } // filter-mapping private final Set<FilterMap> filterMaps = new LinkedHashSet<>(); private final Set<String> filterMappingNames = new HashSet<>(); public void addFilterMapping(FilterMap filterMap) { filterMaps.add(filterMap); filterMappingNames.add(filterMap.getFilterName()); } public Set<FilterMap> getFilterMappings() { return filterMaps; } // listener // TODO: description (multiple with language) is ignored // TODO: display-name (multiple with language) is ignored // TODO: icon (multiple) is ignored private final Set<String> listeners = new LinkedHashSet<>(); public void addListener(String className) { listeners.add(className); } public Set<String> getListeners() { return listeners; } // servlet // TODO: description (multiple with language) is ignored // TODO: display-name (multiple with language) is ignored // TODO: icon (multiple) is ignored // TODO: init-param/description (multiple with language) is ignored // TODO: security-role-ref/description (multiple with language) is ignored private final Map<String,ServletDef> servlets = new HashMap<>(); public void addServlet(ServletDef servletDef) { servlets.put(servletDef.getServletName(), servletDef); if (overridable) { servletDef.setOverridable(overridable); } } public Map<String,ServletDef> getServlets() { return servlets; } // servlet-mapping private final Map<String,String> servletMappings = new HashMap<>(); private final Set<String> servletMappingNames = new HashSet<>(); public void addServletMapping(String urlPattern, String servletName) { String oldServletName = servletMappings.put(urlPattern, servletName); if (oldServletName != null) { // Duplicate mapping. As per clarification from the Servlet EG, // deployment should fail. throw new IllegalArgumentException(sm.getString( "webXml.duplicateServletMapping", oldServletName, servletName, urlPattern)); } servletMappingNames.add(servletName); } public Map<String,String> getServletMappings() { return servletMappings; } // session-config // Digester will check there is only one of these private SessionConfig sessionConfig = new SessionConfig(); public void setSessionConfig(SessionConfig sessionConfig) { this.sessionConfig = sessionConfig; } public SessionConfig getSessionConfig() { return sessionConfig; } // mime-mapping private final Map<String,String> mimeMappings = new HashMap<>(); public void addMimeMapping(String extension, String mimeType) { mimeMappings.put(extension, mimeType); } public Map<String,String> getMimeMappings() { return mimeMappings; } // welcome-file-list merge control private boolean replaceWelcomeFiles = false; private boolean alwaysAddWelcomeFiles = true; /** * When merging/parsing web.xml files into this web.xml should the current * set be completely replaced? */ public void setReplaceWelcomeFiles(boolean replaceWelcomeFiles) { this.replaceWelcomeFiles = replaceWelcomeFiles; } /** * When merging from this web.xml, should the welcome files be added to the * target web.xml even if it already contains welcome file definitions. */ public void setAlwaysAddWelcomeFiles(boolean alwaysAddWelcomeFiles) { this.alwaysAddWelcomeFiles = alwaysAddWelcomeFiles; } // welcome-file-list private final Set<String> welcomeFiles = new LinkedHashSet<>(); public void addWelcomeFile(String welcomeFile) { if (replaceWelcomeFiles) { welcomeFiles.clear(); replaceWelcomeFiles = false; } welcomeFiles.add(welcomeFile); } public Set<String> getWelcomeFiles() { return welcomeFiles; } // error-page private final Map<String,ErrorPage> errorPages = new HashMap<>(); public void addErrorPage(ErrorPage errorPage) { errorPages.put(errorPage.getName(), errorPage); } public Map<String,ErrorPage> getErrorPages() { return errorPages; } // Digester will check there is only one jsp-config // jsp-config/taglib or taglib (2.3 and earlier) private final Map<String,String> taglibs = new HashMap<>(); public void addTaglib(String uri, String location) { if (taglibs.containsKey(uri)) { // Taglib URIs must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateTaglibUri", uri)); } taglibs.put(uri, location); } public Map<String,String> getTaglibs() { return taglibs; } // jsp-config/jsp-property-group private final Set<JspPropertyGroup> jspPropertyGroups = new LinkedHashSet<>(); public void addJspPropertyGroup(JspPropertyGroup propertyGroup) { jspPropertyGroups.add(propertyGroup); } public Set<JspPropertyGroup> getJspPropertyGroups() { return jspPropertyGroups; } // security-constraint // TODO: Should support multiple display-name elements with language // TODO: Should support multiple description elements with language private final Set<SecurityConstraint> securityConstraints = new HashSet<>(); public void addSecurityConstraint(SecurityConstraint securityConstraint) { securityConstraints.add(securityConstraint); } public Set<SecurityConstraint> getSecurityConstraints() { return securityConstraints; } // login-config // Digester will check there is only one of these private LoginConfig loginConfig = null; public void setLoginConfig(LoginConfig loginConfig) { this.loginConfig = loginConfig; } public LoginConfig getLoginConfig() { return loginConfig; } // security-role // TODO: description (multiple with language) is ignored private final Set<String> securityRoles = new HashSet<>(); public void addSecurityRole(String securityRole) { securityRoles.add(securityRole); } public Set<String> getSecurityRoles() { return securityRoles; } // env-entry // TODO: Should support multiple description elements with language private final Map<String,ContextEnvironment> envEntries = new HashMap<>(); public void addEnvEntry(ContextEnvironment envEntry) { if (envEntries.containsKey(envEntry.getName())) { // env-entry names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateEnvEntry", envEntry.getName())); } envEntries.put(envEntry.getName(),envEntry); } public Map<String,ContextEnvironment> getEnvEntries() { return envEntries; } // ejb-ref // TODO: Should support multiple description elements with language private final Map<String,ContextEjb> ejbRefs = new HashMap<>(); public void addEjbRef(ContextEjb ejbRef) { ejbRefs.put(ejbRef.getName(),ejbRef); } public Map<String,ContextEjb> getEjbRefs() { return ejbRefs; } // ejb-local-ref // TODO: Should support multiple description elements with language private final Map<String,ContextLocalEjb> ejbLocalRefs = new HashMap<>(); public void addEjbLocalRef(ContextLocalEjb ejbLocalRef) { ejbLocalRefs.put(ejbLocalRef.getName(),ejbLocalRef); } public Map<String,ContextLocalEjb> getEjbLocalRefs() { return ejbLocalRefs; } // service-ref // TODO: Should support multiple description elements with language // TODO: Should support multiple display-names elements with language // TODO: Should support multiple icon elements ??? private final Map<String,ContextService> serviceRefs = new HashMap<>(); public void addServiceRef(ContextService serviceRef) { serviceRefs.put(serviceRef.getName(), serviceRef); } public Map<String,ContextService> getServiceRefs() { return serviceRefs; } // resource-ref // TODO: Should support multiple description elements with language private final Map<String,ContextResource> resourceRefs = new HashMap<>(); public void addResourceRef(ContextResource resourceRef) { if (resourceRefs.containsKey(resourceRef.getName())) { // resource-ref names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateResourceRef", resourceRef.getName())); } resourceRefs.put(resourceRef.getName(), resourceRef); } public Map<String,ContextResource> getResourceRefs() { return resourceRefs; } // resource-env-ref // TODO: Should support multiple description elements with language private final Map<String,ContextResourceEnvRef> resourceEnvRefs = new HashMap<>(); public void addResourceEnvRef(ContextResourceEnvRef resourceEnvRef) { if (resourceEnvRefs.containsKey(resourceEnvRef.getName())) { // resource-env-ref names must be unique within a web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateResourceEnvRef", resourceEnvRef.getName())); } resourceEnvRefs.put(resourceEnvRef.getName(), resourceEnvRef); } public Map<String,ContextResourceEnvRef> getResourceEnvRefs() { return resourceEnvRefs; } // message-destination-ref // TODO: Should support multiple description elements with language private final Map<String,MessageDestinationRef> messageDestinationRefs = new HashMap<>(); public void addMessageDestinationRef( MessageDestinationRef messageDestinationRef) { if (messageDestinationRefs.containsKey( messageDestinationRef.getName())) { // message-destination-ref names must be unique within a // web(-fragment).xml throw new IllegalArgumentException(sm.getString( "webXml.duplicateMessageDestinationRef", messageDestinationRef.getName())); } messageDestinationRefs.put(messageDestinationRef.getName(), messageDestinationRef); } public Map<String,MessageDestinationRef> getMessageDestinationRefs() { return messageDestinationRefs; } // message-destination // TODO: Should support multiple description elements with language // TODO: Should support multiple display-names elements with language // TODO: Should support multiple icon elements ??? private final Map<String,MessageDestination> messageDestinations = new HashMap<>(); public void addMessageDestination( MessageDestination messageDestination) { if (messageDestinations.containsKey( messageDestination.getName())) { // message-destination names must be unique within a // web(-fragment).xml throw new IllegalArgumentException( sm.getString("webXml.duplicateMessageDestination", messageDestination.getName())); } messageDestinations.put(messageDestination.getName(), messageDestination); } public Map<String,MessageDestination> getMessageDestinations() { return messageDestinations; } // locale-encoding-mapping-list private final Map<String,String> localeEncodingMappings = new HashMap<>(); public void addLocaleEncodingMapping(String locale, String encoding) { localeEncodingMappings.put(locale, encoding); } public Map<String,String> getLocaleEncodingMappings() { return localeEncodingMappings; } // post-construct elements private Map<String, String> postConstructMethods = new HashMap<>(); public void addPostConstructMethods(String clazz, String method) { if (!postConstructMethods.containsKey(clazz)) { postConstructMethods.put(clazz, method); } } public Map<String, String> getPostConstructMethods() { return postConstructMethods; } // pre-destroy elements private Map<String, String> preDestroyMethods = new HashMap<>(); public void addPreDestroyMethods(String clazz, String method) { if (!preDestroyMethods.containsKey(clazz)) { preDestroyMethods.put(clazz, method); } } public Map<String, String> getPreDestroyMethods() { return preDestroyMethods; } // Attributes not defined in web.xml or web-fragment.xml // URL of JAR / exploded JAR for this web-fragment private URL uRL = null; public void setURL(URL url) { this.uRL = url; } public URL getURL() { return uRL; } // Name of jar file private String jarName = null; public void setJarName(String jarName) { this.jarName = jarName; } public String getJarName() { return jarName; } // Is this JAR part of the application or is it a container JAR? Assume it // is. private boolean webappJar = true; public void setWebappJar(boolean webappJar) { this.webappJar = webappJar; } public boolean getWebappJar() { return webappJar; } // Does this web application delegate first for class loading? private boolean delegate = false; public boolean getDelegate() { return delegate; } public void setDelegate(boolean delegate) { this.delegate = delegate; } @Override public String toString() { StringBuilder buf = new StringBuilder(32); buf.append("Name: "); buf.append(getName()); buf.append(", URL: "); buf.append(getURL()); return buf.toString(); } private static final String INDENT2 = " "; private static final String INDENT4 = " "; private static final String INDENT6 = " "; /** * Generate a web.xml in String form that matches the representation stored * in this object. * * @return The complete contents of web.xml as a String */ public String toXml() { StringBuilder sb = new StringBuilder(2048); // TODO - Various, icon, description etc elements are skipped - mainly // because they are ignored when web.xml is parsed - see above // Declaration sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"); // Root element sb.append("<web-app xmlns=\"http://xmlns.jcp.org/xml/ns/javaee\"\n"); sb.append(" xmlns:xsi="); sb.append("\"http://www.w3.org/2001/XMLSchema-instance\"\n"); sb.append(" xsi:schemaLocation="); sb.append("\"http://xmlns.jcp.org/xml/ns/javaee" + " http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd\"\n"); sb.append(" version=\""); sb.append(getVersion()); sb.append("\"\n"); sb.append(" metadata-complete=\"true\">\n\n"); appendElement(sb, INDENT2, "display-name", displayName); if (isDistributable()) { sb.append(" <distributable/>\n\n"); } for (Map.Entry<String, String> entry : contextParams.entrySet()) { sb.append(" <context-param>\n"); appendElement(sb, INDENT4, "param-name", entry.getKey()); appendElement(sb, INDENT4, "param-value", entry.getValue()); sb.append(" </context-param>\n"); } sb.append('\n'); for (Map.Entry<String, FilterDef> entry : filters.entrySet()) { FilterDef filterDef = entry.getValue(); sb.append(" <filter>\n"); appendElement(sb, INDENT4, "description", filterDef.getDescription()); appendElement(sb, INDENT4, "display-name", filterDef.getDisplayName()); appendElement(sb, INDENT4, "filter-name", filterDef.getFilterName()); appendElement(sb, INDENT4, "filter-class", filterDef.getFilterClass()); appendElement(sb, INDENT4, "async-supported", filterDef.getAsyncSupported()); for (Map.Entry<String, String> param : filterDef.getParameterMap().entrySet()) { sb.append(" <init-param>\n"); appendElement(sb, INDENT6, "param-name", param.getKey()); appendElement(sb, INDENT6, "param-value", param.getValue()); sb.append(" </init-param>\n"); } sb.append(" </filter>\n"); } sb.append('\n'); for (FilterMap filterMap : filterMaps) { sb.append(" <filter-mapping>\n"); appendElement(sb, INDENT4, "filter-name", filterMap.getFilterName()); if (filterMap.getMatchAllServletNames()) { sb.append(" <servlet-name>*</servlet-name>\n"); } else { for (String servletName : filterMap.getServletNames()) { appendElement(sb, INDENT4, "servlet-name", servletName); } } if (filterMap.getMatchAllUrlPatterns()) { sb.append(" <url-pattern>*</url-pattern>\n"); } else { for (String urlPattern : filterMap.getURLPatterns()) { appendElement(sb, INDENT4, "url-pattern", urlPattern); } } for (String dispatcher : filterMap.getDispatcherNames()) { appendElement(sb, INDENT4, "dispatcher", dispatcher); } sb.append(" </filter-mapping>\n"); } sb.append('\n'); for (String listener : listeners) { sb.append(" <listener>\n"); appendElement(sb, INDENT4, "listener-class", listener); sb.append(" </listener>\n"); } sb.append('\n'); for (Map.Entry<String, ServletDef> entry : servlets.entrySet()) { ServletDef servletDef = entry.getValue(); sb.append(" <servlet>\n"); appendElement(sb, INDENT4, "description", servletDef.getDescription()); appendElement(sb, INDENT4, "display-name", servletDef.getDisplayName()); appendElement(sb, INDENT4, "servlet-name", entry.getKey()); appendElement(sb, INDENT4, "servlet-class", servletDef.getServletClass()); appendElement(sb, INDENT4, "jsp-file", servletDef.getJspFile()); for (Map.Entry<String, String> param : servletDef.getParameterMap().entrySet()) { sb.append(" <init-param>\n"); appendElement(sb, INDENT6, "param-name", param.getKey()); appendElement(sb, INDENT6, "param-value", param.getValue()); sb.append(" </init-param>\n"); } appendElement(sb, INDENT4, "load-on-startup", servletDef.getLoadOnStartup()); appendElement(sb, INDENT4, "enabled", servletDef.getEnabled()); appendElement(sb, INDENT4, "async-supported", servletDef.getAsyncSupported()); if (servletDef.getRunAs() != null) { sb.append(" <run-as>\n"); appendElement(sb, INDENT6, "role-name", servletDef.getRunAs()); sb.append(" </run-as>\n"); } for (SecurityRoleRef roleRef : servletDef.getSecurityRoleRefs()) { sb.append(" <security-role-ref>\n"); appendElement(sb, INDENT6, "role-name", roleRef.getName()); appendElement(sb, INDENT6, "role-link", roleRef.getLink()); sb.append(" </security-role-ref>\n"); } MultipartDef multipartDef = servletDef.getMultipartDef(); if (multipartDef != null) { sb.append(" <multipart-config>\n"); appendElement(sb, INDENT6, "location", multipartDef.getLocation()); appendElement(sb, INDENT6, "max-file-size", multipartDef.getMaxFileSize()); appendElement(sb, INDENT6, "max-request-size", multipartDef.getMaxRequestSize()); appendElement(sb, INDENT6, "file-size-threshold", multipartDef.getFileSizeThreshold()); sb.append(" </multipart-config>\n"); } sb.append(" </servlet>\n"); } sb.append('\n'); for (Map.Entry<String, String> entry : servletMappings.entrySet()) { sb.append(" <servlet-mapping>\n"); appendElement(sb, INDENT4, "servlet-name", entry.getValue()); appendElement(sb, INDENT4, "url-pattern", entry.getKey()); sb.append(" </servlet-mapping>\n"); } sb.append('\n'); if (sessionConfig != null) { sb.append(" <session-config>\n"); appendElement(sb, INDENT4, "session-timeout", sessionConfig.getSessionTimeout()); sb.append(" <cookie-config>\n"); appendElement(sb, INDENT6, "name", sessionConfig.getCookieName()); appendElement(sb, INDENT6, "domain", sessionConfig.getCookieDomain()); appendElement(sb, INDENT6, "path", sessionConfig.getCookiePath()); appendElement(sb, INDENT6, "comment", sessionConfig.getCookieComment()); appendElement(sb, INDENT6, "http-only", sessionConfig.getCookieHttpOnly()); appendElement(sb, INDENT6, "secure", sessionConfig.getCookieSecure()); appendElement(sb, INDENT6, "max-age", sessionConfig.getCookieMaxAge()); sb.append(" </cookie-config>\n"); for (SessionTrackingMode stm : sessionConfig.getSessionTrackingModes()) { appendElement(sb, INDENT4, "tracking-mode", stm.name()); } sb.append(" </session-config>\n\n"); } for (Map.Entry<String, String> entry : mimeMappings.entrySet()) { sb.append(" <mime-mapping>\n"); appendElement(sb, INDENT4, "extension", entry.getKey()); appendElement(sb, INDENT4, "mime-type", entry.getValue()); sb.append(" </mime-mapping>\n"); } sb.append('\n'); if (welcomeFiles.size() > 0) { sb.append(" <welcome-file-list>\n"); for (String welcomeFile : welcomeFiles) { appendElement(sb, INDENT4, "welcome-file", welcomeFile); } sb.append(" </welcome-file-list>\n\n"); } for (ErrorPage errorPage : errorPages.values()) { sb.append(" <error-page>\n"); if (errorPage.getExceptionType() == null) { appendElement(sb, INDENT4, "error-code", Integer.toString(errorPage.getErrorCode())); } else { appendElement(sb, INDENT4, "exception-type", errorPage.getExceptionType()); } appendElement(sb, INDENT4, "location", errorPage.getLocation()); sb.append(" </error-page>\n"); } sb.append('\n'); if (taglibs.size() > 0 || jspPropertyGroups.size() > 0) { sb.append(" <jsp-config>\n"); for (Map.Entry<String, String> entry : taglibs.entrySet()) { sb.append(" <taglib>\n"); appendElement(sb, INDENT6, "taglib-uri", entry.getKey()); appendElement(sb, INDENT6, "taglib-location", entry.getValue()); sb.append(" </taglib>\n"); } for (JspPropertyGroup jpg : jspPropertyGroups) { sb.append(" <jsp-property-group>\n"); for (String urlPattern : jpg.getUrlPatterns()) { appendElement(sb, INDENT6, "url-pattern", urlPattern); } appendElement(sb, INDENT6, "el-ignored", jpg.getElIgnored()); appendElement(sb, INDENT6, "page-encoding", jpg.getPageEncoding()); appendElement(sb, INDENT6, "scripting-invalid", jpg.getScriptingInvalid()); appendElement(sb, INDENT6, "is-xml", jpg.getIsXml()); for (String prelude : jpg.getIncludePreludes()) { appendElement(sb, INDENT6, "include-prelude", prelude); } for (String coda : jpg.getIncludeCodas()) { appendElement(sb, INDENT6, "include-coda", coda); } appendElement(sb, INDENT6, "deferred-syntax-allowed-as-literal", jpg.getDeferredSyntax()); appendElement(sb, INDENT6, "trim-directive-whitespaces", jpg.getTrimWhitespace()); appendElement(sb, INDENT6, "default-content-type", jpg.getDefaultContentType()); appendElement(sb, INDENT6, "buffer", jpg.getBuffer()); appendElement(sb, INDENT6, "error-on-undeclared-namespace", jpg.getErrorOnUndeclaredNamespace()); sb.append(" </jsp-property-group>\n"); } sb.append(" </jsp-config>\n\n"); } for (SecurityConstraint constraint : securityConstraints) { sb.append(" <security-constraint>\n"); appendElement(sb, INDENT4, "display-name", constraint.getDisplayName()); for (SecurityCollection collection : constraint.findCollections()) { sb.append(" <web-resource-collection>\n"); appendElement(sb, INDENT6, "web-resource-name", collection.getName()); appendElement(sb, INDENT6, "description", collection.getDescription()); for (String urlPattern : collection.findPatterns()) { appendElement(sb, INDENT6, "url-pattern", urlPattern); } for (String method : collection.findMethods()) { appendElement(sb, INDENT6, "http-method", method); } for (String method : collection.findOmittedMethods()) { appendElement(sb, INDENT6, "http-method-omission", method); } sb.append(" </web-resource-collection>\n"); } if (constraint.findAuthRoles().length > 0) { sb.append(" <auth-constraint>\n"); for (String role : constraint.findAuthRoles()) { appendElement(sb, INDENT6, "role-name", role); } sb.append(" </auth-constraint>\n"); } if (constraint.getUserConstraint() != null) { sb.append(" <user-data-constraint>\n"); appendElement(sb, INDENT6, "transport-guarantee", constraint.getUserConstraint()); sb.append(" </user-data-constraint>\n"); } sb.append(" </security-constraint>\n"); } sb.append('\n'); if (loginConfig != null) { sb.append(" <login-config>\n"); appendElement(sb, INDENT4, "auth-method", loginConfig.getAuthMethod()); appendElement(sb,INDENT4, "realm-name", loginConfig.getRealmName()); if (loginConfig.getErrorPage() != null || loginConfig.getLoginPage() != null) { sb.append(" <form-login-config>\n"); appendElement(sb, INDENT6, "form-login-page", loginConfig.getLoginPage()); appendElement(sb, INDENT6, "form-error-page", loginConfig.getErrorPage()); sb.append(" </form-login-config>\n"); } sb.append(" </login-config>\n\n"); } for (String roleName : securityRoles) { sb.append(" <security-role>\n"); appendElement(sb, INDENT4, "role-name", roleName); sb.append(" </security-role>\n"); } for (ContextEnvironment envEntry : envEntries.values()) { sb.append(" <env-entry>\n"); appendElement(sb, INDENT4, "description", envEntry.getDescription()); appendElement(sb, INDENT4, "env-entry-name", envEntry.getName()); appendElement(sb, INDENT4, "env-entry-type", envEntry.getType()); appendElement(sb, INDENT4, "env-entry-value", envEntry.getValue()); // TODO mapped-name for (InjectionTarget target : envEntry.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </env-entry>\n"); } sb.append('\n'); for (ContextEjb ejbRef : ejbRefs.values()) { sb.append(" <ejb-ref>\n"); appendElement(sb, INDENT4, "description", ejbRef.getDescription()); appendElement(sb, INDENT4, "ejb-ref-name", ejbRef.getName()); appendElement(sb, INDENT4, "ejb-ref-type", ejbRef.getType()); appendElement(sb, INDENT4, "home", ejbRef.getHome()); appendElement(sb, INDENT4, "remote", ejbRef.getRemote()); appendElement(sb, INDENT4, "ejb-link", ejbRef.getLink()); // TODO mapped-name for (InjectionTarget target : ejbRef.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </ejb-ref>\n"); } sb.append('\n'); for (ContextLocalEjb ejbLocalRef : ejbLocalRefs.values()) { sb.append(" <ejb-local-ref>\n"); appendElement(sb, INDENT4, "description", ejbLocalRef.getDescription()); appendElement(sb, INDENT4, "ejb-ref-name", ejbLocalRef.getName()); appendElement(sb, INDENT4, "ejb-ref-type", ejbLocalRef.getType()); appendElement(sb, INDENT4, "local-home", ejbLocalRef.getHome()); appendElement(sb, INDENT4, "local", ejbLocalRef.getLocal()); appendElement(sb, INDENT4, "ejb-link", ejbLocalRef.getLink()); // TODO mapped-name for (InjectionTarget target : ejbLocalRef.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </ejb-local-ref>\n"); } sb.append('\n'); for (ContextService serviceRef : serviceRefs.values()) { sb.append(" <service-ref>\n"); appendElement(sb, INDENT4, "description", serviceRef.getDescription()); appendElement(sb, INDENT4, "display-name", serviceRef.getDisplayname()); appendElement(sb, INDENT4, "service-ref-name", serviceRef.getName()); appendElement(sb, INDENT4, "service-interface", serviceRef.getInterface()); appendElement(sb, INDENT4, "service-ref-type", serviceRef.getType()); appendElement(sb, INDENT4, "wsdl-file", serviceRef.getWsdlfile()); appendElement(sb, INDENT4, "jaxrpc-mapping-file", serviceRef.getJaxrpcmappingfile()); String qname = serviceRef.getServiceqnameNamespaceURI(); if (qname != null) { qname = qname + ":"; } qname = qname + serviceRef.getServiceqnameLocalpart(); appendElement(sb, INDENT4, "service-qname", qname); Iterator<String> endpointIter = serviceRef.getServiceendpoints(); while (endpointIter.hasNext()) { String endpoint = endpointIter.next(); sb.append(" <port-component-ref>\n"); appendElement(sb, INDENT6, "service-endpoint-interface", endpoint); appendElement(sb, INDENT6, "port-component-link", serviceRef.getProperty(endpoint)); sb.append(" </port-component-ref>\n"); } Iterator<String> handlerIter = serviceRef.getHandlers(); while (handlerIter.hasNext()) { String handler = handlerIter.next(); sb.append(" <handler>\n"); ContextHandler ch = serviceRef.getHandler(handler); appendElement(sb, INDENT6, "handler-name", ch.getName()); appendElement(sb, INDENT6, "handler-class", ch.getHandlerclass()); sb.append(" </handler>\n"); } // TODO handler-chains // TODO mapped-name for (InjectionTarget target : serviceRef.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </service-ref>\n"); } sb.append('\n'); for (ContextResource resourceRef : resourceRefs.values()) { sb.append(" <resource-ref>\n"); appendElement(sb, INDENT4, "description", resourceRef.getDescription()); appendElement(sb, INDENT4, "res-ref-name", resourceRef.getName()); appendElement(sb, INDENT4, "res-type", resourceRef.getType()); appendElement(sb, INDENT4, "res-auth", resourceRef.getAuth()); appendElement(sb, INDENT4, "res-sharing-scope", resourceRef.getScope()); // TODO mapped-name for (InjectionTarget target : resourceRef.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </resource-ref>\n"); } sb.append('\n'); for (ContextResourceEnvRef resourceEnvRef : resourceEnvRefs.values()) { sb.append(" <resource-env-ref>\n"); appendElement(sb, INDENT4, "description", resourceEnvRef.getDescription()); appendElement(sb, INDENT4, "resource-env-ref-name", resourceEnvRef.getName()); appendElement(sb, INDENT4, "resource-env-ref-type", resourceEnvRef.getType()); // TODO mapped-name for (InjectionTarget target : resourceEnvRef.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </resource-env-ref>\n"); } sb.append('\n'); if (!postConstructMethods.isEmpty()) { for (Entry<String, String> entry : postConstructMethods .entrySet()) { sb.append(" <post-construct>\n"); appendElement(sb, INDENT4, "lifecycle-callback-class", entry.getKey()); appendElement(sb, INDENT4, "lifecycle-callback-method", entry.getValue()); sb.append(" </post-construct>\n"); } sb.append('\n'); } if (!preDestroyMethods.isEmpty()) { for (Entry<String, String> entry : preDestroyMethods .entrySet()) { sb.append(" <pre-destroy>\n"); appendElement(sb, INDENT4, "lifecycle-callback-class", entry.getKey()); appendElement(sb, INDENT4, "lifecycle-callback-method", entry.getValue()); sb.append(" </pre-destroy>\n"); } sb.append('\n'); } for (MessageDestinationRef mdr : messageDestinationRefs.values()) { sb.append(" <message-destination-ref>\n"); appendElement(sb, INDENT4, "description", mdr.getDescription()); appendElement(sb, INDENT4, "message-destination-ref-name", mdr.getName()); appendElement(sb, INDENT4, "message-destination-type", mdr.getType()); appendElement(sb, INDENT4, "message-destination-usage", mdr.getUsage()); appendElement(sb, INDENT4, "message-destination-link", mdr.getLink()); // TODO mapped-name for (InjectionTarget target : mdr.getInjectionTargets()) { sb.append(" <injection-target>\n"); appendElement(sb, INDENT6, "injection-target-class", target.getTargetClass()); appendElement(sb, INDENT6, "injection-target-name", target.getTargetName()); sb.append(" </injection-target>\n"); } // TODO lookup-name sb.append(" </message-destination-ref>\n"); } sb.append('\n'); for (MessageDestination md : messageDestinations.values()) { sb.append(" <message-destination>\n"); appendElement(sb, INDENT4, "description", md.getDescription()); appendElement(sb, INDENT4, "display-name", md.getDisplayName()); appendElement(sb, INDENT4, "message-destination-name", md.getName()); // TODO mapped-name sb.append(" </message-destination>\n"); } sb.append('\n'); if (localeEncodingMappings.size() > 0) { sb.append(" <locale-encoding-mapping-list>\n"); for (Map.Entry<String, String> entry : localeEncodingMappings.entrySet()) { sb.append(" <locale-encoding-mapping>\n"); appendElement(sb, INDENT6, "locale", entry.getKey()); appendElement(sb, INDENT6, "encoding", entry.getValue()); sb.append(" </locale-encoding-mapping>\n"); } sb.append(" </locale-encoding-mapping-list>\n"); } sb.append("</web-app>"); return sb.toString(); } private static void appendElement(StringBuilder sb, String indent, String elementName, String value) { if (value == null || value.length() == 0) return; sb.append(indent); sb.append('<'); sb.append(elementName); sb.append('>'); sb.append(escapeXml(value)); sb.append("</"); sb.append(elementName); sb.append(">\n"); } private static void appendElement(StringBuilder sb, String indent, String elementName, Object value) { if (value == null) return; appendElement(sb, indent, elementName, value.toString()); } /** * Escape the 5 entities defined by XML. */ private static String escapeXml(String s) { if (s == null) return null; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '<') { sb.append("&lt;"); } else if (c == '>') { sb.append("&gt;"); } else if (c == '\'') { sb.append("&apos;"); } else if (c == '&') { sb.append("&amp;"); } else if (c == '"') { sb.append("&quot;"); } else { sb.append(c); } } return sb.toString(); } /** * Merge the supplied web fragments into this main web.xml. * * @param fragments The fragments to merge in * @return <code>true</code> if merge is successful, else * <code>false</code> */ public boolean merge(Set<WebXml> fragments) { // As far as possible, process in alphabetical order so it is easy to // check everything is present // Merge rules vary from element to element. See SRV.8.2.3 WebXml temp = new WebXml(); for (WebXml fragment : fragments) { if (!mergeMap(fragment.getContextParams(), contextParams, temp.getContextParams(), fragment, "Context Parameter")) { return false; } } contextParams.putAll(temp.getContextParams()); if (displayName == null) { for (WebXml fragment : fragments) { String value = fragment.getDisplayName(); if (value != null) { if (temp.getDisplayName() == null) { temp.setDisplayName(value); } else { log.error(sm.getString( "webXml.mergeConflictDisplayName", fragment.getName(), fragment.getURL())); return false; } } } displayName = temp.getDisplayName(); } // Note: Not permitted in fragments but we also use fragments for // per-Host and global defaults so it may appear there if (!denyUncoveredHttpMethods) { for (WebXml fragment : fragments) { if (fragment.getDenyUncoveredHttpMethods()) { denyUncoveredHttpMethods = true; break; } } } if (distributable) { for (WebXml fragment : fragments) { if (!fragment.isDistributable()) { distributable = false; break; } } } for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getEjbLocalRefs(), ejbLocalRefs, temp.getEjbLocalRefs(), fragment)) { return false; } } ejbLocalRefs.putAll(temp.getEjbLocalRefs()); for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getEjbRefs(), ejbRefs, temp.getEjbRefs(), fragment)) { return false; } } ejbRefs.putAll(temp.getEjbRefs()); for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getEnvEntries(), envEntries, temp.getEnvEntries(), fragment)) { return false; } } envEntries.putAll(temp.getEnvEntries()); for (WebXml fragment : fragments) { if (!mergeMap(fragment.getErrorPages(), errorPages, temp.getErrorPages(), fragment, "Error Page")) { return false; } } errorPages.putAll(temp.getErrorPages()); // As per 'clarification' from the Servlet EG, filter definitions in the // main web.xml override those in fragments and those in fragments // override those in annotations List<FilterMap> filterMapsToAdd = new ArrayList<>(); for (WebXml fragment : fragments) { for (FilterMap filterMap : fragment.getFilterMappings()) { if (!filterMappingNames.contains(filterMap.getFilterName())) { filterMapsToAdd.add(filterMap); } } } for (FilterMap filterMap : filterMapsToAdd) { // Additive addFilterMapping(filterMap); } for (WebXml fragment : fragments) { for (Map.Entry<String,FilterDef> entry : fragment.getFilters().entrySet()) { if (filters.containsKey(entry.getKey())) { mergeFilter(entry.getValue(), filters.get(entry.getKey()), false); } else { if (temp.getFilters().containsKey(entry.getKey())) { if (!(mergeFilter(entry.getValue(), temp.getFilters().get(entry.getKey()), true))) { log.error(sm.getString( "webXml.mergeConflictFilter", entry.getKey(), fragment.getName(), fragment.getURL())); return false; } } else { temp.getFilters().put(entry.getKey(), entry.getValue()); } } } } filters.putAll(temp.getFilters()); for (WebXml fragment : fragments) { for (JspPropertyGroup jspPropertyGroup : fragment.getJspPropertyGroups()) { // Always additive addJspPropertyGroup(jspPropertyGroup); } } for (WebXml fragment : fragments) { for (String listener : fragment.getListeners()) { // Always additive addListener(listener); } } for (WebXml fragment : fragments) { if (!mergeMap(fragment.getLocaleEncodingMappings(), localeEncodingMappings, temp.getLocaleEncodingMappings(), fragment, "Locale Encoding Mapping")) { return false; } } localeEncodingMappings.putAll(temp.getLocaleEncodingMappings()); if (getLoginConfig() == null) { LoginConfig tempLoginConfig = null; for (WebXml fragment : fragments) { LoginConfig fragmentLoginConfig = fragment.loginConfig; if (fragmentLoginConfig != null) { if (tempLoginConfig == null || fragmentLoginConfig.equals(tempLoginConfig)) { tempLoginConfig = fragmentLoginConfig; } else { log.error(sm.getString( "webXml.mergeConflictLoginConfig", fragment.getName(), fragment.getURL())); } } } loginConfig = tempLoginConfig; } for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getMessageDestinationRefs(), messageDestinationRefs, temp.getMessageDestinationRefs(), fragment)) { return false; } } messageDestinationRefs.putAll(temp.getMessageDestinationRefs()); for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getMessageDestinations(), messageDestinations, temp.getMessageDestinations(), fragment)) { return false; } } messageDestinations.putAll(temp.getMessageDestinations()); for (WebXml fragment : fragments) { if (!mergeMap(fragment.getMimeMappings(), mimeMappings, temp.getMimeMappings(), fragment, "Mime Mapping")) { return false; } } mimeMappings.putAll(temp.getMimeMappings()); for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getResourceEnvRefs(), resourceEnvRefs, temp.getResourceEnvRefs(), fragment)) { return false; } } resourceEnvRefs.putAll(temp.getResourceEnvRefs()); for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getResourceRefs(), resourceRefs, temp.getResourceRefs(), fragment)) { return false; } } resourceRefs.putAll(temp.getResourceRefs()); for (WebXml fragment : fragments) { for (SecurityConstraint constraint : fragment.getSecurityConstraints()) { // Always additive addSecurityConstraint(constraint); } } for (WebXml fragment : fragments) { for (String role : fragment.getSecurityRoles()) { // Always additive addSecurityRole(role); } } for (WebXml fragment : fragments) { if (!mergeResourceMap(fragment.getServiceRefs(), serviceRefs, temp.getServiceRefs(), fragment)) { return false; } } serviceRefs.putAll(temp.getServiceRefs()); // As per 'clarification' from the Servlet EG, servlet definitions and // mappings in the main web.xml override those in fragments and those in // fragments override those in annotations // Skip servlet definitions and mappings from fragments that are // defined in web.xml List<Map.Entry<String,String>> servletMappingsToAdd = new ArrayList<>(); for (WebXml fragment : fragments) { for (Map.Entry<String,String> servletMap : fragment.getServletMappings().entrySet()) { if (!servletMappingNames.contains(servletMap.getValue()) && !servletMappings.containsKey(servletMap.getKey())) { servletMappingsToAdd.add(servletMap); } } } // Add fragment mappings for (Map.Entry<String,String> mapping : servletMappingsToAdd) { addServletMapping(mapping.getKey(), mapping.getValue()); } for (WebXml fragment : fragments) { for (Map.Entry<String,ServletDef> entry : fragment.getServlets().entrySet()) { if (servlets.containsKey(entry.getKey())) { mergeServlet(entry.getValue(), servlets.get(entry.getKey()), false); } else { if (temp.getServlets().containsKey(entry.getKey())) { if (!(mergeServlet(entry.getValue(), temp.getServlets().get(entry.getKey()), true))) { log.error(sm.getString( "webXml.mergeConflictServlet", entry.getKey(), fragment.getName(), fragment.getURL())); return false; } } else { temp.getServlets().put(entry.getKey(), entry.getValue()); } } } } servlets.putAll(temp.getServlets()); if (sessionConfig.getSessionTimeout() == null) { for (WebXml fragment : fragments) { Integer value = fragment.getSessionConfig().getSessionTimeout(); if (value != null) { if (temp.getSessionConfig().getSessionTimeout() == null) { temp.getSessionConfig().setSessionTimeout(value.toString()); } else if (value.equals( temp.getSessionConfig().getSessionTimeout())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionTimeout", fragment.getName(), fragment.getURL())); return false; } } } if (temp.getSessionConfig().getSessionTimeout() != null) { sessionConfig.setSessionTimeout( temp.getSessionConfig().getSessionTimeout().toString()); } } if (sessionConfig.getCookieName() == null) { for (WebXml fragment : fragments) { String value = fragment.getSessionConfig().getCookieName(); if (value != null) { if (temp.getSessionConfig().getCookieName() == null) { temp.getSessionConfig().setCookieName(value); } else if (value.equals( temp.getSessionConfig().getCookieName())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookieName", fragment.getName(), fragment.getURL())); return false; } } } sessionConfig.setCookieName( temp.getSessionConfig().getCookieName()); } if (sessionConfig.getCookieDomain() == null) { for (WebXml fragment : fragments) { String value = fragment.getSessionConfig().getCookieDomain(); if (value != null) { if (temp.getSessionConfig().getCookieDomain() == null) { temp.getSessionConfig().setCookieDomain(value); } else if (value.equals( temp.getSessionConfig().getCookieDomain())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookieDomain", fragment.getName(), fragment.getURL())); return false; } } } sessionConfig.setCookieDomain( temp.getSessionConfig().getCookieDomain()); } if (sessionConfig.getCookiePath() == null) { for (WebXml fragment : fragments) { String value = fragment.getSessionConfig().getCookiePath(); if (value != null) { if (temp.getSessionConfig().getCookiePath() == null) { temp.getSessionConfig().setCookiePath(value); } else if (value.equals( temp.getSessionConfig().getCookiePath())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookiePath", fragment.getName(), fragment.getURL())); return false; } } } sessionConfig.setCookiePath( temp.getSessionConfig().getCookiePath()); } if (sessionConfig.getCookieComment() == null) { for (WebXml fragment : fragments) { String value = fragment.getSessionConfig().getCookieComment(); if (value != null) { if (temp.getSessionConfig().getCookieComment() == null) { temp.getSessionConfig().setCookieComment(value); } else if (value.equals( temp.getSessionConfig().getCookieComment())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookieComment", fragment.getName(), fragment.getURL())); return false; } } } sessionConfig.setCookieComment( temp.getSessionConfig().getCookieComment()); } if (sessionConfig.getCookieHttpOnly() == null) { for (WebXml fragment : fragments) { Boolean value = fragment.getSessionConfig().getCookieHttpOnly(); if (value != null) { if (temp.getSessionConfig().getCookieHttpOnly() == null) { temp.getSessionConfig().setCookieHttpOnly(value.toString()); } else if (value.equals( temp.getSessionConfig().getCookieHttpOnly())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookieHttpOnly", fragment.getName(), fragment.getURL())); return false; } } } if (temp.getSessionConfig().getCookieHttpOnly() != null) { sessionConfig.setCookieHttpOnly( temp.getSessionConfig().getCookieHttpOnly().toString()); } } if (sessionConfig.getCookieSecure() == null) { for (WebXml fragment : fragments) { Boolean value = fragment.getSessionConfig().getCookieSecure(); if (value != null) { if (temp.getSessionConfig().getCookieSecure() == null) { temp.getSessionConfig().setCookieSecure(value.toString()); } else if (value.equals( temp.getSessionConfig().getCookieSecure())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookieSecure", fragment.getName(), fragment.getURL())); return false; } } } if (temp.getSessionConfig().getCookieSecure() != null) { sessionConfig.setCookieSecure( temp.getSessionConfig().getCookieSecure().toString()); } } if (sessionConfig.getCookieMaxAge() == null) { for (WebXml fragment : fragments) { Integer value = fragment.getSessionConfig().getCookieMaxAge(); if (value != null) { if (temp.getSessionConfig().getCookieMaxAge() == null) { temp.getSessionConfig().setCookieMaxAge(value.toString()); } else if (value.equals( temp.getSessionConfig().getCookieMaxAge())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionCookieMaxAge", fragment.getName(), fragment.getURL())); return false; } } } if (temp.getSessionConfig().getCookieMaxAge() != null) { sessionConfig.setCookieMaxAge( temp.getSessionConfig().getCookieMaxAge().toString()); } } if (sessionConfig.getSessionTrackingModes().size() == 0) { for (WebXml fragment : fragments) { EnumSet<SessionTrackingMode> value = fragment.getSessionConfig().getSessionTrackingModes(); if (value.size() > 0) { if (temp.getSessionConfig().getSessionTrackingModes().size() == 0) { temp.getSessionConfig().getSessionTrackingModes().addAll(value); } else if (value.equals( temp.getSessionConfig().getSessionTrackingModes())) { // Fragments use same value - no conflict } else { log.error(sm.getString( "webXml.mergeConflictSessionTrackingMode", fragment.getName(), fragment.getURL())); return false; } } } sessionConfig.getSessionTrackingModes().addAll( temp.getSessionConfig().getSessionTrackingModes()); } for (WebXml fragment : fragments) { if (!mergeMap(fragment.getTaglibs(), taglibs, temp.getTaglibs(), fragment, "Taglibs")) { return false; } } taglibs.putAll(temp.getTaglibs()); for (WebXml fragment : fragments) { if (fragment.alwaysAddWelcomeFiles || welcomeFiles.size() == 0) { for (String welcomeFile : fragment.getWelcomeFiles()) { addWelcomeFile(welcomeFile); } } } if (postConstructMethods.isEmpty()) { for (WebXml fragment : fragments) { if (!mergeLifecycleCallback(fragment.getPostConstructMethods(), temp.getPostConstructMethods(), fragment, "Post Construct Methods")) { return false; } } postConstructMethods.putAll(temp.getPostConstructMethods()); } if (preDestroyMethods.isEmpty()) { for (WebXml fragment : fragments) { if (!mergeLifecycleCallback(fragment.getPreDestroyMethods(), temp.getPreDestroyMethods(), fragment, "Pre Destroy Methods")) { return false; } } preDestroyMethods.putAll(temp.getPreDestroyMethods()); } return true; } private static <T extends ResourceBase> boolean mergeResourceMap( Map<String, T> fragmentResources, Map<String, T> mainResources, Map<String, T> tempResources, WebXml fragment) { for (T resource : fragmentResources.values()) { String resourceName = resource.getName(); if (mainResources.containsKey(resourceName)) { mainResources.get(resourceName).getInjectionTargets().addAll( resource.getInjectionTargets()); } else { // Not defined in main web.xml T existingResource = tempResources.get(resourceName); if (existingResource != null) { if (!existingResource.equals(resource)) { log.error(sm.getString( "webXml.mergeConflictResource", resourceName, fragment.getName(), fragment.getURL())); return false; } } else { tempResources.put(resourceName, resource); } } } return true; } private static <T> boolean mergeMap(Map<String,T> fragmentMap, Map<String,T> mainMap, Map<String,T> tempMap, WebXml fragment, String mapName) { for (Entry<String, T> entry : fragmentMap.entrySet()) { final String key = entry.getKey(); if (!mainMap.containsKey(key)) { // Not defined in main web.xml T value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals( tempMap.get(key))) { log.error(sm.getString( "webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } } return true; } private static boolean mergeFilter(FilterDef src, FilterDef dest, boolean failOnConflict) { if (dest.getAsyncSupported() == null) { dest.setAsyncSupported(src.getAsyncSupported()); } else if (src.getAsyncSupported() != null) { if (failOnConflict && !src.getAsyncSupported().equals(dest.getAsyncSupported())) { return false; } } if (dest.getFilterClass() == null) { dest.setFilterClass(src.getFilterClass()); } else if (src.getFilterClass() != null) { if (failOnConflict && !src.getFilterClass().equals(dest.getFilterClass())) { return false; } } for (Map.Entry<String,String> srcEntry : src.getParameterMap().entrySet()) { if (dest.getParameterMap().containsKey(srcEntry.getKey())) { if (failOnConflict && !dest.getParameterMap().get( srcEntry.getKey()).equals(srcEntry.getValue())) { return false; } } else { dest.addInitParameter(srcEntry.getKey(), srcEntry.getValue()); } } return true; } private static boolean mergeServlet(ServletDef src, ServletDef dest, boolean failOnConflict) { // These tests should be unnecessary... if (dest.getServletClass() != null && dest.getJspFile() != null) { return false; } if (src.getServletClass() != null && src.getJspFile() != null) { return false; } if (dest.getServletClass() == null && dest.getJspFile() == null) { dest.setServletClass(src.getServletClass()); dest.setJspFile(src.getJspFile()); } else if (failOnConflict) { if (src.getServletClass() != null && (dest.getJspFile() != null || !src.getServletClass().equals(dest.getServletClass()))) { return false; } if (src.getJspFile() != null && (dest.getServletClass() != null || !src.getJspFile().equals(dest.getJspFile()))) { return false; } } // Additive for (SecurityRoleRef securityRoleRef : src.getSecurityRoleRefs()) { dest.addSecurityRoleRef(securityRoleRef); } if (dest.getLoadOnStartup() == null) { if (src.getLoadOnStartup() != null) { dest.setLoadOnStartup(src.getLoadOnStartup().toString()); } } else if (src.getLoadOnStartup() != null) { if (failOnConflict && !src.getLoadOnStartup().equals(dest.getLoadOnStartup())) { return false; } } if (dest.getEnabled() == null) { if (src.getEnabled() != null) { dest.setEnabled(src.getEnabled().toString()); } } else if (src.getEnabled() != null) { if (failOnConflict && !src.getEnabled().equals(dest.getEnabled())) { return false; } } for (Map.Entry<String,String> srcEntry : src.getParameterMap().entrySet()) { if (dest.getParameterMap().containsKey(srcEntry.getKey())) { if (failOnConflict && !dest.getParameterMap().get( srcEntry.getKey()).equals(srcEntry.getValue())) { return false; } } else { dest.addInitParameter(srcEntry.getKey(), srcEntry.getValue()); } } if (dest.getMultipartDef() == null) { dest.setMultipartDef(src.getMultipartDef()); } else if (src.getMultipartDef() != null) { return mergeMultipartDef(src.getMultipartDef(), dest.getMultipartDef(), failOnConflict); } if (dest.getAsyncSupported() == null) { if (src.getAsyncSupported() != null) { dest.setAsyncSupported(src.getAsyncSupported().toString()); } } else if (src.getAsyncSupported() != null) { if (failOnConflict && !src.getAsyncSupported().equals(dest.getAsyncSupported())) { return false; } } return true; } private static boolean mergeMultipartDef(MultipartDef src, MultipartDef dest, boolean failOnConflict) { if (dest.getLocation() == null) { dest.setLocation(src.getLocation()); } else if (src.getLocation() != null) { if (failOnConflict && !src.getLocation().equals(dest.getLocation())) { return false; } } if (dest.getFileSizeThreshold() == null) { dest.setFileSizeThreshold(src.getFileSizeThreshold()); } else if (src.getFileSizeThreshold() != null) { if (failOnConflict && !src.getFileSizeThreshold().equals( dest.getFileSizeThreshold())) { return false; } } if (dest.getMaxFileSize() == null) { dest.setMaxFileSize(src.getMaxFileSize()); } else if (src.getLocation() != null) { if (failOnConflict && !src.getMaxFileSize().equals(dest.getMaxFileSize())) { return false; } } if (dest.getMaxRequestSize() == null) { dest.setMaxRequestSize(src.getMaxRequestSize()); } else if (src.getMaxRequestSize() != null) { if (failOnConflict && !src.getMaxRequestSize().equals( dest.getMaxRequestSize())) { return false; } } return true; } private static <T> boolean mergeLifecycleCallback( Map<String, String> fragmentMap, Map<String, String> tempMap, WebXml fragment, String mapName) { for (Entry<String, String> entry : fragmentMap.entrySet()) { final String key = entry.getKey(); final String value = entry.getValue(); if (tempMap.containsKey(key)) { if (value != null && !value.equals(tempMap.get(key))) { log.error(sm.getString("webXml.mergeConflictString", mapName, key, fragment.getName(), fragment.getURL())); return false; } } else { tempMap.put(key, value); } } return true; } /** * Generates the sub-set of the web-fragment.xml files to be processed in * the order that the fragments must be processed as per the rules in the * Servlet spec. * * @param application The application web.xml file * @param fragments The map of fragment names to web fragments * @param servletContext The servlet context the fragments are associated * with * @return Ordered list of web-fragment.xml files to process */ public static Set<WebXml> orderWebFragments(WebXml application, Map<String,WebXml> fragments, ServletContext servletContext) { Set<WebXml> orderedFragments = new LinkedHashSet<>(); boolean absoluteOrdering = (application.getAbsoluteOrdering() != null); boolean orderingPresent = false; if (absoluteOrdering) { orderingPresent = true; // Only those fragments listed should be processed Set<String> requestedOrder = application.getAbsoluteOrdering(); for (String requestedName : requestedOrder) { if (WebXml.ORDER_OTHERS.equals(requestedName)) { // Add all fragments not named explicitly at this point for (Entry<String, WebXml> entry : fragments.entrySet()) { if (!requestedOrder.contains(entry.getKey())) { WebXml fragment = entry.getValue(); if (fragment != null) { orderedFragments.add(fragment); } } } } else { WebXml fragment = fragments.get(requestedName); if (fragment != null) { orderedFragments.add(fragment); } else { log.warn(sm.getString("webXml.wrongFragmentName",requestedName)); } } } } else { // Stage 1. Make all dependencies bi-directional - this makes the // next stage simpler. for (WebXml fragment : fragments.values()) { Iterator<String> before = fragment.getBeforeOrdering().iterator(); while (before.hasNext()) { orderingPresent = true; String beforeEntry = before.next(); if (!beforeEntry.equals(ORDER_OTHERS)) { WebXml beforeFragment = fragments.get(beforeEntry); if (beforeFragment == null) { before.remove(); } else { beforeFragment.addAfterOrdering(fragment.getName()); } } } Iterator<String> after = fragment.getAfterOrdering().iterator(); while (after.hasNext()) { orderingPresent = true; String afterEntry = after.next(); if (!afterEntry.equals(ORDER_OTHERS)) { WebXml afterFragment = fragments.get(afterEntry); if (afterFragment == null) { after.remove(); } else { afterFragment.addBeforeOrdering(fragment.getName()); } } } } // Stage 2. Make all fragments that are implicitly before/after // others explicitly so. This is iterative so the next // stage doesn't have to be. for (WebXml fragment : fragments.values()) { if (fragment.getBeforeOrdering().contains(ORDER_OTHERS)) { makeBeforeOthersExplicit(fragment.getAfterOrdering(), fragments); } if (fragment.getAfterOrdering().contains(ORDER_OTHERS)) { makeAfterOthersExplicit(fragment.getBeforeOrdering(), fragments); } } // Stage 3. Separate into three groups Set<WebXml> beforeSet = new HashSet<>(); Set<WebXml> othersSet = new HashSet<>(); Set<WebXml> afterSet = new HashSet<>(); for (WebXml fragment : fragments.values()) { if (fragment.getBeforeOrdering().contains(ORDER_OTHERS)) { beforeSet.add(fragment); fragment.getBeforeOrdering().remove(ORDER_OTHERS); } else if (fragment.getAfterOrdering().contains(ORDER_OTHERS)) { afterSet.add(fragment); fragment.getAfterOrdering().remove(ORDER_OTHERS); } else { othersSet.add(fragment); } } // Stage 4. Decouple the groups so the ordering requirements for // each fragment in the group only refer to other fragments // in the group. Ordering requirements outside the group // will be handled by processing the groups in order. // Note: Only after ordering requirements are considered. // This is OK because of the processing in stage 1. decoupleOtherGroups(beforeSet); decoupleOtherGroups(othersSet); decoupleOtherGroups(afterSet); // Stage 5. Order each group // Note: Only after ordering requirements are considered. // This is OK because of the processing in stage 1. orderFragments(orderedFragments, beforeSet); orderFragments(orderedFragments, othersSet); orderFragments(orderedFragments, afterSet); } // Container fragments are always included Set<WebXml> containerFragments = new LinkedHashSet<>(); // Find all the container fragments and remove any present from the // ordered list for (WebXml fragment : fragments.values()) { if (!fragment.getWebappJar()) { containerFragments.add(fragment); orderedFragments.remove(fragment); } } // Avoid NPE when unit testing if (servletContext != null) { // Publish the ordered fragments. The app does not need to know // about container fragments List<String> orderedJarFileNames = null; if (orderingPresent) { orderedJarFileNames = new ArrayList<>(); for (WebXml fragment: orderedFragments) { orderedJarFileNames.add(fragment.getJarName()); } } servletContext.setAttribute(ServletContext.ORDERED_LIBS, orderedJarFileNames); } // The remainder of the processing needs to know about container // fragments if (containerFragments.size() > 0) { Set<WebXml> result = new LinkedHashSet<>(); if (containerFragments.iterator().next().getDelegate()) { result.addAll(containerFragments); result.addAll(orderedFragments); } else { result.addAll(orderedFragments); result.addAll(containerFragments); } return result; } else { return orderedFragments; } } private static void decoupleOtherGroups(Set<WebXml> group) { Set<String> names = new HashSet<>(); for (WebXml fragment : group) { names.add(fragment.getName()); } for (WebXml fragment : group) { Iterator<String> after = fragment.getAfterOrdering().iterator(); while (after.hasNext()) { String entry = after.next(); if (!names.contains(entry)) { after.remove(); } } } } private static void orderFragments(Set<WebXml> orderedFragments, Set<WebXml> unordered) { Set<WebXml> addedThisRound = new HashSet<>(); Set<WebXml> addedLastRound = new HashSet<>(); while (unordered.size() > 0) { Iterator<WebXml> source = unordered.iterator(); while (source.hasNext()) { WebXml fragment = source.next(); for (WebXml toRemove : addedLastRound) { fragment.getAfterOrdering().remove(toRemove.getName()); } if (fragment.getAfterOrdering().isEmpty()) { addedThisRound.add(fragment); orderedFragments.add(fragment); source.remove(); } } if (addedThisRound.size() == 0) { // Circular throw new IllegalArgumentException( sm.getString("webXml.mergeConflictOrder")); } addedLastRound.clear(); addedLastRound.addAll(addedThisRound); addedThisRound.clear(); } } private static void makeBeforeOthersExplicit(Set<String> beforeOrdering, Map<String, WebXml> fragments) { for (String before : beforeOrdering) { if (!before.equals(ORDER_OTHERS)) { WebXml webXml = fragments.get(before); if (!webXml.getBeforeOrdering().contains(ORDER_OTHERS)) { webXml.addBeforeOrderingOthers(); makeBeforeOthersExplicit(webXml.getAfterOrdering(), fragments); } } } } private static void makeAfterOthersExplicit(Set<String> afterOrdering, Map<String, WebXml> fragments) { for (String after : afterOrdering) { if (!after.equals(ORDER_OTHERS)) { WebXml webXml = fragments.get(after); if (!webXml.getAfterOrdering().contains(ORDER_OTHERS)) { webXml.addAfterOrderingOthers(); makeAfterOthersExplicit(webXml.getBeforeOrdering(), fragments); } } } } }
55,218
Bug 55218 Upgrade Digester to be based on DefaultHandler2 and use LexicalHandler to detect publicId
Digester uses SAX2 features but is still based the SAX1 DefaultHandler. By upgrading to DefaultHandler2 it would be able to handle baseURIs when resolving entities and would have a default implementation of a LexicalHandler. Using LexicalHandler would allow it to respond directly to the startDTD event that reports the DOCTYPE (if present) so that it would not need to infer that from the first attempt to resolve an entity.
closed fixed
aa7896b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T10:07:23Z
2013-07-09T11:40:00Z
java/org/apache/tomcat/util/digester/Digester.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.digester; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; import java.util.EmptyStackException; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.xml.sax.Attributes; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXNotRecognizedException; import org.xml.sax.SAXNotSupportedException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; /** * <p>A <strong>Digester</strong> processes an XML input stream by matching a * series of element nesting patterns to execute Rules that have been added * prior to the start of parsing. This package was inspired by the * <code>XmlMapper</code> class that was part of Tomcat 3.0 and 3.1, * but is organized somewhat differently.</p> * * <p>See the <a href="package-summary.html#package_description">Digester * Developer Guide</a> for more information.</p> * * <p><strong>IMPLEMENTATION NOTE</strong> - A single Digester instance may * only be used within the context of a single thread at a time, and a call * to <code>parse()</code> must be completed before another can be initiated * even from the same thread.</p> * * <p><strong>IMPLEMENTATION NOTE</strong> - A bug in Xerces 2.0.2 prevents * the support of XML schema. You need Xerces 2.1/2.3 and up to make * this class working with XML schema</p> */ public class Digester extends DefaultHandler { // ---------------------------------------------------------- Static Fields private static class SystemPropertySource implements IntrospectionUtils.PropertySource { @Override public String getProperty( String key ) { return System.getProperty(key); } } protected static IntrospectionUtils.PropertySource source[] = new IntrospectionUtils.PropertySource[] { new SystemPropertySource() }; static { String className = System.getProperty("org.apache.tomcat.util.digester.PROPERTY_SOURCE"); if (className!=null) { IntrospectionUtils.PropertySource[] sources = new IntrospectionUtils.PropertySource[2]; sources[1] = source[0]; ClassLoader[] cls = new ClassLoader[] {Digester.class.getClassLoader(),Thread.currentThread().getContextClassLoader()}; boolean initialized = false; for (int i=0; i<cls.length && (!initialized); i++) { try { Class<?> clazz = Class.forName(className,true,cls[i]); IntrospectionUtils.PropertySource src = (IntrospectionUtils.PropertySource)clazz.newInstance(); sources[0] = src; initialized = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); LogFactory.getLog("org.apache.tomcat.util.digester.Digester"). error("Unable to load property source["+className+"].",t); } } if (initialized) source = sources; } } // --------------------------------------------------- Instance Variables /** * The body text of the current element. */ protected StringBuilder bodyText = new StringBuilder(); /** * The stack of body text string buffers for surrounding elements. */ protected ArrayStack<StringBuilder> bodyTexts = new ArrayStack<>(); /** * Stack whose elements are List objects, each containing a list of * Rule objects as returned from Rules.getMatch(). As each xml element * in the input is entered, the matching rules are pushed onto this * stack. After the end tag is reached, the matches are popped again. * The depth of is stack is therefore exactly the same as the current * "nesting" level of the input xml. * * @since 1.6 */ protected ArrayStack<List<Rule>> matches = new ArrayStack<>(10); /** * The class loader to use for instantiating application objects. * If not specified, the context class loader, or the class loader * used to load Digester itself, is used, based on the value of the * <code>useContextClassLoader</code> variable. */ protected ClassLoader classLoader = null; /** * Has this Digester been configured yet. */ protected boolean configured = false; /** * The EntityResolver used by the SAX parser. By default it use this class */ protected EntityResolver entityResolver; /** * The URLs of entityValidator that have been registered, keyed by the public * identifier that corresponds. */ protected HashMap<String,String> entityValidator = new HashMap<>(); /** * The application-supplied error handler that is notified when parsing * warnings, errors, or fatal errors occur. */ protected ErrorHandler errorHandler = null; /** * The SAXParserFactory that is created the first time we need it. */ protected SAXParserFactory factory = null; /** * The Locator associated with our parser. */ protected Locator locator = null; /** * The current match pattern for nested element processing. */ protected String match = ""; /** * Do we want a "namespace aware" parser. */ protected boolean namespaceAware = false; /** * Registered namespaces we are currently processing. The key is the * namespace prefix that was declared in the document. The value is an * ArrayStack of the namespace URIs this prefix has been mapped to -- * the top Stack element is the most current one. (This architecture * is required because documents can declare nested uses of the same * prefix for different Namespace URIs). */ protected HashMap<String,ArrayStack<String>> namespaces = new HashMap<>(); /** * The parameters stack being utilized by CallMethodRule and * CallParamRule rules. */ protected ArrayStack<Object> params = new ArrayStack<>(); /** * The SAXParser we will use to parse the input stream. */ protected SAXParser parser = null; /** * The public identifier of the DTD we are currently parsing under * (if any). */ protected String publicId = null; /** * The XMLReader used to parse digester rules. */ protected XMLReader reader = null; /** * The "root" element of the stack (in other words, the last object * that was popped. */ protected Object root = null; /** * The <code>Rules</code> implementation containing our collection of * <code>Rule</code> instances and associated matching policy. If not * established before the first rule is added, a default implementation * will be provided. */ protected Rules rules = null; /** * The object stack being constructed. */ protected ArrayStack<Object> stack = new ArrayStack<>(); /** * Do we want to use the Context ClassLoader when loading classes * for instantiating new objects. Default is <code>false</code>. */ protected boolean useContextClassLoader = false; /** * Do we want to use a validating parser. */ protected boolean validating = false; /** * Warn on missing attributes and elements. */ protected boolean rulesValidation = false; /** * Fake attributes map (attributes are often used for object creation). */ protected Map<Class<?>, List<String>> fakeAttributes = null; /** * The Log to which most logging calls will be made. */ protected Log log = LogFactory.getLog("org.apache.tomcat.util.digester.Digester"); /** * The Log to which all SAX event related logging calls will be made. */ protected Log saxLog = LogFactory.getLog("org.apache.tomcat.util.digester.Digester.sax"); // ------------------------------------------------------------- Properties /** * Return the currently mapped namespace URI for the specified prefix, * if any; otherwise return <code>null</code>. These mappings come and * go dynamically as the document is parsed. * * @param prefix Prefix to look up */ public String findNamespaceURI(String prefix) { ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { return (null); } try { return stack.peek(); } catch (EmptyStackException e) { return (null); } } /** * Return the class loader to be used for instantiating application objects * when required. This is determined based upon the following rules: * <ul> * <li>The class loader set by <code>setClassLoader()</code>, if any</li> * <li>The thread context class loader, if it exists and the * <code>useContextClassLoader</code> property is set to true</li> * <li>The class loader used to load the Digester class itself. * </ul> */ public ClassLoader getClassLoader() { if (this.classLoader != null) { return (this.classLoader); } if (this.useContextClassLoader) { ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); if (classLoader != null) { return (classLoader); } } return (this.getClass().getClassLoader()); } /** * Set the class loader to be used for instantiating application objects * when required. * * @param classLoader The new class loader to use, or <code>null</code> * to revert to the standard rules */ public void setClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } /** * Return the current depth of the element stack. */ public int getCount() { return (stack.size()); } /** * Return the name of the XML element that is currently being processed. */ public String getCurrentElementName() { String elementName = match; int lastSlash = elementName.lastIndexOf('/'); if (lastSlash >= 0) { elementName = elementName.substring(lastSlash + 1); } return (elementName); } /** * Return the error handler for this Digester. */ public ErrorHandler getErrorHandler() { return (this.errorHandler); } /** * Set the error handler for this Digester. * * @param errorHandler The new error handler */ public void setErrorHandler(ErrorHandler errorHandler) { this.errorHandler = errorHandler; } /** * Return the SAXParserFactory we will use, creating one if necessary. * @throws ParserConfigurationException * @throws SAXNotSupportedException * @throws SAXNotRecognizedException */ public SAXParserFactory getFactory() throws SAXNotRecognizedException, SAXNotSupportedException, ParserConfigurationException { if (factory == null) { factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(namespaceAware); factory.setValidating(validating); if (validating) { // Enable DTD validation factory.setFeature( "http://xml.org/sax/features/validation", true); // Enable schema validation factory.setFeature( "http://apache.org/xml/features/validation/schema", true); } } return (factory); } /** * Sets a flag indicating whether the requested feature is supported * by the underlying implementation of <code>org.xml.sax.XMLReader</code>. * See <a href="http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-description" * http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-description</a> * for information about the standard SAX2 feature flags. In order to be * effective, this method must be called <strong>before</strong> the * <code>getParser()</code> method is called for the first time, either * directly or indirectly. * * @param feature Name of the feature to set the status for * @param value The new value for this feature * * @exception ParserConfigurationException if a parser configuration error * occurs * @exception SAXNotRecognizedException if the property name is * not recognized * @exception SAXNotSupportedException if the property name is * recognized but not supported */ public void setFeature(String feature, boolean value) throws ParserConfigurationException, SAXNotRecognizedException, SAXNotSupportedException { getFactory().setFeature(feature, value); } /** * Return the current Logger associated with this instance of the Digester */ public Log getLogger() { return log; } /** * Set the current logger for this Digester. */ public void setLogger(Log log) { this.log = log; } /** * Gets the logger used for logging SAX-related information. * <strong>Note</strong> the output is finely grained. * * @since 1.6 */ public Log getSAXLogger() { return saxLog; } /** * Sets the logger used for logging SAX-related information. * <strong>Note</strong> the output is finely grained. * @param saxLog Log, not null * * @since 1.6 */ public void setSAXLogger(Log saxLog) { this.saxLog = saxLog; } /** * Return the current rule match path */ public String getMatch() { return match; } /** * Return the "namespace aware" flag for parsers we create. */ public boolean getNamespaceAware() { return (this.namespaceAware); } /** * Set the "namespace aware" flag for parsers we create. * * @param namespaceAware The new "namespace aware" flag */ public void setNamespaceAware(boolean namespaceAware) { this.namespaceAware = namespaceAware; } /** * Set the public id of the current file being parse. * @param publicId the DTD/Schema public's id. */ public void setPublicId(String publicId){ this.publicId = publicId; } /** * Return the public identifier of the DTD we are currently * parsing under, if any. */ public String getPublicId() { return (this.publicId); } /** * Return the namespace URI that will be applied to all subsequently * added <code>Rule</code> objects. */ public String getRuleNamespaceURI() { return (getRules().getNamespaceURI()); } /** * Set the namespace URI that will be applied to all subsequently * added <code>Rule</code> objects. * * @param ruleNamespaceURI Namespace URI that must match on all * subsequently added rules, or <code>null</code> for matching * regardless of the current namespace URI */ public void setRuleNamespaceURI(String ruleNamespaceURI) { getRules().setNamespaceURI(ruleNamespaceURI); } /** * Return the SAXParser we will use to parse the input stream. If there * is a problem creating the parser, return <code>null</code>. */ public SAXParser getParser() { // Return the parser we already created (if any) if (parser != null) { return (parser); } // Create a new parser try { parser = getFactory().newSAXParser(); } catch (Exception e) { log.error("Digester.getParser: ", e); return (null); } return (parser); } /** * Return the current value of the specified property for the underlying * <code>XMLReader</code> implementation. * See <a href="http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-description" * http://www.saxproject.org/apidoc/xml/sax/package-summary.html#package-description</a> * for information about the standard SAX2 properties. * * @param property Property name to be retrieved * * @exception SAXNotRecognizedException if the property name is * not recognized * @exception SAXNotSupportedException if the property name is * recognized but not supported */ public Object getProperty(String property) throws SAXNotRecognizedException, SAXNotSupportedException { return (getParser().getProperty(property)); } /** * Return the <code>Rules</code> implementation object containing our * rules collection and associated matching policy. If none has been * established, a default implementation will be created and returned. */ public Rules getRules() { if (this.rules == null) { this.rules = new RulesBase(); this.rules.setDigester(this); } return (this.rules); } /** * Set the <code>Rules</code> implementation object containing our * rules collection and associated matching policy. * * @param rules New Rules implementation */ public void setRules(Rules rules) { this.rules = rules; this.rules.setDigester(this); } /** * Return the boolean as to whether the context classloader should be used. */ public boolean getUseContextClassLoader() { return useContextClassLoader; } /** * Determine whether to use the Context ClassLoader (the one found by * calling <code>Thread.currentThread().getContextClassLoader()</code>) * to resolve/load classes that are defined in various rules. If not * using Context ClassLoader, then the class-loading defaults to * using the calling-class' ClassLoader. * * @param use determines whether to use Context ClassLoader. */ public void setUseContextClassLoader(boolean use) { useContextClassLoader = use; } /** * Return the validating parser flag. */ public boolean getValidating() { return (this.validating); } /** * Set the validating parser flag. This must be called before * <code>parse()</code> is called the first time. * * @param validating The new validating parser flag. */ public void setValidating(boolean validating) { this.validating = validating; } /** * Return the rules validation flag. */ public boolean getRulesValidation() { return (this.rulesValidation); } /** * Set the rules validation flag. This must be called before * <code>parse()</code> is called the first time. * * @param rulesValidation The new rules validation flag. */ public void setRulesValidation(boolean rulesValidation) { this.rulesValidation = rulesValidation; } /** * Return the fake attributes list. */ public Map<Class<?>, List<String>> getFakeAttributes() { return (this.fakeAttributes); } /** * Determine if an attribute is a fake attribute. */ public boolean isFakeAttribute(Object object, String name) { if (fakeAttributes == null) { return false; } List<String> result = fakeAttributes.get(object.getClass()); if (result == null) { result = fakeAttributes.get(Object.class); } if (result == null) { return false; } else { return result.contains(name); } } /** * Set the fake attributes. * * @param fakeAttributes The new fake attributes. */ public void setFakeAttributes(Map<Class<?>, List<String>> fakeAttributes) { this.fakeAttributes = fakeAttributes; } /** * Return the XMLReader to be used for parsing the input document. * * FIX ME: there is a bug in JAXP/XERCES that prevent the use of a * parser that contains a schema with a DTD. * @exception SAXException if no XMLReader can be instantiated */ public XMLReader getXMLReader() throws SAXException { if (reader == null){ reader = getParser().getXMLReader(); } reader.setDTDHandler(this); reader.setContentHandler(this); if (entityResolver == null){ reader.setEntityResolver(this); } else { reader.setEntityResolver(entityResolver); } reader.setErrorHandler(this); return reader; } // ------------------------------------------------- ContentHandler Methods /** * Process notification of character data received from the body of * an XML element. * * @param buffer The characters from the XML document * @param start Starting offset into the buffer * @param length Number of characters from the buffer * * @exception SAXException if a parsing error is to be reported */ @Override public void characters(char buffer[], int start, int length) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("characters(" + new String(buffer, start, length) + ")"); } bodyText.append(buffer, start, length); } /** * Process notification of the end of the document being reached. * * @exception SAXException if a parsing error is to be reported */ @Override public void endDocument() throws SAXException { if (saxLog.isDebugEnabled()) { if (getCount() > 1) { saxLog.debug("endDocument(): " + getCount() + " elements left"); } else { saxLog.debug("endDocument()"); } } while (getCount() > 1) { pop(); } // Fire "finish" events for all defined rules Iterator<Rule> rules = getRules().rules().iterator(); while (rules.hasNext()) { Rule rule = rules.next(); try { rule.finish(); } catch (Exception e) { log.error("Finish event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Finish event threw error", e); throw e; } } // Perform final cleanup clear(); } /** * Process notification of the end of an XML element being reached. * * @param namespaceURI - The Namespace URI, or the empty string if the * element has no Namespace URI or if Namespace processing is not * being performed. * @param localName - The local name (without prefix), or the empty * string if Namespace processing is not being performed. * @param qName - The qualified XML 1.0 name (with prefix), or the * empty string if qualified names are not available. * @exception SAXException if a parsing error is to be reported */ @Override public void endElement(String namespaceURI, String localName, String qName) throws SAXException { boolean debug = log.isDebugEnabled(); if (debug) { if (saxLog.isDebugEnabled()) { saxLog.debug("endElement(" + namespaceURI + "," + localName + "," + qName + ")"); } log.debug(" match='" + match + "'"); log.debug(" bodyText='" + bodyText + "'"); } // Parse system properties bodyText = updateBodyText(bodyText); // the actual element name is either in localName or qName, depending // on whether the parser is namespace aware String name = localName; if ((name == null) || (name.length() < 1)) { name = qName; } // Fire "body" events for all relevant rules List<Rule> rules = matches.pop(); if ((rules != null) && (rules.size() > 0)) { String bodyText = this.bodyText.toString(); for (int i = 0; i < rules.size(); i++) { try { Rule rule = rules.get(i); if (debug) { log.debug(" Fire body() for " + rule); } rule.body(namespaceURI, name, bodyText); } catch (Exception e) { log.error("Body event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Body event threw error", e); throw e; } } } else { if (debug) { log.debug(" No rules found matching '" + match + "'."); } if (rulesValidation) { log.warn(" No rules found matching '" + match + "'."); } } // Recover the body text from the surrounding element bodyText = bodyTexts.pop(); if (debug) { log.debug(" Popping body text '" + bodyText.toString() + "'"); } // Fire "end" events for all relevant rules in reverse order if (rules != null) { for (int i = 0; i < rules.size(); i++) { int j = (rules.size() - i) - 1; try { Rule rule = rules.get(j); if (debug) { log.debug(" Fire end() for " + rule); } rule.end(namespaceURI, name); } catch (Exception e) { log.error("End event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("End event threw error", e); throw e; } } } // Recover the previous match expression int slash = match.lastIndexOf('/'); if (slash >= 0) { match = match.substring(0, slash); } else { match = ""; } } /** * Process notification that a namespace prefix is going out of scope. * * @param prefix Prefix that is going out of scope * * @exception SAXException if a parsing error is to be reported */ @Override public void endPrefixMapping(String prefix) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("endPrefixMapping(" + prefix + ")"); } // Deregister this prefix mapping ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { return; } try { stack.pop(); if (stack.empty()) namespaces.remove(prefix); } catch (EmptyStackException e) { throw createSAXException("endPrefixMapping popped too many times"); } } /** * Process notification of ignorable whitespace received from the body of * an XML element. * * @param buffer The characters from the XML document * @param start Starting offset into the buffer * @param len Number of characters from the buffer * * @exception SAXException if a parsing error is to be reported */ @Override public void ignorableWhitespace(char buffer[], int start, int len) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("ignorableWhitespace(" + new String(buffer, start, len) + ")"); } // No processing required } /** * Process notification of a processing instruction that was encountered. * * @param target The processing instruction target * @param data The processing instruction data (if any) * * @exception SAXException if a parsing error is to be reported */ @Override public void processingInstruction(String target, String data) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("processingInstruction('" + target + "','" + data + "')"); } // No processing is required } /** * Gets the document locator associated with our parser. * * @return the Locator supplied by the document parser */ public Locator getDocumentLocator() { return locator; } /** * Sets the document locator associated with our parser. * * @param locator The new locator */ @Override public void setDocumentLocator(Locator locator) { if (saxLog.isDebugEnabled()) { saxLog.debug("setDocumentLocator(" + locator + ")"); } this.locator = locator; } /** * Process notification of a skipped entity. * * @param name Name of the skipped entity * * @exception SAXException if a parsing error is to be reported */ @Override public void skippedEntity(String name) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("skippedEntity(" + name + ")"); } // No processing required } /** * Process notification of the beginning of the document being reached. * * @exception SAXException if a parsing error is to be reported */ @Override public void startDocument() throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("startDocument()"); } // ensure that the digester is properly configured, as // the digester could be used as a SAX ContentHandler // rather than via the parse() methods. configure(); } /** * Process notification of the start of an XML element being reached. * * @param namespaceURI The Namespace URI, or the empty string if the element * has no Namespace URI or if Namespace processing is not being performed. * @param localName The local name (without prefix), or the empty * string if Namespace processing is not being performed. * @param qName The qualified name (with prefix), or the empty * string if qualified names are not available.\ * @param list The attributes attached to the element. If there are * no attributes, it shall be an empty Attributes object. * @exception SAXException if a parsing error is to be reported */ @Override public void startElement(String namespaceURI, String localName, String qName, Attributes list) throws SAXException { boolean debug = log.isDebugEnabled(); if (saxLog.isDebugEnabled()) { saxLog.debug("startElement(" + namespaceURI + "," + localName + "," + qName + ")"); } // Parse system properties list = updateAttributes(list); // Save the body text accumulated for our surrounding element bodyTexts.push(bodyText); if (debug) { log.debug(" Pushing body text '" + bodyText.toString() + "'"); } bodyText = new StringBuilder(); // the actual element name is either in localName or qName, depending // on whether the parser is namespace aware String name = localName; if ((name == null) || (name.length() < 1)) { name = qName; } // Compute the current matching rule StringBuilder sb = new StringBuilder(match); if (match.length() > 0) { sb.append('/'); } sb.append(name); match = sb.toString(); if (debug) { log.debug(" New match='" + match + "'"); } // Fire "begin" events for all relevant rules List<Rule> rules = getRules().match(namespaceURI, match); matches.push(rules); if ((rules != null) && (rules.size() > 0)) { for (int i = 0; i < rules.size(); i++) { try { Rule rule = rules.get(i); if (debug) { log.debug(" Fire begin() for " + rule); } rule.begin(namespaceURI, name, list); } catch (Exception e) { log.error("Begin event threw exception", e); throw createSAXException(e); } catch (Error e) { log.error("Begin event threw error", e); throw e; } } } else { if (debug) { log.debug(" No rules found matching '" + match + "'."); } } } /** * Process notification that a namespace prefix is coming in to scope. * * @param prefix Prefix that is being declared * @param namespaceURI Corresponding namespace URI being mapped to * * @exception SAXException if a parsing error is to be reported */ @Override public void startPrefixMapping(String prefix, String namespaceURI) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("startPrefixMapping(" + prefix + "," + namespaceURI + ")"); } // Register this prefix mapping ArrayStack<String> stack = namespaces.get(prefix); if (stack == null) { stack = new ArrayStack<>(); namespaces.put(prefix, stack); } stack.push(namespaceURI); } // ----------------------------------------------------- DTDHandler Methods /** * Receive notification of a notation declaration event. * * @param name The notation name * @param publicId The public identifier (if any) * @param systemId The system identifier (if any) */ @Override public void notationDecl(String name, String publicId, String systemId) { if (saxLog.isDebugEnabled()) { saxLog.debug("notationDecl(" + name + "," + publicId + "," + systemId + ")"); } } /** * Receive notification of an unparsed entity declaration event. * * @param name The unparsed entity name * @param publicId The public identifier (if any) * @param systemId The system identifier (if any) * @param notation The name of the associated notation */ @Override public void unparsedEntityDecl(String name, String publicId, String systemId, String notation) { if (saxLog.isDebugEnabled()) { saxLog.debug("unparsedEntityDecl(" + name + "," + publicId + "," + systemId + "," + notation + ")"); } } // ----------------------------------------------- EntityResolver Methods /** * Set the <code>EntityResolver</code> used by SAX when resolving * public id and system id. * This must be called before the first call to <code>parse()</code>. * @param entityResolver a class that implement the <code>EntityResolver</code> interface. */ public void setEntityResolver(EntityResolver entityResolver){ this.entityResolver = entityResolver; } /** * Return the Entity Resolver used by the SAX parser. * @return Return the Entity Resolver used by the SAX parser. */ public EntityResolver getEntityResolver(){ return entityResolver; } /** * Resolve the requested external entity. * * @param publicId The public identifier of the entity being referenced * @param systemId The system identifier of the entity being referenced * * @exception SAXException if a parsing exception occurs * */ @Override public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (saxLog.isDebugEnabled()) { saxLog.debug("resolveEntity('" + publicId + "', '" + systemId + "')"); } if (publicId != null) this.publicId = publicId; // Has this system identifier been registered? String entityURL = null; if (publicId != null) { entityURL = entityValidator.get(publicId); } if (entityURL == null) { if (systemId == null) { // cannot resolve if (log.isDebugEnabled()) { log.debug(" Cannot resolve entity: '" + publicId + "'"); } return (null); } else { // try to resolve using system ID if (log.isDebugEnabled()) { log.debug(" Trying to resolve using system ID '" + systemId + "'"); } entityURL = systemId; } } // Return an input source to our alternative URL if (log.isDebugEnabled()) { log.debug(" Resolving to alternate DTD '" + entityURL + "'"); } try { return (new InputSource(entityURL)); } catch (Exception e) { throw createSAXException(e); } } // ------------------------------------------------- ErrorHandler Methods /** * Forward notification of a parsing error to the application supplied * error handler (if any). * * @param exception The error information * * @exception SAXException if a parsing exception occurs */ @Override public void error(SAXParseException exception) throws SAXException { log.error("Parse Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.error(exception); } } /** * Forward notification of a fatal parsing error to the application * supplied error handler (if any). * * @param exception The fatal error information * * @exception SAXException if a parsing exception occurs */ @Override public void fatalError(SAXParseException exception) throws SAXException { log.error("Parse Fatal Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); if (errorHandler != null) { errorHandler.fatalError(exception); } } /** * Forward notification of a parse warning to the application supplied * error handler (if any). * * @param exception The warning information * * @exception SAXException if a parsing exception occurs */ @Override public void warning(SAXParseException exception) throws SAXException { if (errorHandler != null) { log.warn("Parse Warning Error at line " + exception.getLineNumber() + " column " + exception.getColumnNumber() + ": " + exception.getMessage(), exception); errorHandler.warning(exception); } } // ------------------------------------------------------- Public Methods /** * Parse the content of the specified file using this Digester. Returns * the root element from the object stack (if any). * * @param file File containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(File file) throws IOException, SAXException { configure(); InputSource input = new InputSource(new FileInputStream(file)); input.setSystemId("file://" + file.getAbsolutePath()); getXMLReader().parse(input); return (root); } /** * Parse the content of the specified input source using this Digester. * Returns the root element from the object stack (if any). * * @param input Input source containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(InputSource input) throws IOException, SAXException { configure(); getXMLReader().parse(input); return (root); } /** * Parse the content of the specified input stream using this Digester. * Returns the root element from the object stack (if any). * * @param input Input stream containing the XML data to be parsed * * @exception IOException if an input/output error occurs * @exception SAXException if a parsing exception occurs */ public Object parse(InputStream input) throws IOException, SAXException { configure(); InputSource is = new InputSource(input); getXMLReader().parse(is); return (root); } /** * <p>Register the specified DTD URL for the specified public identifier. * This must be called before the first call to <code>parse()</code>. * </p><p> * <code>Digester</code> contains an internal <code>EntityResolver</code> * implementation. This maps <code>PUBLICID</code>'s to URLs * (from which the resource will be loaded). A common use case for this * method is to register local URLs (possibly computed at runtime by a * classloader) for DTDs. This allows the performance advantage of using * a local version without having to ensure every <code>SYSTEM</code> * URI on every processed xml document is local. This implementation provides * only basic functionality. If more sophisticated features are required, * using {@link #setEntityResolver} to set a custom resolver is recommended. * </p><p> * <strong>Note:</strong> This method will have no effect when a custom * <code>EntityResolver</code> has been set. (Setting a custom * <code>EntityResolver</code> overrides the internal implementation.) * </p> * @param publicId Public identifier of the DTD to be resolved * @param entityURL The URL to use for reading this DTD */ public void register(String publicId, String entityURL) { if (log.isDebugEnabled()) { log.debug("register('" + publicId + "', '" + entityURL + "'"); } entityValidator.put(publicId, entityURL); } // --------------------------------------------------------- Rule Methods /** * <p>Register a new Rule matching the specified pattern. * This method sets the <code>Digester</code> property on the rule.</p> * * @param pattern Element matching pattern * @param rule Rule to be registered */ public void addRule(String pattern, Rule rule) { rule.setDigester(this); getRules().add(pattern, rule); } /** * Register a set of Rule instances defined in a RuleSet. * * @param ruleSet The RuleSet instance to configure from */ public void addRuleSet(RuleSet ruleSet) { String oldNamespaceURI = getRuleNamespaceURI(); String newNamespaceURI = ruleSet.getNamespaceURI(); if (log.isDebugEnabled()) { if (newNamespaceURI == null) { log.debug("addRuleSet() with no namespace URI"); } else { log.debug("addRuleSet() with namespace URI " + newNamespaceURI); } } setRuleNamespaceURI(newNamespaceURI); ruleSet.addRuleInstances(this); setRuleNamespaceURI(oldNamespaceURI); } /** * Add an "call method" rule for a method which accepts no arguments. * * @param pattern Element matching pattern * @param methodName Method name to be called * @see CallMethodRule */ public void addCallMethod(String pattern, String methodName) { addRule( pattern, new CallMethodRule(methodName)); } /** * Add an "call method" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to be called * @param paramCount Number of expected parameters (or zero * for a single parameter from the body of this element) * @see CallMethodRule */ public void addCallMethod(String pattern, String methodName, int paramCount) { addRule(pattern, new CallMethodRule(methodName, paramCount)); } /** * Add a "call parameter" rule for the specified parameters. * * @param pattern Element matching pattern * @param paramIndex Zero-relative parameter index to set * (from the body of this element) * @see CallParamRule */ public void addCallParam(String pattern, int paramIndex) { addRule(pattern, new CallParamRule(paramIndex)); } /** * Add a "factory create" rule for the specified parameters. * * @param pattern Element matching pattern * @param creationFactory Previously instantiated ObjectCreationFactory * to be utilized * @param ignoreCreateExceptions when <code>true</code> any exceptions thrown during * object creation will be ignored. * @see FactoryCreateRule */ public void addFactoryCreate(String pattern, ObjectCreationFactory creationFactory, boolean ignoreCreateExceptions) { creationFactory.setDigester(this); addRule(pattern, new FactoryCreateRule(creationFactory, ignoreCreateExceptions)); } /** * Add an "object create" rule for the specified parameters. * * @param pattern Element matching pattern * @param className Java class name to be created * @see ObjectCreateRule */ public void addObjectCreate(String pattern, String className) { addRule(pattern, new ObjectCreateRule(className)); } /** * Add an "object create" rule for the specified parameters. * * @param pattern Element matching pattern * @param className Default Java class name to be created * @param attributeName Attribute name that optionally overrides * the default Java class name to be created * @see ObjectCreateRule */ public void addObjectCreate(String pattern, String className, String attributeName) { addRule(pattern, new ObjectCreateRule(className, attributeName)); } /** * Add a "set next" rule for the specified parameters. * * @param pattern Element matching pattern * @param methodName Method name to call on the parent element * @param paramType Java class name of the expected parameter type * (if you wish to use a primitive type, specify the corresponding * Java wrapper class instead, such as <code>java.lang.Boolean</code> * for a <code>boolean</code> parameter) * @see SetNextRule */ public void addSetNext(String pattern, String methodName, String paramType) { addRule(pattern, new SetNextRule(methodName, paramType)); } /** * Add a "set properties" rule for the specified parameters. * * @param pattern Element matching pattern * @see SetPropertiesRule */ public void addSetProperties(String pattern) { addRule(pattern, new SetPropertiesRule()); } // --------------------------------------------------- Object Stack Methods /** * Clear the current contents of the object stack. * <p> * Calling this method <i>might</i> allow another document of the same type * to be correctly parsed. However this method was not intended for this * purpose. In general, a separate Digester object should be created for * each document to be parsed. */ public void clear() { match = ""; bodyTexts.clear(); params.clear(); publicId = null; stack.clear(); log = null; saxLog = null; configured = false; } public void reset() { root = null; setErrorHandler(null); clear(); } /** * Return the top object on the stack without removing it. If there are * no objects on the stack, return <code>null</code>. */ public Object peek() { try { return (stack.peek()); } catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); } } /** * Return the n'th object down the stack, where 0 is the top element * and [getCount()-1] is the bottom element. If the specified index * is out of range, return <code>null</code>. * * @param n Index of the desired element, where 0 is the top of the stack, * 1 is the next element down, and so on. */ public Object peek(int n) { try { return (stack.peek(n)); } catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); } } /** * Pop the top object off of the stack, and return it. If there are * no objects on the stack, return <code>null</code>. */ public Object pop() { try { return (stack.pop()); } catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); } } /** * Push a new object onto the top of the object stack. * * @param object The new object */ public void push(Object object) { if (stack.size() == 0) { root = object; } stack.push(object); } /** * When the Digester is being used as a SAXContentHandler, * this method allows you to access the root object that has been * created after parsing. * * @return the root object that has been created after parsing * or null if the digester has not parsed any XML yet. */ public Object getRoot() { return root; } // ------------------------------------------------ Parameter Stack Methods // ------------------------------------------------------ Protected Methods /** * <p> * Provide a hook for lazy configuration of this <code>Digester</code> * instance. The default implementation does nothing, but subclasses * can override as needed. * </p> * * <p> * <strong>Note</strong> This method may be called more than once. * Once only initialization code should be placed in {@link #initialize} * or the code should take responsibility by checking and setting the * {@link #configured} flag. * </p> */ protected void configure() { // Do not configure more than once if (configured) { return; } log = LogFactory.getLog("org.apache.tomcat.util.digester.Digester"); saxLog = LogFactory.getLog("org.apache.tomcat.util.digester.Digester.sax"); // Perform lazy configuration as needed initialize(); // call hook method for subclasses that want to be initialized once only // Nothing else required by default // Set the configuration flag to avoid repeating configured = true; } /** * <p> * Provides a hook for lazy initialization of this <code>Digester</code> * instance. * The default implementation does nothing, but subclasses * can override as needed. * Digester (by default) only calls this method once. * </p> * * <p> * <strong>Note</strong> This method will be called by {@link #configure} * only when the {@link #configured} flag is false. * Subclasses that override <code>configure</code> or who set <code>configured</code> * may find that this method may be called more than once. * </p> * * @since 1.6 */ protected void initialize() { // Perform lazy initialization as needed // Nothing required by default } /** * <p>Return the top object on the parameters stack without removing it. If there are * no objects on the stack, return <code>null</code>.</p> * * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters. * See {@link #params}.</p> */ public Object peekParams() { try { return (params.peek()); } catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); } } /** * <p>Pop the top object off of the parameters stack, and return it. If there are * no objects on the stack, return <code>null</code>.</p> * * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters. * See {@link #params}.</p> */ public Object popParams() { try { if (log.isTraceEnabled()) { log.trace("Popping params"); } return (params.pop()); } catch (EmptyStackException e) { log.warn("Empty stack (returning null)"); return (null); } } /** * <p>Push a new object onto the top of the parameters stack.</p> * * <p>The parameters stack is used to store <code>CallMethodRule</code> parameters. * See {@link #params}.</p> * * @param object The new object */ public void pushParams(Object object) { if (log.isTraceEnabled()) { log.trace("Pushing params"); } params.push(object); } /** * Create a SAX exception which also understands about the location in * the digester file where the exception occurs * * @return the new exception */ public SAXException createSAXException(String message, Exception e) { if ((e != null) && (e instanceof InvocationTargetException)) { Throwable t = e.getCause(); if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } if (t instanceof Exception) { e = (Exception) t; } } if (locator != null) { String error = "Error at (" + locator.getLineNumber() + ", " + locator.getColumnNumber() + ") : " + message; if (e != null) { return new SAXParseException(error, locator, e); } else { return new SAXParseException(error, locator); } } log.error("No Locator!"); if (e != null) { return new SAXException(message, e); } else { return new SAXException(message); } } /** * Create a SAX exception which also understands about the location in * the digester file where the exception occurs * * @return the new exception */ public SAXException createSAXException(Exception e) { if (e instanceof InvocationTargetException) { Throwable t = e.getCause(); if (t instanceof ThreadDeath) { throw (ThreadDeath) t; } if (t instanceof VirtualMachineError) { throw (VirtualMachineError) t; } if (t instanceof Exception) { e = (Exception) t; } } return createSAXException(e.getMessage(), e); } /** * Create a SAX exception which also understands about the location in * the digester file where the exception occurs * * @return the new exception */ public SAXException createSAXException(String message) { return createSAXException(message, null); } // ------------------------------------------------------- Private Methods /** * Returns an attributes list which contains all the attributes * passed in, with any text of form "${xxx}" in an attribute value * replaced by the appropriate value from the system property. */ private Attributes updateAttributes(Attributes list) { if (list.getLength() == 0) { return list; } AttributesImpl newAttrs = new AttributesImpl(list); int nAttributes = newAttrs.getLength(); for (int i = 0; i < nAttributes; ++i) { String value = newAttrs.getValue(i); try { String newValue = IntrospectionUtils.replaceProperties(value, null, source); if (value != newValue) { newAttrs.setValue(i, newValue); } } catch (Exception e) { // ignore - let the attribute have its original value } } return newAttrs; } /** * Return a new StringBuilder containing the same contents as the * input buffer, except that data of form ${varname} have been * replaced by the value of that var as defined in the system property. */ private StringBuilder updateBodyText(StringBuilder bodyText) { String in = bodyText.toString(); String out; try { out = IntrospectionUtils.replaceProperties(in, null, source); } catch(Exception e) { return bodyText; // return unchanged data } if (out == in) { // No substitutions required. Don't waste memory creating // a new buffer return bodyText; } else { return new StringBuilder(out); } } }
55,218
Bug 55218 Upgrade Digester to be based on DefaultHandler2 and use LexicalHandler to detect publicId
Digester uses SAX2 features but is still based the SAX1 DefaultHandler. By upgrading to DefaultHandler2 it would be able to handle baseURIs when resolving entities and would have a default implementation of a LexicalHandler. Using LexicalHandler would allow it to respond directly to the startDTD event that reports the DOCTYPE (if present) so that it would not need to infer that from the first attempt to resolve an entity.
closed fixed
aa7896b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T10:07:23Z
2013-07-09T11:40:00Z
test/javax/servlet/resources/TestSchemaValidation.java
55,218
Bug 55218 Upgrade Digester to be based on DefaultHandler2 and use LexicalHandler to detect publicId
Digester uses SAX2 features but is still based the SAX1 DefaultHandler. By upgrading to DefaultHandler2 it would be able to handle baseURIs when resolving entities and would have a default implementation of a LexicalHandler. Using LexicalHandler would allow it to respond directly to the startDTD event that reports the DOCTYPE (if present) so that it would not need to infer that from the first attempt to resolve an entity.
closed fixed
aa7896b
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-09T10:07:23Z
2013-07-09T11:40:00Z
test/org/apache/tomcat/util/descriptor/web/TestWebXml.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.descriptor.web; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; /** * Test case for {@link WebXml}. */ public class TestWebXml { @Test public void testParseVersion() { WebXml webxml = new WebXml(); // Defaults Assert.assertEquals(3, webxml.getMajorVersion()); Assert.assertEquals(0, webxml.getMinorVersion()); // Both get changed webxml.setVersion("2.5"); Assert.assertEquals(2, webxml.getMajorVersion()); Assert.assertEquals(5, webxml.getMinorVersion()); // Reset webxml.setVersion("0.0"); Assert.assertEquals(0, webxml.getMajorVersion()); Assert.assertEquals(0, webxml.getMinorVersion()); // null input should be ignored webxml.setVersion(null); Assert.assertEquals(0, webxml.getMajorVersion()); Assert.assertEquals(0, webxml.getMinorVersion()); // major only webxml.setVersion("3"); Assert.assertEquals(3, webxml.getMajorVersion()); Assert.assertEquals(0, webxml.getMinorVersion()); // no minor digit webxml.setVersion("0.0"); // reset webxml.setVersion("3."); Assert.assertEquals(3, webxml.getMajorVersion()); Assert.assertEquals(0, webxml.getMinorVersion()); // minor only webxml.setVersion("0.0"); // reset webxml.setVersion(".5"); Assert.assertEquals(0, webxml.getMajorVersion()); Assert.assertEquals(5, webxml.getMinorVersion()); // leading & training zeros webxml.setVersion("0.0"); // reset webxml.setVersion("002.500"); Assert.assertEquals(2, webxml.getMajorVersion()); Assert.assertEquals(500, webxml.getMinorVersion()); } @Test public void testParsePublicIdVersion22() { WebXml webxml = new WebXml(); webxml.setPublicId( org.apache.catalina.startup.Constants.WebDtdPublicId_22); Assert.assertEquals(2, webxml.getMajorVersion()); Assert.assertEquals(2, webxml.getMinorVersion()); Assert.assertEquals("2.2", webxml.getVersion()); } @Test public void testParsePublicIdVersion23() { WebXml webxml = new WebXml(); webxml.setPublicId( org.apache.catalina.startup.Constants.WebDtdPublicId_23); Assert.assertEquals(2, webxml.getMajorVersion()); Assert.assertEquals(3, webxml.getMinorVersion()); Assert.assertEquals("2.3", webxml.getVersion()); } @Test public void testParsePublicIdVersion24() { WebXml webxml = new WebXml(); webxml.setPublicId( org.apache.catalina.startup.Constants.WebSchemaPublicId_24); Assert.assertEquals(2, webxml.getMajorVersion()); Assert.assertEquals(4, webxml.getMinorVersion()); Assert.assertEquals("2.4", webxml.getVersion()); } @Test public void testParsePublicIdVersion25() { WebXml webxml = new WebXml(); webxml.setPublicId( org.apache.catalina.startup.Constants.WebSchemaPublicId_25); Assert.assertEquals(2, webxml.getMajorVersion()); Assert.assertEquals(5, webxml.getMinorVersion()); Assert.assertEquals("2.5", webxml.getVersion()); } @Test public void testParsePublicIdVersion30() { WebXml webxml = new WebXml(); webxml.setPublicId( org.apache.catalina.startup.Constants.WebSchemaPublicId_30); Assert.assertEquals(3, webxml.getMajorVersion()); Assert.assertEquals(0, webxml.getMinorVersion()); Assert.assertEquals("3.0", webxml.getVersion()); } @Test public void testParsePublicIdVersion31() { WebXml webxml = new WebXml(); webxml.setPublicId( org.apache.catalina.startup.Constants.WebSchemaPublicId_31); Assert.assertEquals(3, webxml.getMajorVersion()); Assert.assertEquals(1, webxml.getMinorVersion()); Assert.assertEquals("3.1", webxml.getVersion()); } @Test public void testLifecycleMethodsWebXml() { WebXml webxml = new WebXml(); webxml.addPostConstructMethods("a", "a"); webxml.addPreDestroyMethods("b", "b"); WebXml fragment = new WebXml(); fragment.addPostConstructMethods("c", "c"); fragment.addPreDestroyMethods("d", "d"); Set<WebXml> fragments = new HashSet<>(); fragments.add(fragment); webxml.merge(fragments); Map<String, String> postConstructMethods = webxml.getPostConstructMethods(); Map<String, String> preDestroyMethods = webxml.getPreDestroyMethods(); Assert.assertEquals(1, postConstructMethods.size()); Assert.assertEquals(1, preDestroyMethods.size()); Assert.assertEquals("a", postConstructMethods.get("a")); Assert.assertEquals("b", preDestroyMethods.get("b")); } @Test public void testLifecycleMethodsWebFragments() { WebXml webxml = new WebXml(); WebXml fragment1 = new WebXml(); fragment1.addPostConstructMethods("a", "a"); fragment1.addPreDestroyMethods("b", "b"); WebXml fragment2 = new WebXml(); fragment2.addPostConstructMethods("c", "c"); fragment2.addPreDestroyMethods("d", "d"); Set<WebXml> fragments = new HashSet<>(); fragments.add(fragment1); fragments.add(fragment2); webxml.merge(fragments); Map<String, String> postConstructMethods = webxml.getPostConstructMethods(); Map<String, String> preDestroyMethods = webxml.getPreDestroyMethods(); Assert.assertEquals(2, postConstructMethods.size()); Assert.assertEquals(2, preDestroyMethods.size()); Assert.assertEquals("a", postConstructMethods.get("a")); Assert.assertEquals("c", postConstructMethods.get("c")); Assert.assertEquals("b", preDestroyMethods.get("b")); Assert.assertEquals("d", preDestroyMethods.get("d")); } @Test public void testLifecycleMethodsWebFragmentsWithConflicts() { WebXml webxml = new WebXml(); WebXml fragment1 = new WebXml(); fragment1.addPostConstructMethods("a", "a"); fragment1.addPreDestroyMethods("b", "a"); WebXml fragment2 = new WebXml(); fragment2.addPostConstructMethods("a", "b"); Set<WebXml> fragments = new HashSet<>(); fragments.add(fragment1); fragments.add(fragment2); Assert.assertFalse(webxml.merge(fragments)); Assert.assertEquals(0, webxml.getPostConstructMethods().size()); WebXml fragment3 = new WebXml(); fragment3.addPreDestroyMethods("b", "b"); fragments.remove(fragment2); fragments.add(fragment3); Assert.assertFalse(webxml.merge(fragments)); Assert.assertEquals(0, webxml.getPreDestroyMethods().size()); } @Test(expected=IllegalArgumentException.class) public void testBug54387a() { // Multiple servlets may not be mapped to the same url-pattern WebXml webxml = new WebXml(); webxml.addServletMapping("/foo", "a"); webxml.addServletMapping("/foo", "b"); } @Test(expected=IllegalArgumentException.class) public void testBug54387b() { // Multiple servlets may not be mapped to the same url-pattern WebXml webxml = new WebXml(); WebXml f1 = new WebXml(); WebXml f2 = new WebXml(); HashSet<WebXml> fragments = new HashSet<>(); fragments.add(f1); fragments.add(f2); f1.addServletMapping("/foo", "a"); f2.addServletMapping("/foo", "b"); webxml.merge(fragments); } @Test public void testBug54387c() { // Multiple servlets may not be mapped to the same url-pattern but main // web.xml takes priority WebXml webxml = new WebXml(); WebXml f1 = new WebXml(); WebXml f2 = new WebXml(); HashSet<WebXml> fragments = new HashSet<>(); fragments.add(f1); fragments.add(f2); f1.addServletMapping("/foo", "a"); f2.addServletMapping("/foo", "b"); webxml.addServletMapping("/foo", "main"); webxml.merge(fragments); } }
55,231
Bug 55231 NPE and incorrect version detection in JspC
JspC's JspConfig now reads version and jsp-config information from the ServletContext. It uses getMajorVersion() which returns the maximum version supported by the container. It should use getEffectiveVersion() to use the version of the web application. ServletContext.getJspConfigDescriptor() can return null if there is no <jsp-config> in the web.xml. JspConfig does not allow for this and will throw a NPE e.g. if there is no web.xml in the application.
closed fixed
c8376e8
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-10T13:40:32Z
2013-07-10T07:06:40Z
java/org/apache/jasper/compiler/JspConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.util.Collection; import java.util.Iterator; import java.util.Vector; import javax.servlet.ServletContext; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.descriptor.JspPropertyGroupDescriptor; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * Handles the jsp-config element in WEB_INF/web.xml. This is used * for specifying the JSP configuration information on a JSP page * * @author Kin-man Chung * @author Remy Maucherat */ public class JspConfig { // Logger private final Log log = LogFactory.getLog(JspConfig.class); private Vector<JspPropertyGroup> jspProperties = null; private final ServletContext ctxt; private volatile boolean initialized = false; private static final String defaultIsXml = null; // unspecified private String defaultIsELIgnored = null; // unspecified private static final String defaultIsScriptingInvalid = null; private String defaultDeferedSyntaxAllowedAsLiteral = null; private static final String defaultTrimDirectiveWhitespaces = null; private static final String defaultDefaultContentType = null; private static final String defaultBuffer = null; private static final String defaultErrorOnUndeclaredNamespace = "false"; private JspProperty defaultJspProperty; public JspConfig(ServletContext ctxt) { this.ctxt = ctxt; } private void processWebDotXml() { // Very, very unlikely but just in case... if (ctxt.getMajorVersion() < 2) { defaultIsELIgnored = "true"; defaultDeferedSyntaxAllowedAsLiteral = "true"; return; } if (ctxt.getMajorVersion() == 2) { if (ctxt.getMinorVersion() < 5) { defaultDeferedSyntaxAllowedAsLiteral = "true"; } if (ctxt.getMinorVersion() < 4) { defaultIsELIgnored = "true"; return; } } JspConfigDescriptor jspConfig = ctxt.getJspConfigDescriptor(); if (jspConfig == null) { return; } Collection<JspPropertyGroupDescriptor> jspPropertyGroups = jspConfig.getJspPropertyGroups(); for (JspPropertyGroupDescriptor jspPropertyGroup : jspPropertyGroups) { Collection<String> urlPatterns = jspPropertyGroup.getUrlPatterns(); if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for (String urlPattern : urlPatterns) { String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0,i+1); file = urlPattern.substring(i+1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.')+1); } // The url patterns are reconstructed as the following: // path != null, extension == null: / or /foo/bar.ext // path == null, extension != null: *.ext // path != null, extension == "*": /foo/* boolean isStar = "*".equals(extension); if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } Vector<String> includePreludes = new Vector<>(); includePreludes.addAll(jspPropertyGroup.getIncludePreludes()); Vector<String> includeCodas = new Vector<>(); includeCodas.addAll(jspPropertyGroup.getIncludeCodas()); JspProperty property = new JspProperty(jspPropertyGroup.getIsXml(), jspPropertyGroup.getElIgnored(), jspPropertyGroup.getScriptingInvalid(), jspPropertyGroup.getPageEncoding(), includePreludes, includeCodas, jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral(), jspPropertyGroup.getTrimDirectiveWhitespaces(), jspPropertyGroup.getDefaultContentType(), jspPropertyGroup.getBuffer(), jspPropertyGroup.getErrorOnUndeclaredNamespace()); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } } private void init() { if (!initialized) { synchronized (this) { if (!initialized) { processWebDotXml(); defaultJspProperty = new JspProperty(defaultIsXml, defaultIsELIgnored, defaultIsScriptingInvalid, null, null, null, defaultDeferedSyntaxAllowedAsLiteral, defaultTrimDirectiveWhitespaces, defaultDefaultContentType, defaultBuffer, defaultErrorOnUndeclaredNamespace); initialized = true; } } } } /** * Select the property group that has more restrictive url-pattern. * In case of tie, select the first. */ @SuppressWarnings("null") // NPE not possible private JspPropertyGroup selectProperty(JspPropertyGroup prev, JspPropertyGroup curr) { if (prev == null) { return curr; } if (prev.getExtension() == null) { // exact match return prev; } if (curr.getExtension() == null) { // exact match return curr; } String prevPath = prev.getPath(); String currPath = curr.getPath(); if (prevPath == null && currPath == null) { // Both specifies a *.ext, keep the first one return prev; } if (prevPath == null && currPath != null) { return curr; } if (prevPath != null && currPath == null) { return prev; } if (prevPath.length() >= currPath.length()) { return prev; } return curr; } /** * Find a property that best matches the supplied resource. * @param uri the resource supplied. * @return a JspProperty indicating the best match, or some default. */ public JspProperty findJspProperty(String uri) { init(); // JSP Configuration settings do not apply to tag files if (jspProperties == null || uri.endsWith(".tag") || uri.endsWith(".tagx")) { return defaultJspProperty; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Vector<String> includePreludes = new Vector<>(); Vector<String> includeCodas = new Vector<>(); JspPropertyGroup isXmlMatch = null; JspPropertyGroup elIgnoredMatch = null; JspPropertyGroup scriptingInvalidMatch = null; JspPropertyGroup pageEncodingMatch = null; JspPropertyGroup deferedSyntaxAllowedAsLiteralMatch = null; JspPropertyGroup trimDirectiveWhitespacesMatch = null; JspPropertyGroup defaultContentTypeMatch = null; JspPropertyGroup bufferMatch = null; JspPropertyGroup errorOnUndeclaredNamespaceMatch = null; Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); JspProperty jp = jpg.getJspProperty(); // (arrays will be the same length) String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { // exact match pattern: /a/foo.jsp if (!uri.equals(path)) { // not matched; continue; } } else { // Matching patterns *.ext or /p/* if (path != null && uriPath != null && ! uriPath.startsWith(path)) { // not matched continue; } if (!extension.equals("*") && !extension.equals(uriExtension)) { // not matched continue; } } // We have a match // Add include-preludes and include-codas if (jp.getIncludePrelude() != null) { includePreludes.addAll(jp.getIncludePrelude()); } if (jp.getIncludeCoda() != null) { includeCodas.addAll(jp.getIncludeCoda()); } // If there is a previous match for the same property, remember // the one that is more restrictive. if (jp.isXml() != null) { isXmlMatch = selectProperty(isXmlMatch, jpg); } if (jp.isELIgnored() != null) { elIgnoredMatch = selectProperty(elIgnoredMatch, jpg); } if (jp.isScriptingInvalid() != null) { scriptingInvalidMatch = selectProperty(scriptingInvalidMatch, jpg); } if (jp.getPageEncoding() != null) { pageEncodingMatch = selectProperty(pageEncodingMatch, jpg); } if (jp.isDeferedSyntaxAllowedAsLiteral() != null) { deferedSyntaxAllowedAsLiteralMatch = selectProperty(deferedSyntaxAllowedAsLiteralMatch, jpg); } if (jp.isTrimDirectiveWhitespaces() != null) { trimDirectiveWhitespacesMatch = selectProperty(trimDirectiveWhitespacesMatch, jpg); } if (jp.getDefaultContentType() != null) { defaultContentTypeMatch = selectProperty(defaultContentTypeMatch, jpg); } if (jp.getBuffer() != null) { bufferMatch = selectProperty(bufferMatch, jpg); } if (jp.isErrorOnUndeclaredNamespace() != null) { errorOnUndeclaredNamespaceMatch = selectProperty(errorOnUndeclaredNamespaceMatch, jpg); } } String isXml = defaultIsXml; String isELIgnored = defaultIsELIgnored; String isScriptingInvalid = defaultIsScriptingInvalid; String pageEncoding = null; String isDeferedSyntaxAllowedAsLiteral = defaultDeferedSyntaxAllowedAsLiteral; String isTrimDirectiveWhitespaces = defaultTrimDirectiveWhitespaces; String defaultContentType = defaultDefaultContentType; String buffer = defaultBuffer; String errorOnUndelcaredNamespace = defaultErrorOnUndeclaredNamespace; if (isXmlMatch != null) { isXml = isXmlMatch.getJspProperty().isXml(); } if (elIgnoredMatch != null) { isELIgnored = elIgnoredMatch.getJspProperty().isELIgnored(); } if (scriptingInvalidMatch != null) { isScriptingInvalid = scriptingInvalidMatch.getJspProperty().isScriptingInvalid(); } if (pageEncodingMatch != null) { pageEncoding = pageEncodingMatch.getJspProperty().getPageEncoding(); } if (deferedSyntaxAllowedAsLiteralMatch != null) { isDeferedSyntaxAllowedAsLiteral = deferedSyntaxAllowedAsLiteralMatch.getJspProperty().isDeferedSyntaxAllowedAsLiteral(); } if (trimDirectiveWhitespacesMatch != null) { isTrimDirectiveWhitespaces = trimDirectiveWhitespacesMatch.getJspProperty().isTrimDirectiveWhitespaces(); } if (defaultContentTypeMatch != null) { defaultContentType = defaultContentTypeMatch.getJspProperty().getDefaultContentType(); } if (bufferMatch != null) { buffer = bufferMatch.getJspProperty().getBuffer(); } if (errorOnUndeclaredNamespaceMatch != null) { errorOnUndelcaredNamespace = errorOnUndeclaredNamespaceMatch.getJspProperty().isErrorOnUndeclaredNamespace(); } return new JspProperty(isXml, isELIgnored, isScriptingInvalid, pageEncoding, includePreludes, includeCodas, isDeferedSyntaxAllowedAsLiteral, isTrimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndelcaredNamespace); } /** * To find out if an uri matches an url pattern in jsp config. If so, * then the uri is a JSP page. This is used primarily for jspc. */ public boolean isJspPage(String uri) { init(); if (jspProperties == null) { return false; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { if (uri.equals(path)) { // There is an exact match return true; } } else { if ((path == null || path.equals(uriPath)) && (extension.equals("*") || extension.equals(uriExtension))) { // Matches *, *.ext, /p/*, or /p/*.ext return true; } } } return false; } public static class JspPropertyGroup { private final String path; private final String extension; private final JspProperty jspProperty; JspPropertyGroup(String path, String extension, JspProperty jspProperty) { this.path = path; this.extension = extension; this.jspProperty = jspProperty; } public String getPath() { return path; } public String getExtension() { return extension; } public JspProperty getJspProperty() { return jspProperty; } } public static class JspProperty { private final String isXml; private final String elIgnored; private final String scriptingInvalid; private final String pageEncoding; private final Vector<String> includePrelude; private final Vector<String> includeCoda; private final String deferedSyntaxAllowedAsLiteral; private final String trimDirectiveWhitespaces; private final String defaultContentType; private final String buffer; private final String errorOnUndeclaredNamespace; public JspProperty(String isXml, String elIgnored, String scriptingInvalid, String pageEncoding, Vector<String> includePrelude, Vector<String> includeCoda, String deferedSyntaxAllowedAsLiteral, String trimDirectiveWhitespaces, String defaultContentType, String buffer, String errorOnUndeclaredNamespace) { this.isXml = isXml; this.elIgnored = elIgnored; this.scriptingInvalid = scriptingInvalid; this.pageEncoding = pageEncoding; this.includePrelude = includePrelude; this.includeCoda = includeCoda; this.deferedSyntaxAllowedAsLiteral = deferedSyntaxAllowedAsLiteral; this.trimDirectiveWhitespaces = trimDirectiveWhitespaces; this.defaultContentType = defaultContentType; this.buffer = buffer; this.errorOnUndeclaredNamespace = errorOnUndeclaredNamespace; } public String isXml() { return isXml; } public String isELIgnored() { return elIgnored; } public String isScriptingInvalid() { return scriptingInvalid; } public String getPageEncoding() { return pageEncoding; } public Vector<String> getIncludePrelude() { return includePrelude; } public Vector<String> getIncludeCoda() { return includeCoda; } public String isDeferedSyntaxAllowedAsLiteral() { return deferedSyntaxAllowedAsLiteral; } public String isTrimDirectiveWhitespaces() { return trimDirectiveWhitespaces; } public String getDefaultContentType() { return defaultContentType; } public String getBuffer() { return buffer; } public String isErrorOnUndeclaredNamespace() { return errorOnUndeclaredNamespace; } } }
55,207
Bug 55207 In XML syntax, jsp:text does not error on sub-elements from other namespaces
null
resolved fixed
6c54031
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-10T19:29:26Z
2013-07-07T04:06:40Z
java/org/apache/jasper/compiler/JspDocumentParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.io.CharArrayWriter; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import java.util.jar.JarFile; import javax.servlet.jsp.tagext.TagFileInfo; import javax.servlet.jsp.tagext.TagInfo; import javax.servlet.jsp.tagext.TagLibraryInfo; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; import org.xml.sax.XMLReader; import org.xml.sax.ext.LexicalHandler; import org.xml.sax.helpers.AttributesImpl; import org.xml.sax.helpers.DefaultHandler; /** * Class implementing a parser for a JSP document, that is, a JSP page in XML * syntax. * * @author Jan Luehe * @author Kin-man Chung */ class JspDocumentParser extends DefaultHandler implements LexicalHandler, TagConstants { private static final String LEXICAL_HANDLER_PROPERTY = "http://xml.org/sax/properties/lexical-handler"; private static final String JSP_URI = "http://java.sun.com/JSP/Page"; private final ParserController parserController; private final JspCompilationContext ctxt; private final PageInfo pageInfo; private final String path; private StringBuilder charBuffer; // Node representing the XML element currently being parsed private Node current; /* * Outermost (in the nesting hierarchy) node whose body is declared to be * scriptless. If a node's body is declared to be scriptless, all its * nested nodes must be scriptless, too. */ private Node scriptlessBodyNode; private Locator locator; //Mark representing the start of the current element. Note //that locator.getLineNumber() and locator.getColumnNumber() //return the line and column numbers for the character //immediately _following_ the current element. The underlying //XMl parser eats white space that is not part of character //data, so for Nodes that are not created from character data, //this is the best we can do. But when we parse character data, //we get an accurate starting location by starting with startMark //as set by the previous element, and updating it as we advance //through the characters. private Mark startMark; // Flag indicating whether we are inside DTD declarations private boolean inDTD; private boolean isValidating; private final ErrorDispatcher err; private final boolean isTagFile; private final boolean directivesOnly; private boolean isTop; // Nesting level of Tag dependent bodies private int tagDependentNesting = 0; // Flag set to delay incrementing tagDependentNesting until jsp:body // is first encountered private boolean tagDependentPending = false; /* * Constructor */ public JspDocumentParser( ParserController pc, String path, boolean isTagFile, boolean directivesOnly) { this.parserController = pc; this.ctxt = pc.getJspCompilationContext(); this.pageInfo = pc.getCompiler().getPageInfo(); this.err = pc.getCompiler().getErrorDispatcher(); this.path = path; this.isTagFile = isTagFile; this.directivesOnly = directivesOnly; this.isTop = true; } /* * Parses a JSP document by responding to SAX events. * * @throws JasperException */ public static Node.Nodes parse( ParserController pc, String path, JarFile jarFile, Node parent, boolean isTagFile, boolean directivesOnly, String pageEnc, String jspConfigPageEnc, boolean isEncodingSpecifiedInProlog, boolean isBomPresent) throws JasperException { JspDocumentParser jspDocParser = new JspDocumentParser(pc, path, isTagFile, directivesOnly); Node.Nodes pageNodes = null; try { // Create dummy root and initialize it with given page encodings Node.Root dummyRoot = new Node.Root(null, parent, true); dummyRoot.setPageEncoding(pageEnc); dummyRoot.setJspConfigPageEncoding(jspConfigPageEnc); dummyRoot.setIsEncodingSpecifiedInProlog( isEncodingSpecifiedInProlog); dummyRoot.setIsBomPresent(isBomPresent); jspDocParser.current = dummyRoot; if (parent == null) { jspDocParser.addInclude( dummyRoot, jspDocParser.pageInfo.getIncludePrelude()); } else { jspDocParser.isTop = false; } // Parse the input SAXParser saxParser = getSAXParser(false, jspDocParser); InputStream inStream = null; try { inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); } catch (EnableDTDValidationException e) { saxParser = getSAXParser(true, jspDocParser); jspDocParser.isValidating = true; if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } inStream = JspUtil.getInputStream(path, jarFile, jspDocParser.ctxt); saxParser.parse(new InputSource(inStream), jspDocParser); } finally { if (inStream != null) { try { inStream.close(); } catch (Exception any) { } } } if (parent == null) { jspDocParser.addInclude( dummyRoot, jspDocParser.pageInfo.getIncludeCoda()); } // Create Node.Nodes from dummy root pageNodes = new Node.Nodes(dummyRoot); } catch (IOException ioe) { jspDocParser.err.jspError(ioe, "jsp.error.data.file.read", path); } catch (SAXParseException e) { jspDocParser.err.jspError (new Mark(jspDocParser.ctxt, path, e.getLineNumber(), e.getColumnNumber()), e, e.getMessage()); } catch (Exception e) { jspDocParser.err.jspError(e, "jsp.error.data.file.processing", path); } return pageNodes; } /* * Processes the given list of included files. * * This is used to implement the include-prelude and include-coda * subelements of the jsp-config element in web.xml */ private void addInclude(Node parent, List<String> files) throws SAXException { if (files != null) { Iterator<String> iter = files.iterator(); while (iter.hasNext()) { String file = iter.next(); AttributesImpl attrs = new AttributesImpl(); attrs.addAttribute("", "file", "file", "CDATA", file); // Create a dummy Include directive node Node includeDir = new Node.IncludeDirective(attrs, null, // XXX parent); processIncludeDirective(file, includeDir); } } } /* * Receives notification of the start of an element. * * This method assigns the given tag attributes to one of 3 buckets: * * - "xmlns" attributes that represent (standard or custom) tag libraries. * - "xmlns" attributes that do not represent tag libraries. * - all remaining attributes. * * For each "xmlns" attribute that represents a custom tag library, the * corresponding TagLibraryInfo object is added to the set of custom * tag libraries. */ @Override public void startElement( String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl taglibAttrs = null; AttributesImpl nonTaglibAttrs = null; AttributesImpl nonTaglibXmlnsAttrs = null; processChars(); checkPrefixes(uri, qName, attrs); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } String currentPrefix = getPrefix(current.getQName()); // jsp:text must not have any subelements if (JSP_URI.equals(uri) && TEXT_ACTION.equals(current.getLocalName()) && "jsp".equals(currentPrefix)) { throw new SAXParseException( Localizer.getMessage("jsp.error.text.has_subelement"), locator); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); if (attrs != null) { /* * Notice that due to a bug in the underlying SAX parser, the * attributes must be enumerated in descending order. */ boolean isTaglib = false; for (int i = attrs.getLength() - 1; i >= 0; i--) { isTaglib = false; String attrQName = attrs.getQName(i); if (!attrQName.startsWith("xmlns")) { if (nonTaglibAttrs == null) { nonTaglibAttrs = new AttributesImpl(); } nonTaglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (attrQName.startsWith("xmlns:jsp")) { isTaglib = true; } else { String attrUri = attrs.getValue(i); // TaglibInfo for this uri already established in // startPrefixMapping isTaglib = pageInfo.hasTaglib(attrUri); } if (isTaglib) { if (taglibAttrs == null) { taglibAttrs = new AttributesImpl(); } taglibAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } else { if (nonTaglibXmlnsAttrs == null) { nonTaglibXmlnsAttrs = new AttributesImpl(); } nonTaglibXmlnsAttrs.addAttribute( attrs.getURI(i), attrs.getLocalName(i), attrs.getQName(i), attrs.getType(i), attrs.getValue(i)); } } } } Node node = null; if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(BODY_ACTION)) { tagDependentPending = false; tagDependentNesting++; current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending && JSP_URI.equals(uri) && localName.equals(ATTRIBUTE_ACTION)) { current = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); return; } if (tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else if (JSP_URI.equals(uri)) { node = parseStandardAction( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark); } else { node = parseCustomAction( qName, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); if (node == null) { node = new Node.UninterpretedTag( qName, localName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, startMark, current); } else { // custom action String bodyType = getBodyType((Node.CustomTag) node); if (scriptlessBodyNode == null && bodyType.equalsIgnoreCase(TagInfo.BODY_CONTENT_SCRIPTLESS)) { scriptlessBodyNode = node; } else if (TagInfo.BODY_CONTENT_TAG_DEPENDENT.equalsIgnoreCase(bodyType)) { tagDependentPending = true; } } } current = node; } /* * Receives notification of character data inside an element. * * The SAX does not call this method with all of the template text, but may * invoke this method with chunks of it. This is a problem when we try * to determine if the text contains only whitespaces, or when we are * looking for an EL expression string. Therefore it is necessary to * buffer and concatenate the chunks and process the concatenated text * later (at beginTag and endTag) * * @param buf The characters * @param offset The start position in the character array * @param len The number of characters to use from the character array * * @throws SAXException */ @Override public void characters(char[] buf, int offset, int len) { if (charBuffer == null) { charBuffer = new StringBuilder(); } charBuffer.append(buf, offset, len); } private void processChars() throws SAXException { if (charBuffer == null || directivesOnly) { return; } /* * JSP.6.1.1: All textual nodes that have only white space are to be * dropped from the document, except for nodes in a jsp:text element, * and any leading and trailing white-space-only textual nodes in a * jsp:attribute whose 'trim' attribute is set to FALSE, which are to * be kept verbatim. * JSP.6.2.3 defines white space characters. */ boolean isAllSpace = true; if (!(current instanceof Node.JspText) && !(current instanceof Node.NamedAttribute)) { for (int i = 0; i < charBuffer.length(); i++) { char ch = charBuffer.charAt(i); if (!(ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t')) { isAllSpace = false; break; } } } if (!isAllSpace && tagDependentPending) { tagDependentPending = false; tagDependentNesting++; } if (tagDependentNesting > 0 || pageInfo.isELIgnored() || current instanceof Node.ScriptingElement) { if (charBuffer.length() > 0) { @SuppressWarnings("unused") Node unused = new Node.TemplateText( charBuffer.toString(), startMark, current); } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; return; } if ((current instanceof Node.JspText) || (current instanceof Node.NamedAttribute) || !isAllSpace) { int line = startMark.getLineNumber(); int column = startMark.getColumnNumber(); CharArrayWriter ttext = new CharArrayWriter(); int lastCh = 0, elType = 0; for (int i = 0; i < charBuffer.length(); i++) { int ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if ((lastCh == '$' || lastCh == '#') && ch == '{') { elType = lastCh; if (ttext.size() > 0) { @SuppressWarnings("unused") Node unused = new Node.TemplateText( ttext.toString(), startMark, current); ttext.reset(); //We subtract two from the column number to //account for the '[$,#]{' that we've already parsed startMark = new Mark(ctxt, path, line, column - 2); } // following "${" || "#{" to first unquoted "}" i++; boolean singleQ = false; boolean doubleQ = false; lastCh = 0; for (;; i++) { if (i >= charBuffer.length()) { throw new SAXParseException( Localizer.getMessage( "jsp.error.unterminated", (char) elType + "{"), locator); } ch = charBuffer.charAt(i); if (ch == '\n') { column = 1; line++; } else { column++; } if (lastCh == '\\' && (singleQ || doubleQ)) { ttext.write(ch); lastCh = 0; continue; } if (ch == '}') { @SuppressWarnings("unused") Node unused = new Node.ELExpression( (char) elType, ttext.toString(), startMark, current); ttext.reset(); startMark = new Mark(ctxt, path, line, column); break; } if (ch == '"') doubleQ = !doubleQ; else if (ch == '\'') singleQ = !singleQ; ttext.write(ch); lastCh = ch; } } else if (lastCh == '\\' && (ch == '$' || ch == '#')) { if (pageInfo.isELIgnored()) { ttext.write('\\'); } ttext.write(ch); ch = 0; // Not start of EL anymore } else { if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ch != '$' && ch != '#' && ch != '\\') { ttext.write(ch); } } lastCh = ch; } if (lastCh == '$' || lastCh == '#' || lastCh == '\\') { ttext.write(lastCh); } if (ttext.size() > 0) { @SuppressWarnings("unused") Node unused = new Node.TemplateText( ttext.toString(), startMark, current); } } startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); charBuffer = null; } /* * Receives notification of the end of an element. */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { processChars(); if (directivesOnly && !(JSP_URI.equals(uri) && localName.startsWith(DIRECTIVE_ACTION))) { return; } if (current instanceof Node.NamedAttribute) { boolean isTrim = ((Node.NamedAttribute)current).isTrim(); Node.Nodes subElems = ((Node.NamedAttribute)current).getBody(); for (int i = 0; subElems != null && i < subElems.size(); i++) { Node subElem = subElems.getNode(i); if (!(subElem instanceof Node.TemplateText)) { continue; } // Ignore any whitespace (including spaces, carriage returns, // line feeds, and tabs, that appear at the beginning and at // the end of the body of the <jsp:attribute> action, if the // action's 'trim' attribute is set to TRUE (default). // In addition, any textual nodes in the <jsp:attribute> that // have only white space are dropped from the document, with // the exception of leading and trailing white-space-only // textual nodes in a <jsp:attribute> whose 'trim' attribute // is set to FALSE, which must be kept verbatim. if (i == 0) { if (isTrim) { ((Node.TemplateText)subElem).ltrim(); } } else if (i == subElems.size() - 1) { if (isTrim) { ((Node.TemplateText)subElem).rtrim(); } } else { if (((Node.TemplateText)subElem).isAllSpace()) { subElems.remove(subElem); } } } } else if (current instanceof Node.ScriptingElement) { checkScriptingBody((Node.ScriptingElement)current); } if ( isTagDependent(current)) { tagDependentNesting--; } if (scriptlessBodyNode != null && current.equals(scriptlessBodyNode)) { scriptlessBodyNode = null; } if (current instanceof Node.CustomTag) { String bodyType = getBodyType((Node.CustomTag) current); if (TagInfo.BODY_CONTENT_EMPTY.equalsIgnoreCase(bodyType)) { // Children - if any - must be JSP attributes Node.Nodes children = current.getBody(); if (children != null && children.size() > 0) { for (int i = 0; i < children.size(); i++) { Node child = children.getNode(i); if (!(child instanceof Node.NamedAttribute)) { throw new SAXParseException(Localizer.getMessage( "jasper.error.emptybodycontent.nonempty", current.qName), locator); } } } } } if (current.getParent() != null) { current = current.getParent(); } } /* * Receives the document locator. * * @param locator the document locator */ @Override public void setDocumentLocator(Locator locator) { this.locator = locator; } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void comment(char[] buf, int offset, int len) throws SAXException { processChars(); // Flush char buffer and remove white spaces // ignore comments in the DTD if (!inDTD) { startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); @SuppressWarnings("unused") Node unused = new Node.Comment( new String(buf, offset, len), startMark, current); } } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void startCDATA() throws SAXException { processChars(); // Flush char buffer and remove white spaces startMark = new Mark(ctxt, path, locator.getLineNumber(), locator.getColumnNumber()); } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void endCDATA() throws SAXException { processChars(); // Flush char buffer and remove white spaces } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void startEntity(String name) throws SAXException { // do nothing } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void endEntity(String name) throws SAXException { // do nothing } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void startDTD(String name, String publicId, String systemId) throws SAXException { if (!isValidating) { fatalError(new EnableDTDValidationException( "jsp.error.enable_dtd_validation", null)); } inDTD = true; } /* * See org.xml.sax.ext.LexicalHandler. */ @Override public void endDTD() throws SAXException { inDTD = false; } /* * Receives notification of a non-recoverable error. */ @Override public void fatalError(SAXParseException e) throws SAXException { throw e; } /* * Receives notification of a recoverable error. */ @Override public void error(SAXParseException e) throws SAXException { throw e; } /* * Receives notification of the start of a Namespace mapping. */ @Override public void startPrefixMapping(String prefix, String uri) throws SAXException { TagLibraryInfo taglibInfo; if (directivesOnly && !(JSP_URI.equals(uri))) { return; } try { taglibInfo = getTaglibInfo(prefix, uri); } catch (JasperException je) { throw new SAXParseException( Localizer.getMessage("jsp.error.could.not.add.taglibraries"), locator, je); } if (taglibInfo != null) { if (pageInfo.getTaglib(uri) == null) { pageInfo.addTaglib(uri, taglibInfo); } pageInfo.pushPrefixMapping(prefix, uri); } else { pageInfo.pushPrefixMapping(prefix, null); } } /* * Receives notification of the end of a Namespace mapping. */ @Override public void endPrefixMapping(String prefix) throws SAXException { if (directivesOnly) { String uri = pageInfo.getURI(prefix); if (!JSP_URI.equals(uri)) { return; } } pageInfo.popPrefixMapping(prefix); } //********************************************************************* // Private utility methods private Node parseStandardAction( String qName, String localName, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start) throws SAXException { Node node = null; if (localName.equals(ROOT_ACTION)) { if (!(current instanceof Node.Root)) { throw new SAXParseException( Localizer.getMessage("jsp.error.nested_jsproot"), locator); } node = new Node.JspRoot( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); if (isTop) { pageInfo.setHasJspRoot(true); } } else if (localName.equals(PAGE_DIRECTIVE_ACTION)) { if (isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.istagfile", localName), locator); } node = new Node.PageDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per page directive if (imports != null) { ((Node.PageDirective)node).addImport(imports); } } else if (localName.equals(INCLUDE_DIRECTIVE_ACTION)) { node = new Node.IncludeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); processIncludeDirective(nonTaglibAttrs.getValue("file"), node); } else if (localName.equals(DECLARATION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Declaration( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SCRIPTLET_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Scriptlet( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(EXPRESSION_ACTION)) { if (scriptlessBodyNode != null) { // We're nested inside a node whose body is // declared to be scriptless throw new SAXParseException( Localizer.getMessage( "jsp.error.no.scriptlets", localName), locator); } node = new Node.Expression( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(USE_BEAN_ACTION)) { node = new Node.UseBean( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(SET_PROPERTY_ACTION)) { node = new Node.SetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(GET_PROPERTY_ACTION)) { node = new Node.GetProperty( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INCLUDE_ACTION)) { node = new Node.IncludeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FORWARD_ACTION)) { node = new Node.ForwardAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAM_ACTION)) { node = new Node.ParamAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PARAMS_ACTION)) { node = new Node.ParamsAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(PLUGIN_ACTION)) { node = new Node.PlugIn( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TEXT_ACTION)) { node = new Node.JspText( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(BODY_ACTION)) { node = new Node.JspBody( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ATTRIBUTE_ACTION)) { node = new Node.NamedAttribute( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(OUTPUT_ACTION)) { node = new Node.JspOutput( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(TAG_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.TagDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); String imports = nonTaglibAttrs.getValue("import"); // There can only be one 'import' attribute per tag directive if (imports != null) { ((Node.TagDirective)node).addImport(imports); } } else if (localName.equals(ATTRIBUTE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.AttributeDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(VARIABLE_DIRECTIVE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.VariableDirective( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(INVOKE_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.InvokeAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(DOBODY_ACTION)) { if (!isTagFile) { throw new SAXParseException( Localizer.getMessage( "jsp.error.action.isnottagfile", localName), locator); } node = new Node.DoBodyAction( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(ELEMENT_ACTION)) { node = new Node.JspElement( qName, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else if (localName.equals(FALLBACK_ACTION)) { node = new Node.FallBackAction( qName, nonTaglibXmlnsAttrs, taglibAttrs, start, current); } else { throw new SAXParseException( Localizer.getMessage( "jsp.error.xml.badStandardAction", localName), locator); } return node; } /* * Checks if the XML element with the given tag name is a custom action, * and returns the corresponding Node object. */ private Node parseCustomAction( String qName, String localName, String uri, Attributes nonTaglibAttrs, Attributes nonTaglibXmlnsAttrs, Attributes taglibAttrs, Mark start, Node parent) throws SAXException { // Check if this is a user-defined (custom) tag TagLibraryInfo tagLibInfo = pageInfo.getTaglib(uri); if (tagLibInfo == null) { return null; } TagInfo tagInfo = tagLibInfo.getTag(localName); TagFileInfo tagFileInfo = tagLibInfo.getTagFile(localName); if (tagInfo == null && tagFileInfo == null) { throw new SAXParseException( Localizer.getMessage("jsp.error.xml.bad_tag", localName, uri), locator); } Class<?> tagHandlerClass = null; if (tagInfo != null) { String handlerClassName = tagInfo.getTagClassName(); try { tagHandlerClass = ctxt.getClassLoader().loadClass(handlerClassName); } catch (Exception e) { throw new SAXParseException( Localizer.getMessage("jsp.error.loadclass.taghandler", handlerClassName, qName), locator, e); } } String prefix = getPrefix(qName); Node.CustomTag ret = null; if (tagInfo != null) { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagInfo, tagHandlerClass); } else { ret = new Node.CustomTag( qName, prefix, localName, uri, nonTaglibAttrs, nonTaglibXmlnsAttrs, taglibAttrs, start, parent, tagFileInfo); } return ret; } /* * Creates the tag library associated with the given uri namespace, and * returns it. * * @param prefix The prefix of the xmlns attribute * @param uri The uri namespace (value of the xmlns attribute) * * @return The tag library associated with the given uri namespace */ private TagLibraryInfo getTaglibInfo(String prefix, String uri) throws JasperException { TagLibraryInfo result = null; if (uri.startsWith(URN_JSPTAGDIR)) { // uri (of the form "urn:jsptagdir:path") references tag file dir String tagdir = uri.substring(URN_JSPTAGDIR.length()); result = new ImplicitTagLibraryInfo( ctxt, parserController, pageInfo, prefix, tagdir, err); } else { // uri references TLD file boolean isPlainUri = false; if (uri.startsWith(URN_JSPTLD)) { // uri is of the form "urn:jsptld:path" uri = uri.substring(URN_JSPTLD.length()); } else { isPlainUri = true; } TldLocation location = ctxt.getTldLocation(uri); if (location != null || !isPlainUri) { if (ctxt.getOptions().isCaching()) { result = ctxt.getOptions().getCache().get(uri); } if (result == null) { /* * If the uri value is a plain uri, a translation error must * not be generated if the uri is not found in the taglib map. * Instead, any actions in the namespace defined by the uri * value must be treated as uninterpreted. */ result = new TagLibraryInfoImpl( ctxt, parserController, pageInfo, prefix, uri, location, err, null); if (ctxt.getOptions().isCaching()) { ctxt.getOptions().getCache().put(uri, result); } } } } return result; } /* * Ensures that the given body only contains nodes that are instances of * TemplateText. * * This check is performed only for the body of a scripting (that is: * declaration, scriptlet, or expression) element, after the end tag of a * scripting element has been reached. */ private void checkScriptingBody(Node.ScriptingElement scriptingElem) throws SAXException { Node.Nodes body = scriptingElem.getBody(); if (body != null) { int size = body.size(); for (int i = 0; i < size; i++) { Node n = body.getNode(i); if (!(n instanceof Node.TemplateText)) { String elemType = SCRIPTLET_ACTION; if (scriptingElem instanceof Node.Declaration) elemType = DECLARATION_ACTION; if (scriptingElem instanceof Node.Expression) elemType = EXPRESSION_ACTION; String msg = Localizer.getMessage( "jsp.error.parse.xml.scripting.invalid.body", elemType); throw new SAXParseException(msg, locator); } } } } /* * Parses the given file included via an include directive. * * @param fname The path to the included resource, as specified by the * 'file' attribute of the include directive * @param parent The Node representing the include directive */ private void processIncludeDirective(String fname, Node parent) throws SAXException { if (fname == null) { return; } try { parserController.parse(fname, parent, null); } catch (FileNotFoundException fnfe) { throw new SAXParseException( Localizer.getMessage("jsp.error.file.not.found", fname), locator, fnfe); } catch (Exception e) { throw new SAXParseException(e.getMessage(), locator, e); } } /* * Checks an element's given URI, qname, and attributes to see if any * of them hijack the 'jsp' prefix, that is, bind it to a namespace other * than http://java.sun.com/JSP/Page. * * @param uri The element's URI * @param qName The element's qname * @param attrs The element's attributes */ private void checkPrefixes(String uri, String qName, Attributes attrs) { checkPrefix(uri, qName); int len = attrs.getLength(); for (int i = 0; i < len; i++) { checkPrefix(attrs.getURI(i), attrs.getQName(i)); } } /* * Checks the given URI and qname to see if they hijack the 'jsp' prefix, * which would be the case if qName contained the 'jsp' prefix and * uri was different from http://java.sun.com/JSP/Page. * * @param uri The URI to check * @param qName The qname to check */ private void checkPrefix(String uri, String qName) { String prefix = getPrefix(qName); if (prefix.length() > 0) { pageInfo.addPrefix(prefix); if ("jsp".equals(prefix) && !JSP_URI.equals(uri)) { pageInfo.setIsJspPrefixHijacked(true); } } } private String getPrefix(String qName) { int index = qName.indexOf(':'); if (index != -1) { return qName.substring(0, index); } return ""; } /* * Gets SAXParser. * * @param validating Indicates whether the requested SAXParser should * be validating * @param jspDocParser The JSP document parser * * @return The SAXParser */ private static SAXParser getSAXParser( boolean validating, JspDocumentParser jspDocParser) throws Exception { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); // Preserve xmlns attributes factory.setFeature( "http://xml.org/sax/features/namespace-prefixes", true); factory.setValidating(validating); //factory.setFeature( // "http://xml.org/sax/features/validation", // validating); // Configure the parser SAXParser saxParser = factory.newSAXParser(); XMLReader xmlReader = saxParser.getXMLReader(); xmlReader.setProperty(LEXICAL_HANDLER_PROPERTY, jspDocParser); xmlReader.setErrorHandler(jspDocParser); return saxParser; } /* * Exception indicating that a DOCTYPE declaration is present, but * validation is turned off. */ private static class EnableDTDValidationException extends SAXParseException { private static final long serialVersionUID = 1L; EnableDTDValidationException(String message, Locator loc) { super(message, loc); } @Override public synchronized Throwable fillInStackTrace() { // This class does not provide a stack trace return this; } } private static String getBodyType(Node.CustomTag custom) { if (custom.getTagInfo() != null) { return custom.getTagInfo().getBodyContent(); } return custom.getTagFileInfo().getTagInfo().getBodyContent(); } private boolean isTagDependent(Node n) { if (n instanceof Node.CustomTag) { String bodyType = getBodyType((Node.CustomTag) n); return TagInfo.BODY_CONTENT_TAG_DEPENDENT.equalsIgnoreCase(bodyType); } return false; } }
55,228
Bug 55228 AbstractHttp11Processor overwrites Date header, even when set by application
null
resolved fixed
95ee699
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T15:58:31Z
2013-07-10T04:20:00Z
java/org/apache/coyote/http11/AbstractHttp11Processor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Locale; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUpgradeHandler; import org.apache.coyote.AbstractProcessor; import org.apache.coyote.ActionCode; import org.apache.coyote.AsyncContextCallback; import org.apache.coyote.RequestInfo; import org.apache.coyote.http11.filters.BufferedInputFilter; import org.apache.coyote.http11.filters.ChunkedInputFilter; import org.apache.coyote.http11.filters.ChunkedOutputFilter; import org.apache.coyote.http11.filters.GzipOutputFilter; import org.apache.coyote.http11.filters.IdentityInputFilter; import org.apache.coyote.http11.filters.IdentityOutputFilter; import org.apache.coyote.http11.filters.SavedRequestInputFilter; import org.apache.coyote.http11.filters.VoidInputFilter; import org.apache.coyote.http11.filters.VoidOutputFilter; import org.apache.juli.logging.Log; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.Ascii; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.HexUtils; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.log.UserDataHelper; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractHttp11Processor<S> extends AbstractProcessor<S> { protected abstract Log getLog(); private final UserDataHelper userDataHelper; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Input. */ protected AbstractInputBuffer<S> inputBuffer ; /** * Output. */ protected AbstractOutputBuffer<S> outputBuffer; /* * 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; /** * Error flag. */ protected boolean error = false; /** * Keep-alive. */ protected boolean keepAlive = true; /** * Flag used to indicate that the socket should be kept open (e.g. for keep * alive or send file. */ protected boolean openSocket = false; /** * Flag used to indicate that the socket should treat the next request * processed like a keep-alive connection - i.e. one where there may not be * any data to process. The initial value of this flag on entering the * process method is different for connectors that use polling (NIO / APR - * data is always expected) compared to those that use blocking (BIO - data * is only expected if the connection isn't in the keep-alive state). */ protected boolean keptAlive; /** * Flag that indicates that send file processing is in progress and that the * socket should not be returned to the poller (where a poller is used). */ protected boolean sendfileInProgress = false; /** * Flag that indicates if the request headers have been completely read. */ protected boolean readComplete = true; /** * HTTP/1.1 flag. */ protected boolean http11 = true; /** * HTTP/0.9 flag. */ protected boolean http09 = false; /** * Content delimiter for the request (if false, the connection will * be closed at the end of the request). */ protected boolean contentDelimitation = true; /** * Is there an expectation ? */ protected boolean expectation = false; /** * Comet used. */ protected boolean comet = false; /** * Regular expression that defines the restricted user agents. */ protected Pattern restrictedUserAgents = null; /** * Maximum number of Keep-Alive requests to honor. */ protected int maxKeepAliveRequests = -1; /** * The number of seconds Tomcat will wait for a subsequent request * before closing the connection. */ protected int keepAliveTimeout = -1; /** * Maximum timeout on uploads. 5 minutes as in Apache HTTPD server. */ protected int connectionUploadTimeout = 300000; /** * Flag to disable setting a different time-out on uploads. */ protected boolean disableUploadTimeout = false; /** * Allowed compression level. */ protected int compressionLevel = 0; /** * Minimum content size to make compression. */ protected int compressionMinSize = 2048; /** * Max saved post size. */ protected int maxSavePostSize = 4 * 1024; /** * Regular expression that defines the user agents to not use gzip with */ protected Pattern noCompressionUserAgents = null; /** * List of MIMES which could be gzipped */ protected String[] compressableMimeTypes = { "text/html", "text/xml", "text/plain" }; /** * Host name (used to avoid useless B2C conversion on the host name). */ protected char[] hostNameC = new char[0]; /** * Allow a customized the server header for the tin-foil hat folks. */ protected String server = null; /** * Instance of the new protocol to use after the HTTP connection has been * upgraded. */ protected HttpUpgradeHandler httpUpgradeHandler = null; public AbstractHttp11Processor(AbstractEndpoint endpoint) { super(endpoint); userDataHelper = new UserDataHelper(getLog()); } /** * Set compression level. */ public void setCompression(String compression) { if (compression.equals("on")) { this.compressionLevel = 1; } else if (compression.equals("force")) { this.compressionLevel = 2; } else if (compression.equals("off")) { this.compressionLevel = 0; } else { try { // Try to parse compression as an int, which would give the // minimum compression size compressionMinSize = Integer.parseInt(compression); this.compressionLevel = 1; } catch (Exception e) { this.compressionLevel = 0; } } } /** * Set Minimum size to trigger compression. */ public void setCompressionMinSize(int compressionMinSize) { this.compressionMinSize = compressionMinSize; } /** * Set no compression user agent pattern. Regular expression as supported * by {@link Pattern}. * * ie: "gorilla|desesplorer|tigrus" */ public void setNoCompressionUserAgents(String noCompressionUserAgents) { if (noCompressionUserAgents == null || noCompressionUserAgents.length() == 0) { this.noCompressionUserAgents = null; } else { this.noCompressionUserAgents = Pattern.compile(noCompressionUserAgents); } } /** * Add a mime-type which will be compressible * The mime-type String will be exactly matched * in the response mime-type header . * * @param mimeType mime-type string */ public void addCompressableMimeType(String mimeType) { compressableMimeTypes = addStringArray(compressableMimeTypes, mimeType); } /** * Set compressible mime-type list (this method is best when used with * a large number of connectors, where it would be better to have all of * them referenced a single array). */ public void setCompressableMimeTypes(String[] compressableMimeTypes) { this.compressableMimeTypes = compressableMimeTypes; } /** * Set compressable mime-type list * List contains users agents separated by ',' : * * ie: "text/html,text/xml,text/plain" */ public void setCompressableMimeTypes(String compressableMimeTypes) { if (compressableMimeTypes != null) { this.compressableMimeTypes = null; StringTokenizer st = new StringTokenizer(compressableMimeTypes, ","); while (st.hasMoreTokens()) { addCompressableMimeType(st.nextToken().trim()); } } } /** * Return compression level. */ public String getCompression() { switch (compressionLevel) { case 0: return "off"; case 1: return "on"; case 2: return "force"; } return "off"; } /** * General use method * * @param sArray the StringArray * @param value string */ private String[] addStringArray(String sArray[], String value) { String[] result = null; if (sArray == null) { result = new String[1]; result[0] = value; } else { result = new String[sArray.length + 1]; for (int i = 0; i < sArray.length; i++) { result[i] = sArray[i]; } result[sArray.length] = value; } return result; } /** * Checks if any entry in the string array starts with the specified value * * @param sArray the StringArray * @param value string */ private boolean startsWithStringArray(String sArray[], String value) { if (value == null) { return false; } for (int i = 0; i < sArray.length; i++) { if (value.startsWith(sArray[i])) { return true; } } return false; } /** * Set restricted user agent list (which will downgrade the connector * to HTTP/1.0 mode). Regular expression as supported by {@link Pattern}. * * ie: "gorilla|desesplorer|tigrus" */ public void setRestrictedUserAgents(String restrictedUserAgents) { if (restrictedUserAgents == null || restrictedUserAgents.length() == 0) { this.restrictedUserAgents = null; } else { this.restrictedUserAgents = Pattern.compile(restrictedUserAgents); } } /** * Set the maximum number of Keep-Alive requests to honor. * This is to safeguard from DoS attacks. Setting to a negative * value disables the check. */ public void setMaxKeepAliveRequests(int mkar) { maxKeepAliveRequests = mkar; } /** * Return the number of Keep-Alive requests that we will honor. */ public int getMaxKeepAliveRequests() { return maxKeepAliveRequests; } /** * Set the Keep-Alive timeout. */ public void setKeepAliveTimeout(int timeout) { keepAliveTimeout = timeout; } /** * Return the number Keep-Alive timeout. */ public int getKeepAliveTimeout() { return keepAliveTimeout; } /** * Set the maximum size of a POST which will be buffered in SSL mode. */ public void setMaxSavePostSize(int msps) { maxSavePostSize = msps; } /** * Return the maximum size of a POST which will be buffered in SSL mode. */ public int getMaxSavePostSize() { return maxSavePostSize; } /** * Set the flag to control upload time-outs. */ public void setDisableUploadTimeout(boolean isDisabled) { disableUploadTimeout = isDisabled; } /** * Get the flag that controls upload time-outs. */ public boolean getDisableUploadTimeout() { return disableUploadTimeout; } /** * Set the socket buffer flag. */ public void setSocketBuffer(int socketBuffer) { outputBuffer.setSocketBuffer(socketBuffer); } /** * Get the socket buffer flag. */ public int getSocketBuffer() { return outputBuffer.getSocketBuffer(); } /** * Set the upload timeout. */ public void setConnectionUploadTimeout(int timeout) { connectionUploadTimeout = timeout ; } /** * Get the upload timeout. */ public int getConnectionUploadTimeout() { return connectionUploadTimeout; } /** * Set the server header name. */ public void setServer( String server ) { if (server==null || server.equals("")) { this.server = null; } else { this.server = server; } } /** * Get the server header name. */ public String getServer() { return server; } /** * Check if the resource could be compressed, if the client supports it. */ private boolean isCompressable() { // Check if content is not already gzipped MessageBytes contentEncodingMB = response.getMimeHeaders().getValue("Content-Encoding"); if ((contentEncodingMB != null) && (contentEncodingMB.indexOf("gzip") != -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check if sufficient length to trigger the compression long contentLength = response.getContentLengthLong(); if ((contentLength == -1) || (contentLength > compressionMinSize)) { // Check for compatible MIME-TYPE if (compressableMimeTypes != null) { return (startsWithStringArray(compressableMimeTypes, response.getContentType())); } } return false; } /** * Check if compression should be used for this resource. Already checked * that the resource could be compressed if the client supports it. */ private boolean useCompression() { // Check if browser support gzip encoding MessageBytes acceptEncodingMB = request.getMimeHeaders().getValue("accept-encoding"); if ((acceptEncodingMB == null) || (acceptEncodingMB.indexOf("gzip") == -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check for incompatible Browser if (noCompressionUserAgents != null) { MessageBytes userAgentValueMB = request.getMimeHeaders().getValue("user-agent"); if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (noCompressionUserAgents != null && noCompressionUserAgents.matcher(userAgentValue).matches()) { return false; } } } return true; } /** * Specialized utility method: find a sequence of lower case bytes inside * a ByteChunk. */ protected int findBytes(ByteChunk bc, byte[] b) { byte first = b[0]; byte[] buff = bc.getBuffer(); int start = bc.getStart(); int end = bc.getEnd(); // Look for first char int srcEnd = b.length; for (int i = start; i <= (end - srcEnd); i++) { if (Ascii.toLower(buff[i]) != first) { continue; } // found first char, now look for a match int myPos = i+1; for (int srcPos = 1; srcPos < srcEnd;) { if (Ascii.toLower(buff[myPos++]) != b[srcPos++]) { break; } if (srcPos == srcEnd) { return i - start; // found it } } } return -1; } /** * Determine if we must drop the connection because of the HTTP status * code. Use the same list of codes as Apache/httpd. */ protected 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 */; } /** * Allows the super class to set the socket wrapper being used. */ protected abstract void setSocketWrapper(SocketWrapper<S> socketWrapper); /** * Exposes input buffer to super class to allow better code re-use. * @return The input buffer used by the processor. */ protected abstract AbstractInputBuffer<S> getInputBuffer(); /** * Exposes output buffer to super class to allow better code re-use. * @return The output buffer used by the processor. */ protected abstract AbstractOutputBuffer<S> getOutputBuffer(); /** * Initialize standard input and output filters. */ protected void initializeFilters(int maxTrailerSize) { // Create and add the identity filters. getInputBuffer().addFilter(new IdentityInputFilter()); getOutputBuffer().addFilter(new IdentityOutputFilter()); // Create and add the chunked filters. getInputBuffer().addFilter(new ChunkedInputFilter(maxTrailerSize)); getOutputBuffer().addFilter(new ChunkedOutputFilter()); // Create and add the void filters. getInputBuffer().addFilter(new VoidInputFilter()); getOutputBuffer().addFilter(new VoidOutputFilter()); // Create and add buffered input filter getInputBuffer().addFilter(new BufferedInputFilter()); // Create and add the chunked filters. //getInputBuffer().addFilter(new GzipInputFilter()); getOutputBuffer().addFilter(new GzipOutputFilter()); pluggableFilterIndex = getInputBuffer().getFilters().length; } /** * Add an input filter to the current request. * * @return false if the encoding was not found (which would mean it is * unsupported) */ protected boolean addInputFilter(InputFilter[] inputFilters, String encodingName) { if (encodingName.equals("identity")) { // Skip } else if (encodingName.equals("chunked")) { getInputBuffer().addActiveFilter (inputFilters[Constants.CHUNKED_FILTER]); contentDelimitation = true; } else { for (int i = pluggableFilterIndex; i < inputFilters.length; i++) { if (inputFilters[i].getEncodingName() .toString().equals(encodingName)) { getInputBuffer().addActiveFilter(inputFilters[i]); return true; } } return false; } return true; } /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override public final void action(ActionCode actionCode, Object param) { if (actionCode == ActionCode.CLOSE) { // End the processing of the current request try { getOutputBuffer().endRequest(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.COMMIT) { // Commit current response if (response.isCommitted()) { return; } // Validate and write response headers try { prepareResponse(); getOutputBuffer().commit(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.ACK) { // Acknowledge request // Send a 100 status back if it makes sense (response not committed // yet, and client specified an expectation for 100-continue) if ((response.isCommitted()) || !expectation) { return; } getInputBuffer().setSwallowInput(true); try { getOutputBuffer().sendAck(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.CLIENT_FLUSH) { try { getOutputBuffer().flush(); } catch (IOException e) { // Set error flag error = true; response.setErrorException(e); } } else if (actionCode == ActionCode.DISABLE_SWALLOW_INPUT) { // Do not swallow request input but // make sure we are closing the connection error = true; getInputBuffer().setSwallowInput(false); } else if (actionCode == ActionCode.RESET) { // Reset response // Note: This must be called before the response is committed getOutputBuffer().reset(); } else if (actionCode == ActionCode.REQ_SET_BODY_REPLAY) { ByteChunk body = (ByteChunk) param; InputFilter savedBody = new SavedRequestInputFilter(body); savedBody.setRequest(request); AbstractInputBuffer<S> internalBuffer = (AbstractInputBuffer<S>) request.getInputBuffer(); internalBuffer.addActiveFilter(savedBody); } else if (actionCode == ActionCode.ASYNC_START) { asyncStateMachine.asyncStart((AsyncContextCallback) param); } else if (actionCode == ActionCode.ASYNC_DISPATCHED) { asyncStateMachine.asyncDispatched(); } else if (actionCode == ActionCode.ASYNC_TIMEOUT) { AtomicBoolean result = (AtomicBoolean) param; result.set(asyncStateMachine.asyncTimeout()); } else if (actionCode == ActionCode.ASYNC_RUN) { asyncStateMachine.asyncRun((Runnable) param); } else if (actionCode == ActionCode.ASYNC_ERROR) { asyncStateMachine.asyncError(); } else if (actionCode == ActionCode.ASYNC_IS_STARTED) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted()); } else if (actionCode == ActionCode.ASYNC_IS_DISPATCHING) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching()); } else if (actionCode == ActionCode.ASYNC_IS_ASYNC) { ((AtomicBoolean) param).set(asyncStateMachine.isAsync()); } else if (actionCode == ActionCode.ASYNC_IS_TIMINGOUT) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut()); } else if (actionCode == ActionCode.ASYNC_IS_ERROR) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError()); } else if (actionCode == ActionCode.AVAILABLE) { request.setAvailable(inputBuffer.available()); } else if (actionCode == ActionCode.NB_WRITE_INTEREST) { AtomicBoolean isReady = (AtomicBoolean)param; try { isReady.set(getOutputBuffer().isReady()); } catch (IOException e) { getLog().debug("isReady() failed", e); error = true; } } else if (actionCode == ActionCode.NB_READ_INTEREST) { registerForEvent(true, false); } else if (actionCode == ActionCode.UPGRADE) { httpUpgradeHandler = (HttpUpgradeHandler) param; // Stop further HTTP output getOutputBuffer().finished = true; } else if (actionCode == ActionCode.REQUEST_BODY_FULLY_READ) { AtomicBoolean result = (AtomicBoolean) param; result.set(getInputBuffer().isFinished()); } else { actionInternal(actionCode, param); } } abstract void actionInternal(ActionCode actionCode, Object param); /** * Processors (currently only HTTP BIO) may elect to disable HTTP keep-alive * in some circumstances. This method allows the processor implementation to * determine if keep-alive should be disabled or not. */ protected abstract boolean disableKeepAlive(); /** * Configures the timeout to be used for reading the request line. */ protected abstract void setRequestLineReadTimeout() throws IOException; /** * Defines how a connector handles an incomplete request line read. * * @return <code>true</code> if the processor should break out of the * processing loop, otherwise <code>false</code>. */ protected abstract boolean handleIncompleteRequestLineRead(); /** * Set the socket timeout. */ protected abstract void setSocketTimeout(int timeout) throws IOException; /** * Process pipelined HTTP requests using the specified input and output * streams. * * @param socketWrapper Socket from which the HTTP requests will be read * and the HTTP responses will be written. * * @throws IOException error during an I/O operation */ @Override public SocketState process(SocketWrapper<S> socketWrapper) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the I/O setSocketWrapper(socketWrapper); getInputBuffer().init(socketWrapper, endpoint); getOutputBuffer().init(socketWrapper, endpoint); // Flags error = false; keepAlive = true; comet = false; openSocket = false; sendfileInProgress = false; readComplete = true; if (endpoint.getUsePolling()) { keptAlive = false; } else { keptAlive = socketWrapper.isKeptAlive(); } if (disableKeepAlive()) { socketWrapper.setKeepAliveLeft(0); } while (!error && keepAlive && !comet && !isAsync() && httpUpgradeHandler == null && !endpoint.isPaused()) { // Parsing the request header try { setRequestLineReadTimeout(); if (!getInputBuffer().parseRequestLine(keptAlive)) { if (handleIncompleteRequestLineRead()) { break; } } if (endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); error = true; } else { // Make sure that connectors that are non-blocking during // header processing (NIO) only set the start time the first // time a request is processed. if (request.getStartTime() < 0) { request.setStartTime(System.currentTimeMillis()); } keptAlive = true; // Set this every time in case limit has been changed via JMX request.getMimeHeaders().setLimit(endpoint.getMaxHeaderCount()); // Currently only NIO will ever return false here if (!getInputBuffer().parseHeaders()) { // We've read part of the request, don't recycle it // instead associate it with the socket openSocket = true; readComplete = false; break; } if (!disableUploadTimeout) { setSocketTimeout(connectionUploadTimeout); } } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); UserDataHelper.Mode logMode = userDataHelper.getNextMode(); if (logMode != null) { String message = sm.getString( "http11processor.header.parse"); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "http11processor.fallToDebug"); //$FALL-THROUGH$ case INFO: getLog().info(message); break; case DEBUG: getLog().debug(message); } } // 400 - Bad Request response.setStatus(400); getAdapter().log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); getAdapter().log(request, response, 0); error = true; } } if (maxKeepAliveRequests == 1) { keepAlive = false; } else if (maxKeepAliveRequests > 0 && socketWrapper.decrementKeepAlive() <= 0) { keepAlive = false; } // Process the request in the adapter if (!error) { try { 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 // 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 && !error) { // Avoid checking twice. error = response.getErrorException() != null || (!isAsync() && statusDropsConnection(response.getStatus())); } setCometTimeouts(socketWrapper); } catch (InterruptedIOException e) { error = true; } catch (HeadersTooLargeException e) { error = true; // The response should not have been committed but check it // anyway to be safe if (!response.isCommitted()) { response.reset(); response.setStatus(500); response.setHeader("Connection", "close"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); error = true; } } // Finish the handling of the request rp.setStage(org.apache.coyote.Constants.STAGE_ENDINPUT); if (!isAsync() && !comet) { if (error) { // If we know we are closing the connection, don't drain // input. This way uploading a 100GB file doesn't tie up the // thread if the servlet has rejected it. getInputBuffer().setSwallowInput(false); } endRequest(); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDOUTPUT); // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); if (!isAsync() && !comet || error) { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); } if (!disableUploadTimeout) { if(endpoint.getSoTimeout() > 0) { setSocketTimeout(endpoint.getSoTimeout()); } else { setSocketTimeout(0); } } rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); if (breakKeepAliveLoop(socketWrapper)) { break; } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || endpoint.isPaused()) { return SocketState.CLOSED; } else if (isAsync() || comet) { return SocketState.LONG; } else if (isUpgrade()) { return SocketState.UPGRADING; } else { if (sendfileInProgress) { return SocketState.SENDFILE; } else { if (openSocket) { if (readComplete) { return SocketState.OPEN; } else { return SocketState.LONG; } } else { return SocketState.CLOSED; } } } } /** * Regsiter the socket for the specified events. * * @param read Register the socket for read events * @param write Regsiter the socket for write events */ protected abstract void registerForEvent(boolean read, boolean write); /** * After reading the request headers, we have to setup the request filters. */ protected void prepareRequest() { http11 = true; http09 = false; contentDelimitation = false; expectation = false; prepareRequestInternal(); if (endpoint.isSSLEnabled()) { request.scheme().setString("https"); } MessageBytes protocolMB = request.protocol(); if (protocolMB.equals(Constants.HTTP_11)) { http11 = true; protocolMB.setString(Constants.HTTP_11); } else if (protocolMB.equals(Constants.HTTP_10)) { http11 = false; keepAlive = false; protocolMB.setString(Constants.HTTP_10); } else if (protocolMB.equals("")) { // HTTP/0.9 http09 = true; http11 = false; keepAlive = false; } else { // Unsupported protocol http11 = false; error = true; // Send 505; Unsupported HTTP version if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " Unsupported HTTP version \""+protocolMB+"\""); } response.setStatus(505); } MessageBytes methodMB = request.method(); if (methodMB.equals(Constants.GET)) { methodMB.setString(Constants.GET); } else if (methodMB.equals(Constants.POST)) { methodMB.setString(Constants.POST); } MimeHeaders headers = request.getMimeHeaders(); // Check connection header MessageBytes connectionValueMB = headers.getValue(Constants.CONNECTION); if (connectionValueMB != null) { ByteChunk connectionValueBC = connectionValueMB.getByteChunk(); if (findBytes(connectionValueBC, Constants.CLOSE_BYTES) != -1) { keepAlive = false; } else if (findBytes(connectionValueBC, Constants.KEEPALIVE_BYTES) != -1) { keepAlive = true; } } MessageBytes expectMB = null; if (http11) { expectMB = headers.getValue("expect"); } if ((expectMB != null) && (expectMB.indexOfIgnoreCase("100-continue", 0) != -1)) { getInputBuffer().setSwallowInput(false); expectation = true; } // Check user-agent header if ((restrictedUserAgents != null) && ((http11) || (keepAlive))) { MessageBytes userAgentValueMB = headers.getValue("user-agent"); // Check in the restricted list, and adjust the http11 // and keepAlive flags accordingly if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (restrictedUserAgents != null && restrictedUserAgents.matcher(userAgentValue).matches()) { http11 = false; keepAlive = false; } } } // Check for a full URI (including protocol://host:port/) ByteChunk uriBC = request.requestURI().getByteChunk(); if (uriBC.startsWithIgnoreCase("http", 0)) { int pos = uriBC.indexOf("://", 0, 3, 4); int uriBCStart = uriBC.getStart(); int slashPos = -1; if (pos != -1) { byte[] uriB = uriBC.getBytes(); slashPos = uriBC.indexOf('/', pos + 3); if (slashPos == -1) { slashPos = uriBC.getLength(); // Set URI as "/" request.requestURI().setBytes (uriB, uriBCStart + pos + 1, 1); } else { request.requestURI().setBytes (uriB, uriBCStart + slashPos, uriBC.getLength() - slashPos); } MessageBytes hostMB = headers.setValue("host"); hostMB.setBytes(uriB, uriBCStart + pos + 3, slashPos - pos - 3); } } // Input filter setup InputFilter[] inputFilters = getInputBuffer().getFilters(); // Parse transfer-encoding header MessageBytes transferEncodingValueMB = null; if (http11) { transferEncodingValueMB = headers.getValue("transfer-encoding"); } if (transferEncodingValueMB != null) { String transferEncodingValue = transferEncodingValueMB.toString(); // Parse the comma separated list. "identity" codings are ignored int startPos = 0; int commaPos = transferEncodingValue.indexOf(','); String encodingName = null; while (commaPos != -1) { encodingName = transferEncodingValue.substring (startPos, commaPos).toLowerCase(Locale.ENGLISH).trim(); if (!addInputFilter(inputFilters, encodingName)) { // Unsupported transfer encoding error = true; // 501 - Unimplemented response.setStatus(501); } startPos = commaPos + 1; commaPos = transferEncodingValue.indexOf(',', startPos); } encodingName = transferEncodingValue.substring(startPos) .toLowerCase(Locale.ENGLISH).trim(); if (!addInputFilter(inputFilters, encodingName)) { // Unsupported transfer encoding error = true; // 501 - Unimplemented if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " Unsupported transfer encoding \""+encodingName+"\""); } response.setStatus(501); } } // Parse content-length header long contentLength = request.getContentLengthLong(); if (contentLength >= 0 && !contentDelimitation) { getInputBuffer().addActiveFilter (inputFilters[Constants.IDENTITY_FILTER]); contentDelimitation = true; } MessageBytes valueMB = headers.getValue("host"); // Check host header if (http11 && (valueMB == null)) { error = true; // 400 - Bad request if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " host header missing"); } response.setStatus(400); } parseHost(valueMB); if (!contentDelimitation) { // If there's no content length // (broken HTTP/1.0 or HTTP/1.1), assume // the client is not broken and didn't send a body getInputBuffer().addActiveFilter (inputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } if (error) { getAdapter().log(request, response, 0); } } /** * Connector implementation specific request preparation. Ideally, this will * go away in the future. */ protected abstract void prepareRequestInternal(); /** * When committing the response, we have to validate the set of headers, as * well as setup the response filters. */ private void prepareResponse() { boolean entityBody = true; contentDelimitation = false; OutputFilter[] outputFilters = getOutputBuffer().getFilters(); if (http09 == true) { // HTTP/0.9 getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); return; } int statusCode = response.getStatus(); if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304) { // No entity body getOutputBuffer().addActiveFilter (outputFilters[Constants.VOID_FILTER]); entityBody = false; contentDelimitation = true; } MessageBytes methodMB = request.method(); if (methodMB.equals("HEAD")) { // No entity body getOutputBuffer().addActiveFilter (outputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } // Sendfile support boolean sendingWithSendfile = false; if (getEndpoint().getUseSendfile()) { sendingWithSendfile = prepareSendfile(outputFilters); } // Check for compression boolean isCompressable = false; boolean useCompression = false; if (entityBody && (compressionLevel > 0) && !sendingWithSendfile) { isCompressable = isCompressable(); if (isCompressable) { useCompression = useCompression(); } // Change content-length to -1 to force chunking if (useCompression) { response.setContentLength(-1); } } MimeHeaders headers = response.getMimeHeaders(); if (!entityBody) { response.setContentLength(-1); } // A SC_NO_CONTENT response may include entity headers if (entityBody || statusCode == HttpServletResponse.SC_NO_CONTENT) { String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language") .setString(contentLanguage); } } long contentLength = response.getContentLengthLong(); boolean connectionClosePresent = false; if (contentLength != -1) { headers.setValue("Content-Length").setLong(contentLength); getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); contentDelimitation = true; } else { // If the response code supports an entity body and we're on // HTTP 1.1 then we chunk unless we have a Connection: close header connectionClosePresent = isConnectionClose(headers); if (entityBody && http11 && !connectionClosePresent) { getOutputBuffer().addActiveFilter (outputFilters[Constants.CHUNKED_FILTER]); contentDelimitation = true; headers.addValue(Constants.TRANSFERENCODING).setString(Constants.CHUNKED); } else { getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); } } if (useCompression) { getOutputBuffer().addActiveFilter(outputFilters[Constants.GZIP_FILTER]); headers.setValue("Content-Encoding").setString("gzip"); } // If it might be compressed, set the Vary header if (isCompressable) { // Make Proxies happy via Vary (from mod_deflate) MessageBytes vary = headers.getValue("Vary"); if (vary == null) { // Add a new Vary header headers.setValue("Vary").setString("Accept-Encoding"); } else if (vary.equals("*")) { // No action required } else { // Merge into current header headers.setValue("Vary").setString( vary.getString() + ",Accept-Encoding"); } } // Add date header headers.setValue("Date").setString(FastHttpDateFormat.getCurrentDate()); // FIXME: Add transfer encoding header if ((entityBody) && (!contentDelimitation)) { // Mark as close the connection after the request, and add the // connection: close header keepAlive = false; } // If we know that the request is bad this early, add the // Connection: close header. keepAlive = keepAlive && !statusDropsConnection(statusCode); if (!keepAlive) { // Avoid adding the close header twice if (!connectionClosePresent) { headers.addValue(Constants.CONNECTION).setString( Constants.CLOSE); } } else if (!http11 && !error) { headers.addValue(Constants.CONNECTION).setString(Constants.KEEPALIVE); } // Build the response header getOutputBuffer().sendStatus(); // Add server header if (server != null) { // Always overrides anything the app might set headers.setValue("Server").setString(server); } else if (headers.getValue("Server") == null) { // If app didn't set the header, use the default getOutputBuffer().write(Constants.SERVER_BYTES); } int size = headers.size(); for (int i = 0; i < size; i++) { getOutputBuffer().sendHeader(headers.getName(i), headers.getValue(i)); } getOutputBuffer().endHeaders(); } private boolean isConnectionClose(MimeHeaders headers) { MessageBytes connection = headers.getValue(Constants.CONNECTION); if (connection == null) { return false; } return connection.equals(Constants.CLOSE); } abstract boolean prepareSendfile(OutputFilter[] outputFilters); /** * Parse host. */ protected void parseHost(MessageBytes valueMB) { if (valueMB == null || valueMB.isNull()) { // HTTP/1.0 // If no host header, use the port info from the endpoint // The host will be obtained lazily from the socket if required // using ActionCode#REQ_LOCAL_NAME_ATTRIBUTE request.setServerPort(endpoint.getPort()); return; } ByteChunk valueBC = valueMB.getByteChunk(); byte[] valueB = valueBC.getBytes(); int valueL = valueBC.getLength(); int valueS = valueBC.getStart(); int colonPos = -1; if (hostNameC.length < valueL) { hostNameC = new char[valueL]; } boolean ipv6 = (valueB[valueS] == '['); boolean bracketClosed = false; for (int i = 0; i < valueL; i++) { char b = (char) valueB[i + valueS]; hostNameC[i] = b; if (b == ']') { bracketClosed = true; } else if (b == ':') { if (!ipv6 || bracketClosed) { colonPos = i; break; } } } if (colonPos < 0) { if (!endpoint.isSSLEnabled()) { // 80 - Default HTTP port request.setServerPort(80); } else { // 443 - Default HTTPS port request.setServerPort(443); } request.serverName().setChars(hostNameC, 0, valueL); } else { request.serverName().setChars(hostNameC, 0, colonPos); int port = 0; int mult = 1; for (int i = valueL - 1; i > colonPos; i--) { int charValue = HexUtils.getDec(valueB[i + valueS]); if (charValue == -1 || charValue > 9) { // Invalid character error = true; // 400 - Bad request response.setStatus(400); break; } port = port + (charValue * mult); mult = 10 * mult; } request.setServerPort(port); } } @Override public SocketState asyncDispatch(SocketStatus status) { if (status == SocketStatus.OPEN_WRITE) { try { asyncStateMachine.asyncOperation(); try { if (outputBuffer.hasDataToWrite()) { if (outputBuffer.flushBuffer(false)) { // There is data to write but go via Response to // maintain a consistent view of non-blocking state response.checkRegisterForWrite(true); return SocketState.LONG; } } } catch (IOException x) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to write async data.",x); } status = SocketStatus.ASYNC_WRITE_ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, x); } } catch (IllegalStateException x) { registerForEvent(false, true); } } else if (status == SocketStatus.OPEN_READ && request.getReadListener() != null) { try { try { if (inputBuffer.nbRead() > 0) { asyncStateMachine.asyncOperation(); } } catch (IOException x) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to read async data.",x); } status = SocketStatus.ASYNC_READ_ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, x); } } catch (IllegalStateException x) { registerForEvent(true, false); } } RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !getAdapter().asyncDispatch(request, response, status); resetTimeouts(); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; } finally { if (error) { // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (isAsync()) { return SocketState.LONG; } else { if (!keepAlive) { return SocketState.CLOSED; } else { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); return SocketState.OPEN; } } } @Override public boolean isComet() { return comet; } @Override public boolean isUpgrade() { return httpUpgradeHandler != null; } @Override public SocketState upgradeDispatch(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("http11Processor.upgrade")); } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { return httpUpgradeHandler; } /** * Provides a mechanism for those connector implementations (currently only * NIO) that need to reset timeouts from Async timeouts to standard HTTP * timeouts once async processing completes. */ protected abstract void resetTimeouts(); /** * Provides a mechanism for those connectors (currently only NIO) that need * that need to set comet timeouts. */ protected abstract void setCometTimeouts(SocketWrapper<S> socketWrapper); public void endRequest() { // Finish the handling of the request try { getInputBuffer().endRequest(); } catch (IOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; } try { getOutputBuffer().endRequest(); } catch (IOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; } } /** * Checks to see if the keep-alive loop should be broken, performing any * processing (e.g. sendfile handling) that may have an impact on whether * or not the keep-alive loop should be broken. * @return true if the keep-alive loop should be broken */ protected abstract boolean breakKeepAliveLoop( SocketWrapper<S> socketWrapper); @Override public final void recycle(boolean isSocketClosing) { if (getInputBuffer() != null) { getInputBuffer().recycle(); } if (getOutputBuffer() != null) { getOutputBuffer().recycle(); } if (asyncStateMachine != null) { asyncStateMachine.recycle(); } httpUpgradeHandler = null; comet = false; recycleInternal(); } protected abstract void recycleInternal(); }
55,238
Bug 55238 [websocket] NPE in clearHandler(WsRemoteEndpointImplServer.java:156)
null
resolved fixed
4758796
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T16:14:59Z
2013-07-11T10:53:20Z
java/org/apache/tomcat/websocket/server/WsRemoteEndpointImplServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket.server; import java.io.EOFException; import java.io.IOException; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import javax.servlet.ServletOutputStream; import javax.websocket.SendHandler; import javax.websocket.SendResult; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.WsRemoteEndpointImplBase; /** * This is the server side {@link javax.websocket.RemoteEndpoint} implementation * - i.e. what the server uses to send data to the client. Communication is over * a {@link ServletOutputStream}. */ public class WsRemoteEndpointImplServer extends WsRemoteEndpointImplBase { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final Log log = LogFactory.getLog(WsHttpUpgradeHandler.class); private final ServletOutputStream sos; private final WsWriteTimeout wsWriteTimeout; private volatile SendHandler handler = null; private volatile ByteBuffer[] buffers = null; private volatile long timeoutExpiry = -1; private volatile boolean close; public WsRemoteEndpointImplServer(ServletOutputStream sos, WsServerContainer serverContainer) { this.sos = sos; this.wsWriteTimeout = serverContainer.getTimeout(); } @Override protected final boolean isMasked() { return false; } @Override protected void doWrite(SendHandler handler, ByteBuffer... buffers) { this.handler = handler; this.buffers = buffers; onWritePossible(); } public void onWritePossible() { boolean complete = true; try { // If this is false there will be a call back when it is true while (sos.isReady()) { complete = true; for (ByteBuffer buffer : buffers) { if (buffer.hasRemaining()) { complete = false; sos.write(buffer.array(), buffer.arrayOffset(), buffer.limit()); buffer.position(buffer.limit()); break; } } if (complete) { wsWriteTimeout.unregister(this); if (close) { close(); } // Setting the result marks this (partial) message as // complete which means the next one may be sent which // could update the value of the handler. Therefore, keep a // local copy before signalling the end of the (partial) // message. clearHandler(null); break; } } } catch (IOException ioe) { wsWriteTimeout.unregister(this); close(); clearHandler(ioe); } if (!complete) { // Async write is in progress long timeout = getSendTimeout(); if (timeout > 0) { // Register with timeout thread timeoutExpiry = timeout + System.currentTimeMillis(); wsWriteTimeout.register(this); } } } @Override protected void doClose() { if (handler != null) { clearHandler(new EOFException()); } try { sos.close(); } catch (IOException e) { if (log.isInfoEnabled()) { log.info(sm.getString("wsRemoteEndpointServer.closeFailed"), e); } } wsWriteTimeout.unregister(this); } protected long getTimeoutExpiry() { return timeoutExpiry; } protected void onTimeout() { clearHandler(new SocketTimeoutException()); close(); } private void clearHandler(Throwable t) { SendHandler sh = handler; handler = null; if (t == null) { sh.onResult(new SendResult()); } else { sh.onResult(new SendResult(t)); } } }
55,240
Bug 55240 [websocket] SOE in NioEndpoint
null
resolved fixed
68f6f6f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T18:08:17Z
2013-07-11T16:26:40Z
java/org/apache/coyote/http11/upgrade/AbstractProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.IOException; import java.util.concurrent.Executor; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; import org.apache.coyote.Processor; import org.apache.coyote.Request; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractProcessor<S> implements Processor<S>, WebConnection { protected static final StringManager sm = StringManager.getManager(Constants.Package); private final HttpUpgradeHandler httpUpgradeHandler; private final AbstractServletInputStream upgradeServletInputStream; private final AbstractServletOutputStream upgradeServletOutputStream; protected AbstractProcessor (HttpUpgradeHandler httpUpgradeHandler, AbstractServletInputStream upgradeServletInputStream, AbstractServletOutputStream upgradeServletOutputStream) { this.httpUpgradeHandler = httpUpgradeHandler; this.upgradeServletInputStream = upgradeServletInputStream; this.upgradeServletOutputStream = upgradeServletOutputStream; } // --------------------------------------------------- AutoCloseable methods @Override public void close() throws Exception { upgradeServletInputStream.close(); upgradeServletOutputStream.close(); } // --------------------------------------------------- WebConnection methods @Override public ServletInputStream getInputStream() throws IOException { return upgradeServletInputStream; } @Override public ServletOutputStream getOutputStream() throws IOException { return upgradeServletOutputStream; } // ------------------------------------------- Implemented Processor methods @Override public final boolean isUpgrade() { return true; } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { return httpUpgradeHandler; } @Override public final SocketState upgradeDispatch(SocketStatus status) throws IOException { if (status == SocketStatus.OPEN_READ) { upgradeServletInputStream.onDataAvailable(); } else if (status == SocketStatus.OPEN_WRITE) { upgradeServletOutputStream.onWritePossible(); } else { // Unexpected state return SocketState.CLOSED; } if (upgradeServletInputStream.isCloseRequired() || upgradeServletOutputStream.isCloseRequired()) { return SocketState.CLOSED; } return SocketState.UPGRADED; } @Override public final void recycle(boolean socketClosing) { // Currently a NO-OP as upgrade processors are not recycled. } // ---------------------------- Processor methods that are NO-OP for upgrade @Override public final Executor getExecutor() { return null; } @Override public final SocketState process(SocketWrapper<S> socketWrapper) throws IOException { return null; } @Override public final SocketState event(SocketStatus status) throws IOException { return null; } @Override public final SocketState asyncDispatch(SocketStatus status) { return null; } @Override public final SocketState asyncPostProcess() { return null; } @Override public final boolean isComet() { return false; } @Override public final boolean isAsync() { return false; } @Override public final Request getRequest() { return null; } @Override public final void setSslSupport(SSLSupport sslSupport) { // NOOP } }
55,240
Bug 55240 [websocket] SOE in NioEndpoint
null
resolved fixed
68f6f6f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T18:08:17Z
2013-07-11T16:26:40Z
java/org/apache/coyote/http11/upgrade/AprProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import javax.servlet.http.HttpUpgradeHandler; import org.apache.tomcat.jni.Socket; import org.apache.tomcat.util.net.AprEndpoint; import org.apache.tomcat.util.net.SocketWrapper; public class AprProcessor extends AbstractProcessor<Long> { private static final int INFINITE_TIMEOUT = -1; public AprProcessor(SocketWrapper<Long> wrapper, HttpUpgradeHandler httpUpgradeProcessor, AprEndpoint endpoint) { super(httpUpgradeProcessor, new AprServletInputStream(wrapper), new AprServletOutputStream(wrapper, endpoint)); Socket.timeoutSet(wrapper.getSocket().longValue(), INFINITE_TIMEOUT); } }
55,240
Bug 55240 [websocket] SOE in NioEndpoint
null
resolved fixed
68f6f6f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T18:08:17Z
2013-07-11T16:26:40Z
java/org/apache/coyote/http11/upgrade/BioProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.IOException; import java.net.Socket; import javax.servlet.http.HttpUpgradeHandler; import org.apache.tomcat.util.net.SocketWrapper; public class BioProcessor extends AbstractProcessor<Socket> { private static final int INFINITE_TIMEOUT = 0; public BioProcessor(SocketWrapper<Socket> wrapper, HttpUpgradeHandler httpUpgradeProcessor) throws IOException { super(httpUpgradeProcessor, new BioServletInputStream(wrapper), new BioServletOutputStream(wrapper)); wrapper.getSocket().setSoTimeout(INFINITE_TIMEOUT); } }
55,240
Bug 55240 [websocket] SOE in NioEndpoint
null
resolved fixed
68f6f6f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T18:08:17Z
2013-07-11T16:26:40Z
java/org/apache/coyote/http11/upgrade/NioProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import javax.servlet.http.HttpUpgradeHandler; import org.apache.tomcat.util.net.NioChannel; import org.apache.tomcat.util.net.NioSelectorPool; import org.apache.tomcat.util.net.SocketWrapper; public class NioProcessor extends AbstractProcessor<NioChannel> { private static final int INFINITE_TIMEOUT = -1; public NioProcessor(SocketWrapper<NioChannel> wrapper, HttpUpgradeHandler httpUpgradeProcessor, NioSelectorPool pool) { super(httpUpgradeProcessor, new NioServletInputStream(wrapper, pool), new NioServletOutputStream(wrapper, pool)); wrapper.setTimeout(INFINITE_TIMEOUT); } }
55,240
Bug 55240 [websocket] SOE in NioEndpoint
null
resolved fixed
68f6f6f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-11T18:08:17Z
2013-07-11T16:26:40Z
java/org/apache/tomcat/util/net/NioEndpoint.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.net; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketTimeoutException; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.FileChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; import java.util.Iterator; import java.util.Set; import java.util.concurrent.CountDownLatch; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.X509KeyManager; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.collections.SynchronizedQueue; import org.apache.tomcat.util.collections.SynchronizedStack; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.SecureNioChannel.ApplicationBufferHandler; import org.apache.tomcat.util.net.jsse.NioX509KeyManager; /** * NIO tailored thread pool, providing the following services: * <ul> * <li>Socket acceptor thread</li> * <li>Socket poller thread</li> * <li>Worker threads pool</li> * </ul> * * When switching to Java 5, there's an opportunity to use the virtual * machine's thread pool. * * @author Mladen Turk * @author Remy Maucherat * @author Filip Hanik */ public class NioEndpoint extends AbstractEndpoint { // -------------------------------------------------------------- Constants private static final Log log = LogFactory.getLog(NioEndpoint.class); public static final int OP_REGISTER = 0x100; //register interest op public static final int OP_CALLBACK = 0x200; //callback interest op // ----------------------------------------------------------------- Fields private NioSelectorPool selectorPool = new NioSelectorPool(); /** * Server socket "pointer". */ private ServerSocketChannel serverSock = null; /** * use send file */ private boolean useSendfile = true; /** * The size of the OOM parachute. */ private int oomParachute = 1024*1024; /** * The oom parachute, when an OOM error happens, * will release the data, giving the JVM instantly * a chunk of data to be able to recover with. */ private byte[] oomParachuteData = null; /** * Make sure this string has already been allocated */ private static final String oomParachuteMsg = "SEVERE:Memory usage is low, parachute is non existent, your system may start failing."; /** * Keep track of OOM warning messages. */ private long lastParachuteCheck = System.currentTimeMillis(); /** * */ private volatile CountDownLatch stopLatch = null; /** * Cache for SocketProcessor objects */ private final SynchronizedStack<SocketProcessor> processorCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getProcessorCache()); /** * Cache for key attachment objects */ private final SynchronizedStack<KeyAttachment> keyCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getKeyCache()); /** * Cache for poller events */ private final SynchronizedStack<PollerEvent> eventCache = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getEventCache()); /** * Bytebuffer cache, each channel holds a set of buffers (two, except for SSL holds four) */ private final SynchronizedStack<NioChannel> nioChannels = new SynchronizedStack<>(SynchronizedStack.DEFAULT_SIZE, socketProperties.getBufferPoolSize()); // ------------------------------------------------------------- Properties /** * Generic properties, introspected */ @Override public boolean setProperty(String name, String value) { final String selectorPoolName = "selectorPool."; try { if (name.startsWith(selectorPoolName)) { return IntrospectionUtils.setProperty(selectorPool, name.substring(selectorPoolName.length()), value); } else { return super.setProperty(name, value); } }catch ( Exception x ) { log.error("Unable to set attribute \""+name+"\" to \""+value+"\"",x); return false; } } /** * Priority of the poller threads. */ private int pollerThreadPriority = Thread.NORM_PRIORITY; public void setPollerThreadPriority(int pollerThreadPriority) { this.pollerThreadPriority = pollerThreadPriority; } public int getPollerThreadPriority() { return pollerThreadPriority; } /** * Handling of accepted sockets. */ private Handler handler = null; public void setHandler(Handler handler ) { this.handler = handler; } public Handler getHandler() { return handler; } /** * Allow comet request handling. */ private boolean useComet = true; public void setUseComet(boolean useComet) { this.useComet = useComet; } @Override public boolean getUseComet() { return useComet; } @Override public boolean getUseCometTimeout() { return getUseComet(); } @Override public boolean getUsePolling() { return true; } // Always supported /** * Poller thread count. */ private int pollerThreadCount = Math.min(2,Runtime.getRuntime().availableProcessors()); public void setPollerThreadCount(int pollerThreadCount) { this.pollerThreadCount = pollerThreadCount; } public int getPollerThreadCount() { return pollerThreadCount; } private long selectorTimeout = 1000; public void setSelectorTimeout(long timeout){ this.selectorTimeout = timeout;} public long getSelectorTimeout(){ return this.selectorTimeout; } /** * The socket poller. */ private Poller[] pollers = null; private AtomicInteger pollerRotater = new AtomicInteger(0); /** * Return an available poller in true round robin fashion */ public Poller getPoller0() { int idx = Math.abs(pollerRotater.incrementAndGet()) % pollers.length; return pollers[idx]; } public void setSelectorPool(NioSelectorPool selectorPool) { this.selectorPool = selectorPool; } public void setSocketProperties(SocketProperties socketProperties) { this.socketProperties = socketProperties; } public void setUseSendfile(boolean useSendfile) { this.useSendfile = useSendfile; } /** * Is deferAccept supported? */ @Override public boolean getDeferAccept() { // Not supported return false; } public void setOomParachute(int oomParachute) { this.oomParachute = oomParachute; } public void setOomParachuteData(byte[] oomParachuteData) { this.oomParachuteData = oomParachuteData; } private SSLContext sslContext = null; public SSLContext getSSLContext() { return sslContext;} public void setSSLContext(SSLContext c) { sslContext = c;} private String[] enabledCiphers; private String[] enabledProtocols; /** * Port in use. */ @Override public int getLocalPort() { ServerSocketChannel ssc = serverSock; if (ssc == null) { return -1; } else { ServerSocket s = ssc.socket(); if (s == null) { return -1; } else { return s.getLocalPort(); } } } @Override public String[] getCiphersUsed() { return enabledCiphers; } // --------------------------------------------------------- OOM Parachute Methods protected void checkParachute() { boolean para = reclaimParachute(false); if (!para && (System.currentTimeMillis()-lastParachuteCheck)>10000) { try { log.fatal(oomParachuteMsg); }catch (Throwable t) { ExceptionUtils.handleThrowable(t); System.err.println(oomParachuteMsg); } lastParachuteCheck = System.currentTimeMillis(); } } protected boolean reclaimParachute(boolean force) { if ( oomParachuteData != null ) return true; if ( oomParachute > 0 && ( force || (Runtime.getRuntime().freeMemory() > (oomParachute*2))) ) oomParachuteData = new byte[oomParachute]; return oomParachuteData != null; } protected void releaseCaches() { this.keyCache.clear(); this.nioChannels.clear(); this.processorCache.clear(); if ( handler != null ) handler.recycle(); } // --------------------------------------------------------- Public Methods /** * Number of keepalive sockets. */ public int getKeepAliveCount() { if (pollers == null) { return 0; } else { int sum = 0; for (int i=0; i<pollers.length; i++) { sum += pollers[i].getKeyCount(); } return sum; } } // ----------------------------------------------- Public Lifecycle Methods /** * Initialize the endpoint. */ @Override public void bind() throws Exception { serverSock = ServerSocketChannel.open(); socketProperties.setProperties(serverSock.socket()); InetSocketAddress addr = (getAddress()!=null?new InetSocketAddress(getAddress(),getPort()):new InetSocketAddress(getPort())); serverSock.socket().bind(addr,getBacklog()); serverSock.configureBlocking(true); //mimic APR behavior serverSock.socket().setSoTimeout(getSocketProperties().getSoTimeout()); // Initialize thread count defaults for acceptor, poller if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } if (pollerThreadCount <= 0) { //minimum one poller thread pollerThreadCount = 1; } stopLatch = new CountDownLatch(pollerThreadCount); // Initialize SSL if needed if (isSSLEnabled()) { SSLUtil sslUtil = handler.getSslImplementation().getSSLUtil(this); sslContext = sslUtil.createSSLContext(); sslContext.init(wrap(sslUtil.getKeyManagers()), sslUtil.getTrustManagers(), null); SSLSessionContext sessionContext = sslContext.getServerSessionContext(); if (sessionContext != null) { sslUtil.configureSessionContext(sessionContext); } // Determine which cipher suites and protocols to enable enabledCiphers = sslUtil.getEnableableCiphers(sslContext); enabledProtocols = sslUtil.getEnableableProtocols(sslContext); } if (oomParachute>0) reclaimParachute(true); selectorPool.open(); } public KeyManager[] wrap(KeyManager[] managers) { if (managers==null) return null; KeyManager[] result = new KeyManager[managers.length]; for (int i=0; i<result.length; i++) { if (managers[i] instanceof X509KeyManager && getKeyAlias()!=null) { result[i] = new NioX509KeyManager((X509KeyManager)managers[i],getKeyAlias()); } else { result[i] = managers[i]; } } return result; } /** * Start the NIO endpoint, creating acceptor, poller threads. */ @Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if ( getExecutor() == null ) { createExecutor(); } initializeConnectionLatch(); // Start poller threads pollers = new Poller[getPollerThreadCount()]; for (int i=0; i<pollers.length; i++) { pollers[i] = new Poller(); Thread pollerThread = new Thread(pollers[i], getName() + "-ClientPoller-"+i); pollerThread.setPriority(threadPriority); pollerThread.setDaemon(true); pollerThread.start(); } startAcceptorThreads(); } } /** * Stop the endpoint. This will cause all processing threads to stop. */ @Override public void stopInternal() { releaseConnectionLatch(); if (!paused) { pause(); } if (running) { running = false; unlockAccept(); for (int i=0; pollers!=null && i<pollers.length; i++) { if (pollers[i]==null) continue; pollers[i].destroy(); pollers[i] = null; } try { stopLatch.await(selectorTimeout + 100, TimeUnit.MILLISECONDS); } catch (InterruptedException ignore) { } } eventCache.clear(); keyCache.clear(); nioChannels.clear(); processorCache.clear(); shutdownExecutor(); } /** * Deallocate NIO memory pools, and close server socket. */ @Override public void unbind() throws Exception { if (log.isDebugEnabled()) { log.debug("Destroy initiated for "+new InetSocketAddress(getAddress(),getPort())); } if (running) { stop(); } // Close server socket serverSock.socket().close(); serverSock.close(); serverSock = null; sslContext = null; releaseCaches(); selectorPool.close(); if (log.isDebugEnabled()) { log.debug("Destroy completed for "+new InetSocketAddress(getAddress(),getPort())); } } // ------------------------------------------------------ Protected Methods public int getWriteBufSize() { return socketProperties.getTxBufSize(); } public int getReadBufSize() { return socketProperties.getRxBufSize(); } public NioSelectorPool getSelectorPool() { return selectorPool; } @Override public boolean getUseSendfile() { return useSendfile; } public int getOomParachute() { return oomParachute; } public byte[] getOomParachuteData() { return oomParachuteData; } @Override protected AbstractEndpoint.Acceptor createAcceptor() { return new Acceptor(); } /** * Process the specified connection. */ protected boolean setSocketOptions(SocketChannel socket) { // Process the connection try { //disable blocking, APR style, we are gonna be polling it socket.configureBlocking(false); Socket sock = socket.socket(); socketProperties.setProperties(sock); NioChannel channel = nioChannels.pop(); if ( channel == null ) { // SSL setup if (sslContext != null) { SSLEngine engine = createSSLEngine(); int appbufsize = engine.getSession().getApplicationBufferSize(); NioBufferHandler bufhandler = new NioBufferHandler(Math.max(appbufsize,socketProperties.getAppReadBufSize()), Math.max(appbufsize,socketProperties.getAppWriteBufSize()), socketProperties.getDirectBuffer()); channel = new SecureNioChannel(socket, engine, bufhandler, selectorPool); } else { // normal tcp setup NioBufferHandler bufhandler = new NioBufferHandler(socketProperties.getAppReadBufSize(), socketProperties.getAppWriteBufSize(), socketProperties.getDirectBuffer()); channel = new NioChannel(socket, bufhandler); } } else { channel.setIOChannel(socket); if ( channel instanceof SecureNioChannel ) { SSLEngine engine = createSSLEngine(); ((SecureNioChannel)channel).reset(engine); } else { channel.reset(); } } getPoller0().register(channel); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); try { log.error("",t); } catch (Throwable tt) { ExceptionUtils.handleThrowable(t); } // Tell to close the socket return false; } return true; } protected SSLEngine createSSLEngine() { SSLEngine engine = sslContext.createSSLEngine(); if ("false".equals(getClientAuth())) { engine.setNeedClientAuth(false); engine.setWantClientAuth(false); } else if ("true".equals(getClientAuth()) || "yes".equals(getClientAuth())){ engine.setNeedClientAuth(true); } else if ("want".equals(getClientAuth())) { engine.setWantClientAuth(true); } engine.setUseClientMode(false); engine.setEnabledCipherSuites(enabledCiphers); engine.setEnabledProtocols(enabledProtocols); handler.onCreateSSLEngine(engine); return engine; } /** * Returns true if a worker thread is available for processing. * @return boolean */ protected boolean isWorkerAvailable() { return true; } public boolean dispatchForEvent(NioChannel socket, SocketStatus status, boolean dispatch) { if (!dispatch) { processSocket(socket,status,dispatch); } else { socket.getPoller().add(socket, OP_CALLBACK); } return true; } protected boolean processSocket(NioChannel socket, SocketStatus status, boolean dispatch) { try { KeyAttachment attachment = (KeyAttachment)socket.getAttachment(false); if (attachment == null) { return false; } attachment.setCometNotify(false); //will get reset upon next reg SocketProcessor sc = processorCache.pop(); if ( sc == null ) sc = new SocketProcessor(socket,status); else sc.reset(socket,status); if ( dispatch && getExecutor()!=null ) getExecutor().execute(sc); else sc.run(); } catch (RejectedExecutionException rx) { log.warn("Socket processing request was rejected for:"+socket,rx); return false; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // This means we got an OOM or similar creating a thread, or that // the pool and its queue are full log.error(sm.getString("endpoint.process.fail"), t); return false; } return true; } @Override protected Log getLog() { return log; } // --------------------------------------------------- Acceptor Inner Class /** * The background thread that listens for incoming TCP/IP connections and * hands them off to an appropriate processor. */ protected class Acceptor extends AbstractEndpoint.Acceptor { @Override public void run() { int errorDelay = 0; // Loop until we receive a shutdown command while (running) { // Loop if endpoint is paused while (paused && running) { state = AcceptorState.PAUSED; try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore } } if (!running) { break; } state = AcceptorState.RUNNING; try { //if we have reached max connections, wait countUpOrAwaitConnection(); SocketChannel socket = null; try { // Accept the next incoming connection from the server // socket socket = serverSock.accept(); } catch (IOException ioe) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw ioe; } // Successful accept, reset the error delay errorDelay = 0; // setSocketOptions() will add channel to the poller // if successful if (running && !paused) { if (!setSocketOptions(socket)) { countDownConnection(); closeSocket(socket); } } else { countDownConnection(); closeSocket(socket); } } catch (SocketTimeoutException sx) { // Ignore: Normal condition } catch (IOException x) { if (running) { log.error(sm.getString("endpoint.accept.fail"), x); } } catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("endpoint.accept.fail"), t); } } state = AcceptorState.ENDED; } } private void closeSocket(SocketChannel socket) { try { socket.socket().close(); } catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } } try { socket.close(); } catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("", ioe); } } } // ----------------------------------------------------- Poller Inner Classes /** * * PollerEvent, cacheable object for poller events to avoid GC */ public static class PollerEvent implements Runnable { private NioChannel socket; private int interestOps; private KeyAttachment key; public PollerEvent(NioChannel ch, KeyAttachment k, int intOps) { reset(ch, k, intOps); } public void reset(NioChannel ch, KeyAttachment k, int intOps) { socket = ch; interestOps = intOps; key = k; } public void reset() { reset(null, null, 0); } @Override public void run() { if ( interestOps == OP_REGISTER ) { try { socket.getIOChannel().register(socket.getPoller().getSelector(), SelectionKey.OP_READ, key); } catch (Exception x) { log.error("", x); } } else { final SelectionKey key = socket.getIOChannel().keyFor(socket.getPoller().getSelector()); try { boolean cancel = false; if (key != null) { final KeyAttachment att = (KeyAttachment) key.attachment(); if ( att!=null ) { //handle callback flag if ((interestOps & OP_CALLBACK) == OP_CALLBACK ) { att.setCometNotify(true); } else { att.setCometNotify(false); } interestOps = (interestOps & (~OP_CALLBACK));//remove the callback flag att.access();//to prevent timeout //we are registering the key to start with, reset the fairness counter. int ops = key.interestOps() | interestOps; att.interestOps(ops); if (att.getCometNotify()) key.interestOps(0); else key.interestOps(ops); } else { cancel = true; } } else { cancel = true; } if ( cancel ) socket.getPoller().cancelledKey(key,SocketStatus.ERROR); }catch (CancelledKeyException ckx) { try { socket.getPoller().cancelledKey(key,SocketStatus.DISCONNECT); }catch (Exception ignore) {} } }//end if }//run @Override public String toString() { return super.toString()+"[intOps="+this.interestOps+"]"; } } /** * Poller class. */ public class Poller implements Runnable { private Selector selector; private final SynchronizedQueue<PollerEvent> events = new SynchronizedQueue<>(); private volatile boolean close = false; private long nextExpiration = 0;//optimize expiration handling private AtomicLong wakeupCounter = new AtomicLong(0l); private volatile int keyCount = 0; public Poller() throws IOException { synchronized (Selector.class) { // Selector.open() isn't thread safe // http://bugs.sun.com/view_bug.do?bug_id=6427854 // Affects 1.6.0_29, fixed in 1.7.0_01 this.selector = Selector.open(); } } public int getKeyCount() { return keyCount; } public Selector getSelector() { return selector;} /** * Destroy the poller. */ protected void destroy() { // Wait for polltime before doing anything, so that the poller threads // exit, otherwise parallel closure of sockets which are still // in the poller can cause problems close = true; selector.wakeup(); } private void addEvent(PollerEvent event) { events.offer(event); if ( wakeupCounter.incrementAndGet() == 0 ) selector.wakeup(); } /** * Add specified socket and associated pool to the poller. The socket will * be added to a temporary array, and polled first after a maximum amount * of time equal to pollTime (in most cases, latency will be much lower, * however). * * @param socket to add to the poller */ public void add(final NioChannel socket) { add(socket,SelectionKey.OP_READ); } public void add(final NioChannel socket, final int interestOps) { PollerEvent r = eventCache.pop(); if ( r==null) r = new PollerEvent(socket,null,interestOps); else r.reset(socket,null,interestOps); if ( (interestOps&OP_CALLBACK) == OP_CALLBACK ) { nextExpiration = 0; //force the check for faster callback } addEvent(r); if (close) { processSocket(socket, SocketStatus.STOP, false); } } /** * Processes events in the event queue of the Poller. * * @return <code>true</code> if some events were processed, * <code>false</code> if queue was empty */ public boolean events() { boolean result = false; PollerEvent pe = null; while ( (pe = events.poll()) != null ) { result = true; try { pe.run(); pe.reset(); if (running && !paused) { eventCache.push(pe); } } catch ( Throwable x ) { log.error("",x); } } return result; } /** * Registers a newly created socket with the poller. * * @param socket The newly created socket */ public void register(final NioChannel socket) { socket.setPoller(this); KeyAttachment key = keyCache.pop(); final KeyAttachment ka = key!=null?key:new KeyAttachment(socket); ka.reset(this,socket,getSocketProperties().getSoTimeout()); ka.setKeepAliveLeft(NioEndpoint.this.getMaxKeepAliveRequests()); PollerEvent r = eventCache.pop(); ka.interestOps(SelectionKey.OP_READ);//this is what OP_REGISTER turns into. if ( r==null) r = new PollerEvent(socket,ka,OP_REGISTER); else r.reset(socket,ka,OP_REGISTER); addEvent(r); } public void cancelledKey(SelectionKey key, SocketStatus status) { try { if ( key == null ) return;//nothing to do KeyAttachment ka = (KeyAttachment) key.attachment(); if (ka != null && ka.isComet() && status != null) { ka.setComet(false);//to avoid a loop if (status == SocketStatus.TIMEOUT ) { if (processSocket(ka.getChannel(), status, true)) { return; // don't close on comet timeout } } else { // Don't dispatch if the lines below are canceling the key processSocket(ka.getChannel(), status, false); } } key.attach(null); if (ka!=null) handler.release(ka); else handler.release((SocketChannel)key.channel()); if (key.isValid()) key.cancel(); if (key.channel().isOpen()) { try { key.channel().close(); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.channelCloseFail"), e); } } } try { if (ka!=null) { ka.getSocket().close(true); } } catch (Exception e){ if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.socketCloseFail"), e); } } try { if (ka != null && ka.getSendfileData() != null && ka.getSendfileData().fchannel != null && ka.getSendfileData().fchannel.isOpen()) { ka.getSendfileData().fchannel.close(); } } catch (Exception ignore) { } if (ka!=null) { ka.reset(); countDownConnection(); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); if (log.isDebugEnabled()) log.error("",e); } } /** * The background thread that listens for incoming TCP/IP connections and * hands them off to an appropriate processor. */ @Override public void run() { // Loop until destroy() is called while (true) { try { // Loop if endpoint is paused while (paused && (!close) ) { try { Thread.sleep(100); } catch (InterruptedException e) { // Ignore } } boolean hasEvents = false; // Time to terminate? if (close) { events(); timeout(0, false); try { selector.close(); } catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); } break; } else { hasEvents = events(); } try { if ( !close ) { if (wakeupCounter.getAndSet(-1) > 0) { //if we are here, means we have other stuff to do //do a non blocking select keyCount = selector.selectNow(); } else { keyCount = selector.select(selectorTimeout); } wakeupCounter.set(0); } if (close) { events(); timeout(0, false); try { selector.close(); } catch (IOException ioe) { log.error(sm.getString( "endpoint.nio.selectorCloseFail"), ioe); } break; } } catch ( NullPointerException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; } catch ( CancelledKeyException x ) { //sun bug 5076772 on windows JDK 1.5 if ( log.isDebugEnabled() ) log.debug("Possibly encountered sun bug 5076772 on windows JDK 1.5",x); if ( wakeupCounter == null || selector == null ) throw x; continue; } catch (Throwable x) { ExceptionUtils.handleThrowable(x); log.error("",x); continue; } //either we timed out or we woke up, process events first if ( keyCount == 0 ) hasEvents = (hasEvents | events()); Iterator<SelectionKey> iterator = keyCount > 0 ? selector.selectedKeys().iterator() : null; // Walk through the collection of ready keys and dispatch // any active event. while (iterator != null && iterator.hasNext()) { SelectionKey sk = iterator.next(); KeyAttachment attachment = (KeyAttachment)sk.attachment(); // Attachment may be null if another thread has called // cancelledKey() if (attachment == null) { iterator.remove(); } else { attachment.access(); iterator.remove(); processKey(sk, attachment); } }//while //process timeouts timeout(keyCount,hasEvents); if ( oomParachute > 0 && oomParachuteData == null ) checkParachute(); } catch (OutOfMemoryError oom) { try { oomParachuteData = null; releaseCaches(); log.error("", oom); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } } }//while stopLatch.countDown(); } protected boolean processKey(SelectionKey sk, KeyAttachment attachment) { boolean result = true; try { if ( close ) { cancelledKey(sk, SocketStatus.STOP); } else if ( sk.isValid() && attachment != null ) { attachment.access();//make sure we don't time out valid sockets NioChannel channel = attachment.getChannel(); if (sk.isReadable() || sk.isWritable() ) { if ( attachment.getSendfileData() != null ) { processSendfile(sk,attachment, false); } else if ( attachment.isComet() ) { //check if thread is available if ( isWorkerAvailable() ) { //set interest ops to 0 so we don't get multiple //Invocations for both read and write on separate threads reg(sk, attachment, 0); //read goes before write if (sk.isReadable()) { //read notification if (!processSocket(channel, SocketStatus.OPEN_READ, true)) processSocket(channel, SocketStatus.DISCONNECT, true); } else { //future placement of a WRITE notif if (!processSocket(channel, SocketStatus.OPEN_WRITE, true)) processSocket(channel, SocketStatus.DISCONNECT, true); } } else { result = false; } } else { //later on, improve latch behavior if ( isWorkerAvailable() ) { boolean readAndWrite = sk.isReadable() && sk.isWritable(); reg(sk, attachment, 0); if (attachment.isAsync() && readAndWrite) { //remember the that we want to know about write too attachment.interestOps(SelectionKey.OP_WRITE); } //read goes before write if (sk.isReadable()) { //read notification if (!processSocket(channel, SocketStatus.OPEN_READ, true)) close = true; } else { //future placement of a WRITE notif if (!processSocket(channel, SocketStatus.OPEN_WRITE, true)) close = true; } if (close) { cancelledKey(sk,SocketStatus.DISCONNECT); } } else { result = false; } } } } else { //invalid key cancelledKey(sk, SocketStatus.ERROR); } } catch ( CancelledKeyException ckx ) { cancelledKey(sk, SocketStatus.ERROR); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("",t); } return result; } public boolean processSendfile(SelectionKey sk, KeyAttachment attachment, boolean event) { NioChannel sc = null; try { unreg(sk, attachment, sk.readyOps()); SendfileData sd = attachment.getSendfileData(); if (log.isTraceEnabled()) { log.trace("Processing send file for: " + sd.fileName); } //setup the file channel if ( sd.fchannel == null ) { File f = new File(sd.fileName); if ( !f.exists() ) { cancelledKey(sk,SocketStatus.ERROR); return false; } @SuppressWarnings("resource") // Closed when channel is closed FileInputStream fis = new FileInputStream(f); sd.fchannel = fis.getChannel(); } //configure output channel sc = attachment.getChannel(); sc.setSendFile(true); //ssl channel is slightly different WritableByteChannel wc = ((sc instanceof SecureNioChannel)?sc:sc.getIOChannel()); //we still have data in the buffer if (sc.getOutboundRemaining()>0) { if (sc.flushOutbound()) { attachment.access(); } } else { long written = sd.fchannel.transferTo(sd.pos,sd.length,wc); if ( written > 0 ) { sd.pos += written; sd.length -= written; attachment.access(); } else { // Unusual not to be able to transfer any bytes // Check the length was set correctly if (sd.fchannel.size() <= sd.pos) { throw new IOException("Sendfile configured to " + "send more data than was available"); } } } if ( sd.length <= 0 && sc.getOutboundRemaining()<=0) { if (log.isDebugEnabled()) { log.debug("Send file complete for: "+sd.fileName); } attachment.setSendfileData(null); try { sd.fchannel.close(); } catch (Exception ignore) { } if ( sd.keepAlive ) { if (log.isDebugEnabled()) { log.debug("Connection is keep alive, registering back for OP_READ"); } if (event) { this.add(attachment.getChannel(),SelectionKey.OP_READ); } else { reg(sk,attachment,SelectionKey.OP_READ); } } else { if (log.isDebugEnabled()) { log.debug("Send file connection is being closed"); } cancelledKey(sk,SocketStatus.STOP); return false; } } else { if (log.isDebugEnabled()) { log.debug("OP_WRITE for sendfile: " + sd.fileName); } if (event) { add(attachment.getChannel(),SelectionKey.OP_WRITE); } else { reg(sk,attachment,SelectionKey.OP_WRITE); } } }catch ( IOException x ) { if ( log.isDebugEnabled() ) log.debug("Unable to complete sendfile request:", x); cancelledKey(sk,SocketStatus.ERROR); return false; }catch ( Throwable t ) { log.error("",t); cancelledKey(sk, SocketStatus.ERROR); return false; }finally { if (sc!=null) sc.setSendFile(false); } return true; } protected void unreg(SelectionKey sk, KeyAttachment attachment, int readyOps) { //this is a must, so that we don't have multiple threads messing with the socket reg(sk,attachment,sk.interestOps()& (~readyOps)); } protected void reg(SelectionKey sk, KeyAttachment attachment, int intops) { sk.interestOps(intops); attachment.interestOps(intops); } protected void timeout(int keyCount, boolean hasEvents) { long now = System.currentTimeMillis(); // This method is called on every loop of the Poller. Don't process // timeouts on every loop of the Poller since that would create too // much load and timeouts can afford to wait a few seconds. // However, do process timeouts if any of the following are true: // - the selector simply timed out (suggests there isn't much load) // - the nextExpiration time has passed // - the server socket is being closed if (nextExpiration > 0 && (keyCount > 0 || hasEvents) && (now < nextExpiration) && !close) { return; } //timeout Set<SelectionKey> keys = selector.keys(); int keycount = 0; for (Iterator<SelectionKey> iter = keys.iterator(); iter.hasNext();) { SelectionKey key = iter.next(); keycount++; try { KeyAttachment ka = (KeyAttachment) key.attachment(); if ( ka == null ) { cancelledKey(key, SocketStatus.ERROR); //we don't support any keys without attachments } else if ( ka.getError() ) { cancelledKey(key, SocketStatus.ERROR);//TODO this is not yet being used } else if (ka.getCometNotify() ) { ka.setCometNotify(false); int ops = ka.interestOps() & ~OP_CALLBACK; reg(key,ka,0);//avoid multiple calls, this gets re-registered after invocation ka.interestOps(ops); if (!processSocket(ka.getChannel(), SocketStatus.OPEN_READ, true)) processSocket(ka.getChannel(), SocketStatus.DISCONNECT, true); } else if ((ka.interestOps()&SelectionKey.OP_READ) == SelectionKey.OP_READ || (ka.interestOps()&SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) { //only timeout sockets that we are waiting for a read from long delta = now - ka.getLastAccess(); long timeout = ka.getTimeout(); boolean isTimedout = timeout > 0 && delta > timeout; if ( close ) { key.interestOps(0); ka.interestOps(0); //avoid duplicate stop calls processKey(key,ka); } else if (isTimedout) { key.interestOps(0); ka.interestOps(0); //avoid duplicate timeout calls cancelledKey(key, SocketStatus.TIMEOUT); } } else if (ka.isAsync() || ka.isComet()) { if (close) { key.interestOps(0); ka.interestOps(0); //avoid duplicate stop calls processKey(key,ka); } else if (!ka.isAsync() || ka.getTimeout() > 0) { // Async requests with a timeout of 0 or less never timeout long delta = now - ka.getLastAccess(); long timeout = (ka.getTimeout()==-1)?((long) socketProperties.getSoTimeout()):(ka.getTimeout()); boolean isTimedout = delta > timeout; if (isTimedout) { // Prevent subsequent timeouts if the timeout event takes a while to process ka.access(Long.MAX_VALUE); processSocket(ka.getChannel(), SocketStatus.TIMEOUT, true); } } }//end if }catch ( CancelledKeyException ckx ) { cancelledKey(key, SocketStatus.ERROR); } }//for long prevExp = nextExpiration; //for logging purposes only nextExpiration = System.currentTimeMillis() + socketProperties.getTimeoutInterval(); if (log.isTraceEnabled()) { log.trace("timeout completed: keys processed=" + keycount + "; now=" + now + "; nextExpiration=" + prevExp + "; keyCount=" + keyCount + "; hasEvents=" + hasEvents + "; eval=" + ((now < prevExp) && (keyCount>0 || hasEvents) && (!close) )); } } } // ----------------------------------------------------- Key Attachment Class public static class KeyAttachment extends SocketWrapper<NioChannel> { public KeyAttachment(NioChannel channel) { super(channel); } public void reset(Poller poller, NioChannel channel, long soTimeout) { this.socket = channel; this.poller = poller; lastAccess = System.currentTimeMillis(); setComet(false); timeout = soTimeout; error = false; sendfileData = null; if (readLatch != null) { try { for (int i = 0; i < (int) readLatch.getCount(); i++) { readLatch.countDown(); } } catch (Exception ignore) { } } readLatch = null; if (writeLatch != null) { try { for (int i = 0; i < (int) writeLatch.getCount(); i++) { writeLatch.countDown(); } } catch (Exception ignore) { } } writeLatch = null; cometNotify = false; sendfileData = null; keepAliveLeft = 100; async = false; } public void reset() { reset(null,null,-1); } public Poller getPoller() { return poller;} public void setPoller(Poller poller){this.poller = poller;} public void setCometNotify(boolean notify) { this.cometNotify = notify; } public boolean getCometNotify() { return cometNotify; } public NioChannel getChannel() { return getSocket();} public void setChannel(NioChannel channel) { this.socket = channel;} public int interestOps() { return interestOps;} public int interestOps(int ops) { this.interestOps = ops; return ops; } public CountDownLatch getReadLatch() { return readLatch; } public CountDownLatch getWriteLatch() { return writeLatch; } protected CountDownLatch resetLatch(CountDownLatch latch) { if ( latch==null || latch.getCount() == 0 ) return null; else throw new IllegalStateException("Latch must be at count 0"); } public void resetReadLatch() { readLatch = resetLatch(readLatch); } public void resetWriteLatch() { writeLatch = resetLatch(writeLatch); } protected CountDownLatch startLatch(CountDownLatch latch, int cnt) { if ( latch == null || latch.getCount() == 0 ) { return new CountDownLatch(cnt); } else throw new IllegalStateException("Latch must be at count 0 or null."); } public void startReadLatch(int cnt) { readLatch = startLatch(readLatch,cnt);} public void startWriteLatch(int cnt) { writeLatch = startLatch(writeLatch,cnt);} protected void awaitLatch(CountDownLatch latch, long timeout, TimeUnit unit) throws InterruptedException { if ( latch == null ) throw new IllegalStateException("Latch cannot be null"); // Note: While the return value is ignored if the latch does time // out, logic further up the call stack will trigger a // SocketTimeoutException latch.await(timeout,unit); } public void awaitReadLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(readLatch,timeout,unit);} public void awaitWriteLatch(long timeout, TimeUnit unit) throws InterruptedException { awaitLatch(writeLatch,timeout,unit);} public void setSendfileData(SendfileData sf) { this.sendfileData = sf;} public SendfileData getSendfileData() { return this.sendfileData;} private Poller poller = null; private int interestOps = 0; private boolean cometNotify = false; private CountDownLatch readLatch = null; private CountDownLatch writeLatch = null; private SendfileData sendfileData = null; } // ------------------------------------------------ Application Buffer Handler public static class NioBufferHandler implements ApplicationBufferHandler { private ByteBuffer readbuf = null; private ByteBuffer writebuf = null; public NioBufferHandler(int readsize, int writesize, boolean direct) { if ( direct ) { readbuf = ByteBuffer.allocateDirect(readsize); writebuf = ByteBuffer.allocateDirect(writesize); }else { readbuf = ByteBuffer.allocate(readsize); writebuf = ByteBuffer.allocate(writesize); } } @Override public ByteBuffer expand(ByteBuffer buffer, int remaining) {return buffer;} @Override public ByteBuffer getReadBuffer() {return readbuf;} @Override public ByteBuffer getWriteBuffer() {return writebuf;} } // ------------------------------------------------ Handler Inner Interface /** * Bare bones interface used for socket processing. Per thread data is to be * stored in the ThreadWithAttributes extra folders, or alternately in * thread local fields. */ public interface Handler extends AbstractEndpoint.Handler { public SocketState process(SocketWrapper<NioChannel> socket, SocketStatus status); public void release(SocketWrapper<NioChannel> socket); public void release(SocketChannel socket); public SSLImplementation getSslImplementation(); public void onCreateSSLEngine(SSLEngine engine); } // ---------------------------------------------- SocketProcessor Inner Class /** * This class is the equivalent of the Worker, but will simply use in an * external Executor thread pool. */ protected class SocketProcessor implements Runnable { private NioChannel socket = null; private SocketStatus status = null; public SocketProcessor(NioChannel socket, SocketStatus status) { reset(socket,status); } public void reset(NioChannel socket, SocketStatus status) { this.socket = socket; this.status = status; } @Override public void run() { SelectionKey key = socket.getIOChannel().keyFor( socket.getPoller().getSelector()); KeyAttachment ka = null; if (key != null) { ka = (KeyAttachment)key.attachment(); } // Upgraded connections need to allow multiple threads to access the // connection at the same time to enable blocking IO to be used when // NIO has been configured if (ka != null && ka.isUpgraded() && SocketStatus.OPEN_WRITE == status) { synchronized (ka.getWriteThreadLock()) { doRun(key, ka); } } else { synchronized (socket) { doRun(key, ka); } } } private void doRun(SelectionKey key, KeyAttachment ka) { boolean launch = false; try { int handshake = -1; try { if (key != null) { if (socket.isHandshakeComplete()) { handshake = 0; } else { handshake = socket.handshake( key.isReadable(), key.isWritable()); // The handshake process reads/writes from/to the // socket. status may therefore be OPEN_WRITE once // the handshake completes. However, the handshake // happens when the socket is opened so the status // must always be OPEN_READ after it completes. It // is OK to always set this as it is only used if // the handshake completes. status = SocketStatus.OPEN_READ; } } }catch ( IOException x ) { handshake = -1; if ( log.isDebugEnabled() ) log.debug("Error during SSL handshake",x); }catch ( CancelledKeyException ckx ) { handshake = -1; } if ( handshake == 0 ) { SocketState state = SocketState.OPEN; // Process the request from this socket // Suppress null warnings for key in this block since // key can't be null in this block if (status == null) { state = handler.process(ka, SocketStatus.OPEN_READ); } else { state = handler.process(ka, status); } if (state == SocketState.CLOSED) { // Close socket and pool try { if (ka!=null) ka.setComet(false); socket.getPoller().cancelledKey(key, SocketStatus.ERROR); if (running && !paused) { nioChannels.push(socket); } socket = null; if (running && !paused && ka != null) { keyCache.push(ka); } ka = null; }catch ( Exception x ) { log.error("",x); } } else if (state == SocketState.LONG && ka != null && ka.isAsync() && ka.interestOps() > 0) { //we are async, and we are interested in operations ka.getPoller().add(socket, ka.interestOps()); } } else if (handshake == -1 ) { if (key != null) { socket.getPoller().cancelledKey(key, SocketStatus.DISCONNECT); } if (running && !paused) { nioChannels.push(socket); } socket = null; if (running && !paused && ka != null) { keyCache.push(ka); } ka = null; } else { ka.getPoller().add(socket,handshake); } }catch(CancelledKeyException cx) { socket.getPoller().cancelledKey(key,null); } catch (OutOfMemoryError oom) { try { oomParachuteData = null; log.error("", oom); if (socket != null) { socket.getPoller().cancelledKey(key,SocketStatus.ERROR); } releaseCaches(); }catch ( Throwable oomt ) { try { System.err.println(oomParachuteMsg); oomt.printStackTrace(); }catch (Throwable letsHopeWeDontGetHere){ ExceptionUtils.handleThrowable(letsHopeWeDontGetHere); } } }catch ( Throwable t ) { log.error("",t); if (socket != null) { socket.getPoller().cancelledKey(key,SocketStatus.ERROR); } } finally { if (launch) { try { getExecutor().execute(new SocketProcessor(socket, SocketStatus.OPEN_READ)); } catch (NullPointerException npe) { if (running) { log.error(sm.getString("endpoint.launch.fail"), npe); } } } socket = null; status = null; //return to cache if (running && !paused) { processorCache.push(this); } } } } // ----------------------------------------------- SendfileData Inner Class /** * SendfileData class. */ public static class SendfileData { // File public String fileName; public FileChannel fchannel; public long pos; public long length; // KeepAlive flag public boolean keepAlive; } }
55,244
Bug 55244 JspC throws ClassNotFoundException from Digester
null
resolved fixed
8d6537d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-12T08:36:14Z
2013-07-12T06:20:00Z
java/org/apache/jasper/servlet/JspCServletContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.servlet; import java.io.File; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.EnumSet; import java.util.Enumeration; import java.util.EventListener; import java.util.HashSet; import java.util.Hashtable; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Vector; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.FilterRegistration.Dynamic; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.descriptor.JspPropertyGroupDescriptor; import javax.servlet.descriptor.TaglibDescriptor; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.util.ExceptionUtils; import org.apache.tomcat.util.descriptor.web.JspConfigDescriptorImpl; import org.apache.tomcat.util.descriptor.web.JspPropertyGroup; import org.apache.tomcat.util.descriptor.web.JspPropertyGroupDescriptorImpl; import org.apache.tomcat.util.descriptor.web.TaglibDescriptorImpl; import org.apache.tomcat.util.descriptor.web.WebXml; import org.apache.tomcat.util.descriptor.web.WebXmlParser; import org.xml.sax.InputSource; /** * Simple <code>ServletContext</code> implementation without * HTTP-specific methods. * * @author Peter Rossbach (pr@webapp.de) */ public class JspCServletContext implements ServletContext { // ----------------------------------------------------- Instance Variables /** * Servlet context attributes. */ private final Hashtable<String,Object> myAttributes; /** * The log writer we will write log messages to. */ private final PrintWriter myLogWriter; /** * The base URL (document root) for this context. */ private final URL myResourceBaseURL; /** * Merged web.xml for the application. */ private final WebXml webXml; private final JspConfigDescriptorImpl jspConfigDescriptor; /** * Web application class loader. */ private ClassLoader loader; // ----------------------------------------------------------- Constructors /** * Create a new instance of this ServletContext implementation. * * @param aLogWriter PrintWriter which is used for <code>log()</code> calls * @param aResourceBaseURL Resource base URL * @throws JasperException */ public JspCServletContext(PrintWriter aLogWriter, URL aResourceBaseURL) throws JasperException { myAttributes = new Hashtable<>(); myLogWriter = aLogWriter; myResourceBaseURL = aResourceBaseURL; // Build the merged web.xml // TODO - Process fragments // TODO - Check to see if annotations can impact anything JspC // cares about and if yes, process fragments too. this.webXml = new WebXml(); WebXmlParser webXmlParser = new WebXmlParser(false, false); InputStream webXmlStream = getResourceAsStream( org.apache.tomcat.util.descriptor.web.Constants. WEB_XML_LOCATION); if (webXmlStream != null) { URL webXmlUrl; try { webXmlUrl = getResource( org.apache.tomcat.util.descriptor.web.Constants. WEB_XML_LOCATION); } catch (MalformedURLException e) { // Should never happen. Just in case... throw new JasperException(e); } InputSource source = new InputSource(webXmlUrl.toExternalForm()); source.setByteStream(webXmlStream); if (!webXmlParser.parseWebXml(source, webXml, false)) { throw new JasperException(Localizer.getMessage("")); } } Set<JspPropertyGroup> jspPropertyGroups = webXml.getJspPropertyGroups(); Map<String,String> tagLibs = webXml.getTaglibs(); if (jspPropertyGroups.isEmpty() && tagLibs.isEmpty()) { jspConfigDescriptor = null; } else { jspConfigDescriptor = new JspConfigDescriptorImpl(); for (JspPropertyGroup jspPropertyGroup : jspPropertyGroups) { JspPropertyGroupDescriptor descriptor = new JspPropertyGroupDescriptorImpl(jspPropertyGroup); jspConfigDescriptor.getJspPropertyGroups().add(descriptor); } for (Entry<String, String> entry : webXml.getTaglibs().entrySet()) { TaglibDescriptor descriptor = new TaglibDescriptorImpl( entry.getValue(), entry.getKey()); jspConfigDescriptor.getTaglibs().add(descriptor); } } } // --------------------------------------------------------- Public Methods /** * Return the specified context attribute, if any. * * @param name Name of the requested attribute */ @Override public Object getAttribute(String name) { return myAttributes.get(name); } /** * Return an enumeration of context attribute names. */ @Override public Enumeration<String> getAttributeNames() { return myAttributes.keys(); } /** * Return the servlet context for the specified path. * * @param uripath Server-relative path starting with '/' */ @Override public ServletContext getContext(String uripath) { return null; } /** * Return the context path. */ @Override public String getContextPath() { return null; } /** * Return the specified context initialization parameter. * * @param name Name of the requested parameter */ @Override public String getInitParameter(String name) { return null; } /** * Return an enumeration of the names of context initialization * parameters. */ @Override public Enumeration<String> getInitParameterNames() { return new Vector<String>().elements(); } /** * Return the Servlet API major version number. */ @Override public int getMajorVersion() { return 3; } /** * Return the MIME type for the specified filename. * * @param file Filename whose MIME type is requested */ @Override public String getMimeType(String file) { return null; } /** * Return the Servlet API minor version number. */ @Override public int getMinorVersion() { return 1; } /** * Return a request dispatcher for the specified servlet name. * * @param name Name of the requested servlet */ @Override public RequestDispatcher getNamedDispatcher(String name) { return null; } /** * Return the real path for the specified context-relative * virtual path. * * @param path The context-relative virtual path to resolve */ @Override public String getRealPath(String path) { if (!myResourceBaseURL.getProtocol().equals("file")) return (null); if (!path.startsWith("/")) return (null); try { return (getResource(path).getFile().replace('/', File.separatorChar)); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); } } /** * Return a request dispatcher for the specified context-relative path. * * @param path Context-relative path for which to acquire a dispatcher */ @Override public RequestDispatcher getRequestDispatcher(String path) { return null; } /** * Return a URL object of a resource that is mapped to the * specified context-relative path. * * @param path Context-relative path of the desired resource * * @exception MalformedURLException if the resource path is * not properly formed */ @Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } } return url; } /** * Return an InputStream allowing access to the resource at the * specified context-relative path. * * @param path Context-relative path of the desired resource */ @Override public InputStream getResourceAsStream(String path) { try { return (getResource(path).openStream()); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); } } /** * Return the set of resource paths for the "directory" at the * specified context path. * * @param path Context-relative base path */ @Override public Set<String> getResourcePaths(String path) { Set<String> thePaths = new HashSet<>(); if (!path.endsWith("/")) path += "/"; String basePath = getRealPath(path); if (basePath == null) return (thePaths); File theBaseDir = new File(basePath); if (!theBaseDir.exists() || !theBaseDir.isDirectory()) return (thePaths); String theFiles[] = theBaseDir.list(); for (int i = 0; i < theFiles.length; i++) { File testFile = new File(basePath + File.separator + theFiles[i]); if (testFile.isFile()) thePaths.add(path + theFiles[i]); else if (testFile.isDirectory()) thePaths.add(path + theFiles[i] + "/"); } return (thePaths); } /** * Return descriptive information about this server. */ @Override public String getServerInfo() { return ("JspC/ApacheTomcat8"); } /** * Return a null reference for the specified servlet name. * * @param name Name of the requested servlet * * @deprecated This method has been deprecated with no replacement */ @Override @Deprecated public Servlet getServlet(String name) throws ServletException { return null; } /** * Return the name of this servlet context. */ @Override public String getServletContextName() { return (getServerInfo()); } /** * Return an empty enumeration of servlet names. * * @deprecated This method has been deprecated with no replacement */ @Override @Deprecated public Enumeration<String> getServletNames() { return (new Vector<String>().elements()); } /** * Return an empty enumeration of servlets. * * @deprecated This method has been deprecated with no replacement */ @Override @Deprecated public Enumeration<Servlet> getServlets() { return (new Vector<Servlet>().elements()); } /** * Log the specified message. * * @param message The message to be logged */ @Override public void log(String message) { myLogWriter.println(message); } /** * Log the specified message and exception. * * @param exception The exception to be logged * @param message The message to be logged * * @deprecated Use log(String,Throwable) instead */ @Override @Deprecated public void log(Exception exception, String message) { log(message, exception); } /** * Log the specified message and exception. * * @param message The message to be logged * @param exception The exception to be logged */ @Override public void log(String message, Throwable exception) { myLogWriter.println(message); exception.printStackTrace(myLogWriter); } /** * Remove the specified context attribute. * * @param name Name of the attribute to remove */ @Override public void removeAttribute(String name) { myAttributes.remove(name); } /** * Set or replace the specified context attribute. * * @param name Name of the context attribute to set * @param value Corresponding attribute value */ @Override public void setAttribute(String name, Object value) { myAttributes.put(name, value); } @Override public FilterRegistration.Dynamic addFilter(String filterName, String className) { return null; } @Override public ServletRegistration.Dynamic addServlet(String servletName, String className) { return null; } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { return EnumSet.noneOf(SessionTrackingMode.class); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { return EnumSet.noneOf(SessionTrackingMode.class); } @Override public SessionCookieConfig getSessionCookieConfig() { return null; } @Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { // Do nothing } @Override public Dynamic addFilter(String filterName, Filter filter) { return null; } @Override public Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) { return null; } @Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { return null; } @Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) { return null; } @Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { return null; } @Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { return null; } @Override public FilterRegistration getFilterRegistration(String filterName) { return null; } @Override public ServletRegistration getServletRegistration(String servletName) { return null; } @Override public boolean setInitParameter(String name, String value) { return false; } @Override public void addListener(Class<? extends EventListener> listenerClass) { // NOOP } @Override public void addListener(String className) { // NOOP } @Override public <T extends EventListener> void addListener(T t) { // NOOP } @Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { return null; } @Override public void declareRoles(String... roleNames) { // NOOP } @Override public ClassLoader getClassLoader() { return loader; } public void setClassLoader(ClassLoader loader) { this.loader = loader; } @Override public int getEffectiveMajorVersion() { return webXml.getMajorVersion(); } @Override public int getEffectiveMinorVersion() { return webXml.getMinorVersion(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { return null; } @Override public JspConfigDescriptor getJspConfigDescriptor() { return jspConfigDescriptor; } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { return null; } @Override public String getVirtualServerName() { return null; } }
55,244
Bug 55244 JspC throws ClassNotFoundException from Digester
null
resolved fixed
8d6537d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-12T08:36:14Z
2013-07-12T06:20:00Z
java/org/apache/tomcat/util/descriptor/web/WebXmlParser.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.descriptor.web; import java.io.InputStream; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.descriptor.DigesterFactory; import org.apache.tomcat.util.descriptor.XmlErrorHandler; import org.apache.tomcat.util.digester.Digester; import org.apache.tomcat.util.res.StringManager; import org.xml.sax.InputSource; import org.xml.sax.SAXParseException; public class WebXmlParser { private static final Log log = LogFactory.getLog( WebXmlParser.class ); /** * The string resources for this package. */ private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); /** * The <code>Digester</code> we will use to process web application * deployment descriptor files. */ private final Digester webDigester; private final WebRuleSet webRuleSet; /** * The <code>Digester</code> we will use to process web fragment * deployment descriptor files. */ private final Digester webFragmentDigester; private final WebRuleSet webFragmentRuleSet; public WebXmlParser(boolean namespaceAware, boolean validation) { webRuleSet = new WebRuleSet(false); webDigester = DigesterFactory.newDigester(validation, namespaceAware, webRuleSet); webDigester.getParser(); webFragmentRuleSet = new WebRuleSet(true); webFragmentDigester = DigesterFactory.newDigester(validation, namespaceAware, webFragmentRuleSet); webFragmentDigester.getParser(); } public boolean parseWebXml(InputSource source, WebXml dest, boolean fragment) { boolean ok = true; if (source == null) { return ok; } XmlErrorHandler handler = new XmlErrorHandler(); Digester digester; WebRuleSet ruleSet; if (fragment) { digester = webFragmentDigester; ruleSet = webFragmentRuleSet; } else { digester = webDigester; ruleSet = webRuleSet; } digester.push(dest); digester.setErrorHandler(handler); if(log.isDebugEnabled()) { log.debug(sm.getString("webXmlParser.applicationStart", source.getSystemId())); } try { digester.parse(source); if (handler.getWarnings().size() > 0 || handler.getErrors().size() > 0) { ok = false; handler.logFindings(log, source.getSystemId()); } } catch (SAXParseException e) { log.error(sm.getString("webXmlParser.applicationParse", source.getSystemId()), e); log.error(sm.getString("webXmlParser.applicationPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; } catch (Exception e) { log.error(sm.getString("webXmlParser.applicationParse", source.getSystemId()), e); ok = false; } finally { InputStream is = source.getByteStream(); if (is != null) { try { is.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } digester.reset(); ruleSet.recycle(); } return ok; } }
55,250
Bug 55250 JspC does not initialize tldLocationsCache resulting in NPE
Change in how ServletContext was created missed initialization of tldLocationsCache
resolved fixed
186a782
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-12T08:50:45Z
2013-07-12T06:20:00Z
java/org/apache/jasper/JspC.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper; import java.io.BufferedReader; import java.io.CharArrayWriter; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.compiler.Compiler; import org.apache.jasper.compiler.JspConfig; import org.apache.jasper.compiler.JspRuntimeContext; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.compiler.TagPluginManager; import org.apache.jasper.compiler.TldLocationsCache; import org.apache.jasper.servlet.JspCServletContext; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tools.ant.AntClassLoader; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.apache.tools.ant.util.FileUtils; /** * Shell for the jspc compiler. Handles all options associated with the * command line and creates compilation contexts which it then compiles * according to the specified options. * * This version can process files from a _single_ webapp at once, i.e. * a single docbase can be specified. * * It can be used as an Ant task using: * <pre> * &lt;taskdef classname="org.apache.jasper.JspC" name="jasper" &gt; * &lt;classpath&gt; * &lt;pathelement location="${java.home}/../lib/tools.jar"/&gt; * &lt;fileset dir="${ENV.CATALINA_HOME}/lib"&gt; * &lt;include name="*.jar"/&gt; * &lt;/fileset&gt; * &lt;path refid="myjars"/&gt; * &lt;/classpath&gt; * &lt;/taskdef&gt; * * &lt;jasper verbose="0" * package="my.package" * uriroot="${webapps.dir}/${webapp.name}" * webXmlFragment="${build.dir}/generated_web.xml" * outputDir="${webapp.dir}/${webapp.name}/WEB-INF/src/my/package" /&gt; * </pre> * * @author Danno Ferrin * @author Pierre Delisle * @author Costin Manolache * @author Yoav Shapira */ public class JspC extends Task implements Options { public static final String DEFAULT_IE_CLASS_ID = "clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"; // Logger private static final Log log = LogFactory.getLog(JspC.class); protected static final String SWITCH_VERBOSE = "-v"; protected static final String SWITCH_HELP = "-help"; protected static final String SWITCH_OUTPUT_DIR = "-d"; protected static final String SWITCH_PACKAGE_NAME = "-p"; protected static final String SWITCH_CACHE = "-cache"; protected static final String SWITCH_CLASS_NAME = "-c"; protected static final String SWITCH_FULL_STOP = "--"; protected static final String SWITCH_COMPILE = "-compile"; protected static final String SWITCH_SOURCE = "-source"; protected static final String SWITCH_TARGET = "-target"; protected static final String SWITCH_URI_BASE = "-uribase"; protected static final String SWITCH_URI_ROOT = "-uriroot"; protected static final String SWITCH_FILE_WEBAPP = "-webapp"; protected static final String SWITCH_WEBAPP_INC = "-webinc"; protected static final String SWITCH_WEBAPP_XML = "-webxml"; protected static final String SWITCH_WEBAPP_XML_ENCODING = "-webxmlencoding"; protected static final String SWITCH_ADD_WEBAPP_XML_MAPPINGS = "-addwebxmlmappings"; protected static final String SWITCH_MAPPED = "-mapped"; protected static final String SWITCH_XPOWERED_BY = "-xpoweredBy"; protected static final String SWITCH_TRIM_SPACES = "-trimSpaces"; protected static final String SWITCH_CLASSPATH = "-classpath"; protected static final String SWITCH_DIE = "-die"; protected static final String SWITCH_POOLING = "-poolingEnabled"; protected static final String SWITCH_ENCODING = "-javaEncoding"; protected static final String SWITCH_SMAP = "-smap"; protected static final String SWITCH_DUMP_SMAP = "-dumpsmap"; protected static final String SHOW_SUCCESS ="-s"; protected static final String LIST_ERRORS = "-l"; protected static final int INC_WEBXML = 10; protected static final int ALL_WEBXML = 20; protected static final int DEFAULT_DIE_LEVEL = 1; protected static final int NO_DIE_LEVEL = 0; protected static final Set<String> insertBefore = new HashSet<>(); static { insertBefore.add("</web-app>"); insertBefore.add("<servlet-mapping>"); insertBefore.add("<session-config>"); insertBefore.add("<mime-mapping>"); insertBefore.add("<welcome-file-list>"); insertBefore.add("<error-page>"); insertBefore.add("<taglib>"); insertBefore.add("<resource-env-ref>"); insertBefore.add("<resource-ref>"); insertBefore.add("<security-constraint>"); insertBefore.add("<login-config>"); insertBefore.add("<security-role>"); insertBefore.add("<env-entry>"); insertBefore.add("<ejb-ref>"); insertBefore.add("<ejb-local-ref>"); } protected String classPath = null; protected URLClassLoader loader = null; protected boolean trimSpaces = false; protected boolean genStringAsCharArray = false; protected boolean xpoweredBy; protected boolean mappedFile = false; protected boolean poolingEnabled = true; protected File scratchDir; protected String ieClassId = DEFAULT_IE_CLASS_ID; protected String targetPackage; protected String targetClassName; protected String uriBase; protected String uriRoot; protected int dieLevel; protected boolean helpNeeded = false; protected boolean compile = false; protected boolean smapSuppressed = true; protected boolean smapDumped = false; protected boolean caching = true; protected final Map<String, TagLibraryInfo> cache = new HashMap<>(); protected String compiler = null; protected String compilerTargetVM = "1.6"; protected String compilerSourceVM = "1.6"; protected boolean classDebugInfo = true; /** * Throw an exception if there's a compilation error, or swallow it. * Default is true to preserve old behavior. */ protected boolean failOnError = true; /** * The file extensions to be handled as JSP files. * Default list is .jsp and .jspx. */ protected List<String> extensions; /** * The pages. */ protected final List<String> pages = new Vector<>(); /** * Needs better documentation, this data member does. * True by default. */ protected boolean errorOnUseBeanInvalidClassAttribute = true; /** * The java file encoding. Default * is UTF-8. Added per bugzilla 19622. */ protected String javaEncoding = "UTF-8"; // Generation of web.xml fragments protected String webxmlFile; protected int webxmlLevel; protected String webxmlEncoding; protected boolean addWebXmlMappings = false; protected Writer mapout; protected CharArrayWriter servletout; protected CharArrayWriter mappingout; /** * The servlet context. */ protected JspCServletContext context; /** * The runtime context. * Maintain a dummy JspRuntimeContext for compiling tag files. */ protected JspRuntimeContext rctxt; /** * Cache for the TLD locations */ protected TldLocationsCache tldLocationsCache = null; protected JspConfig jspConfig = null; protected TagPluginManager tagPluginManager = null; protected boolean verbose = false; protected boolean listErrors = false; protected boolean showSuccess = false; protected int argPos; protected boolean fullstop = false; protected String args[]; public static void main(String arg[]) { if (arg.length == 0) { System.out.println(Localizer.getMessage("jspc.usage")); } else { JspC jspc = new JspC(); try { jspc.setArgs(arg); if (jspc.helpNeeded) { System.out.println(Localizer.getMessage("jspc.usage")); } else { jspc.execute(); } } catch (JasperException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } catch (BuildException je) { System.err.println(je); if (jspc.dieLevel != NO_DIE_LEVEL) { System.exit(jspc.dieLevel); } } } } /** * Apply command-line arguments. * * @param arg * The arguments */ public void setArgs(String[] arg) throws JasperException { args = arg; String tok; dieLevel = NO_DIE_LEVEL; while ((tok = nextArg()) != null) { if (tok.equals(SWITCH_VERBOSE)) { verbose = true; showSuccess = true; listErrors = true; } else if (tok.equals(SWITCH_OUTPUT_DIR)) { tok = nextArg(); setOutputDir( tok ); } else if (tok.equals(SWITCH_PACKAGE_NAME)) { targetPackage = nextArg(); } else if (tok.equals(SWITCH_COMPILE)) { compile=true; } else if (tok.equals(SWITCH_CLASS_NAME)) { targetClassName = nextArg(); } else if (tok.equals(SWITCH_URI_BASE)) { uriBase=nextArg(); } else if (tok.equals(SWITCH_URI_ROOT)) { setUriroot( nextArg()); } else if (tok.equals(SWITCH_FILE_WEBAPP)) { setUriroot( nextArg()); } else if ( tok.equals( SHOW_SUCCESS ) ) { showSuccess = true; } else if ( tok.equals( LIST_ERRORS ) ) { listErrors = true; } else if (tok.equals(SWITCH_WEBAPP_INC)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = INC_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML)) { webxmlFile = nextArg(); if (webxmlFile != null) { webxmlLevel = ALL_WEBXML; } } else if (tok.equals(SWITCH_WEBAPP_XML_ENCODING)) { setWebXmlEncoding(nextArg()); } else if (tok.equals(SWITCH_ADD_WEBAPP_XML_MAPPINGS)) { setAddWebXmlMappings(true); } else if (tok.equals(SWITCH_MAPPED)) { mappedFile = true; } else if (tok.equals(SWITCH_XPOWERED_BY)) { xpoweredBy = true; } else if (tok.equals(SWITCH_TRIM_SPACES)) { setTrimSpaces(true); } else if (tok.equals(SWITCH_CACHE)) { tok = nextArg(); if ("false".equals(tok)) { caching = false; } else { caching = true; } } else if (tok.equals(SWITCH_CLASSPATH)) { setClassPath(nextArg()); } else if (tok.startsWith(SWITCH_DIE)) { try { dieLevel = Integer.parseInt( tok.substring(SWITCH_DIE.length())); } catch (NumberFormatException nfe) { dieLevel = DEFAULT_DIE_LEVEL; } } else if (tok.equals(SWITCH_HELP)) { helpNeeded = true; } else if (tok.equals(SWITCH_POOLING)) { tok = nextArg(); if ("false".equals(tok)) { poolingEnabled = false; } else { poolingEnabled = true; } } else if (tok.equals(SWITCH_ENCODING)) { setJavaEncoding(nextArg()); } else if (tok.equals(SWITCH_SOURCE)) { setCompilerSourceVM(nextArg()); } else if (tok.equals(SWITCH_TARGET)) { setCompilerTargetVM(nextArg()); } else if (tok.equals(SWITCH_SMAP)) { smapSuppressed = false; } else if (tok.equals(SWITCH_DUMP_SMAP)) { smapDumped = true; } else { if (tok.startsWith("-")) { throw new JasperException("Unrecognized option: " + tok + ". Use -help for help."); } if (!fullstop) { argPos--; } // Start treating the rest as JSP Pages break; } } // Add all extra arguments to the list of files while( true ) { String file = nextFile(); if( file==null ) { break; } pages.add( file ); } } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getKeepGenerated() { // isn't this why we are running jspc? return true; } /** * {@inheritDoc} */ @Override public boolean getTrimSpaces() { return trimSpaces; } /** * Sets the option to trim white spaces between directives or actions. */ public void setTrimSpaces(boolean ts) { this.trimSpaces = ts; } /** * {@inheritDoc} */ @Override public boolean isPoolingEnabled() { return poolingEnabled; } /** * Sets the option to enable the tag handler pooling. */ public void setPoolingEnabled(boolean poolingEnabled) { this.poolingEnabled = poolingEnabled; } /** * {@inheritDoc} */ @Override public boolean isXpoweredBy() { return xpoweredBy; } /** * Sets the option to enable generation of X-Powered-By response header. */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; } /** * In JspC this always returns <code>true</code>. * {@inheritDoc} */ @Override public boolean getDisplaySourceFragment() { return true; } @Override public int getMaxLoadedJsps() { return -1; } @Override public int getJspIdleTimeout() { return -1; } /** * {@inheritDoc} */ @Override public boolean getErrorOnUseBeanInvalidClassAttribute() { return errorOnUseBeanInvalidClassAttribute; } /** * Sets the option to issue a compilation error if the class attribute * specified in useBean action is invalid. */ public void setErrorOnUseBeanInvalidClassAttribute(boolean b) { errorOnUseBeanInvalidClassAttribute = b; } /** * {@inheritDoc} */ @Override public boolean getMappedFile() { return mappedFile; } /** * Sets the option to include debug information in compiled class. */ public void setClassDebugInfo( boolean b ) { classDebugInfo=b; } /** * {@inheritDoc} */ @Override public boolean getClassDebugInfo() { // compile with debug info return classDebugInfo; } /** * {@inheritDoc} */ @Override public boolean isCaching() { return caching; } /** * Sets the option to enable caching. * * @see Options#isCaching() */ public void setCaching(boolean caching) { this.caching = caching; } /** * {@inheritDoc} */ @Override public Map<String, TagLibraryInfo> getCache() { return cache; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getCheckInterval() { return 0; } /** * In JspC this always returns <code>0</code>. * {@inheritDoc} */ @Override public int getModificationTestInterval() { return 0; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getRecompileOnFail() { return false; } /** * In JspC this always returns <code>false</code>. * {@inheritDoc} */ @Override public boolean getDevelopment() { return false; } /** * {@inheritDoc} */ @Override public boolean isSmapSuppressed() { return smapSuppressed; } /** * Sets smapSuppressed flag. */ public void setSmapSuppressed(boolean smapSuppressed) { this.smapSuppressed = smapSuppressed; } /** * {@inheritDoc} */ @Override public boolean isSmapDumped() { return smapDumped; } /** * Sets smapDumped flag. * * @see Options#isSmapDumped() */ public void setSmapDumped(boolean smapDumped) { this.smapDumped = smapDumped; } /** * Determines whether text strings are to be generated as char arrays, * which improves performance in some cases. * * @param genStringAsCharArray true if text strings are to be generated as * char arrays, false otherwise */ public void setGenStringAsCharArray(boolean genStringAsCharArray) { this.genStringAsCharArray = genStringAsCharArray; } /** * {@inheritDoc} */ @Override public boolean genStringAsCharArray() { return genStringAsCharArray; } /** * Sets the class-id value to be sent to Internet Explorer when using * &lt;jsp:plugin&gt; tags. * * @param ieClassId * Class-id value */ public void setIeClassId(String ieClassId) { this.ieClassId = ieClassId; } /** * {@inheritDoc} */ @Override public String getIeClassId() { return ieClassId; } /** * {@inheritDoc} */ @Override public File getScratchDir() { return scratchDir; } /** * {@inheritDoc} */ @Override public String getCompiler() { return compiler; } /** * Sets the option to determine what compiler to use. * * @see Options#getCompiler() */ public void setCompiler(String c) { compiler=c; } /** * {@inheritDoc} */ @Override public String getCompilerClassName() { return null; } /** * {@inheritDoc} */ @Override public String getCompilerTargetVM() { return compilerTargetVM; } /** * Sets the compiler target VM. * * @see Options#getCompilerTargetVM() */ public void setCompilerTargetVM(String vm) { compilerTargetVM = vm; } /** * {@inheritDoc} */ @Override public String getCompilerSourceVM() { return compilerSourceVM; } /** * Sets the compiler source VM. * * @see Options#getCompilerSourceVM() */ public void setCompilerSourceVM(String vm) { compilerSourceVM = vm; } /** * {@inheritDoc} */ @Override public TldLocationsCache getTldLocationsCache() { return tldLocationsCache; } /** * Returns the encoding to use for * java files. The default is UTF-8. * * @return String The encoding */ @Override public String getJavaEncoding() { return javaEncoding; } /** * Sets the encoding to use for * java files. * * @param encodingName The name, e.g. "UTF-8" */ public void setJavaEncoding(String encodingName) { javaEncoding = encodingName; } /** * {@inheritDoc} */ @Override public boolean getFork() { return false; } /** * {@inheritDoc} */ @Override public String getClassPath() { if( classPath != null ) return classPath; return System.getProperty("java.class.path"); } /** * Sets the classpath used while compiling the servlets generated from JSP * files */ public void setClassPath(String s) { classPath=s; } /** * Returns the list of file extensions * that are treated as JSP files. * * @return The list of extensions */ public List<String> getExtensions() { return extensions; } /** * Adds the given file extension to the * list of extensions handled as JSP files. * * @param extension The extension to add, e.g. "myjsp" */ protected void addExtension(final String extension) { if(extension != null) { if(extensions == null) { extensions = new Vector<>(); } extensions.add(extension); } } /** * Base dir for the webapp. Used to generate class names and resolve * includes. */ public void setUriroot( String s ) { if (s == null) { uriRoot = null; return; } try { uriRoot = resolveFile(s).getCanonicalPath(); } catch( Exception ex ) { uriRoot = s; } } /** * Parses comma-separated list of JSP files to be processed. If the argument * is null, nothing is done. * * <p>Each file is interpreted relative to uriroot, unless it is absolute, * in which case it must start with uriroot.</p> * * @param jspFiles Comma-separated list of JSP files to be processed */ public void setJspFiles(final String jspFiles) { if(jspFiles == null) { return; } StringTokenizer tok = new StringTokenizer(jspFiles, ","); while (tok.hasMoreTokens()) { pages.add(tok.nextToken()); } } /** * Sets the compile flag. * * @param b Flag value */ public void setCompile( final boolean b ) { compile = b; } /** * Sets the verbosity level. The actual number doesn't * matter: if it's greater than zero, the verbose flag will * be true. * * @param level Positive means verbose */ public void setVerbose( final int level ) { if (level > 0) { verbose = true; showSuccess = true; listErrors = true; } } public void setValidateXml( boolean b ) { org.apache.jasper.xmlparser.ParserUtils.validating=b; } public void setListErrors( boolean b ) { listErrors = b; } public void setOutputDir( String s ) { if( s!= null ) { scratchDir = resolveFile(s).getAbsoluteFile(); } else { scratchDir=null; } } /** * Sets the package name to be used for the generated servlet classes. */ public void setPackage( String p ) { targetPackage=p; } /** * Class name of the generated file ( without package ). * Can only be used if a single file is converted. * XXX Do we need this feature ? */ public void setClassName( String p ) { targetClassName=p; } /** * File where we generate a web.xml fragment with the class definitions. */ public void setWebXmlFragment( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=INC_WEBXML; } /** * File where we generate a complete web.xml with the class definitions. */ public void setWebXml( String s ) { webxmlFile=resolveFile(s).getAbsolutePath(); webxmlLevel=ALL_WEBXML; } /** * Sets the encoding to be used to read and write web.xml files. * * <p> * If not specified, defaults to the platform default encoding. * </p> * * @param encoding * Encoding, e.g. "UTF-8". */ public void setWebXmlEncoding(String encoding) { webxmlEncoding = encoding; } /** * Sets the option to merge generated web.xml fragment into the * WEB-INF/web.xml file of the web application that we were processing. * * @param b * <code>true</code> to merge the fragment into the existing * web.xml file of the processed web application * ({uriroot}/WEB-INF/web.xml), <code>false</code> to keep the * generated web.xml fragment */ public void setAddWebXmlMappings(boolean b) { addWebXmlMappings = b; } /** * Sets the option that throws an exception in case of a compilation error. */ public void setFailOnError(final boolean b) { failOnError = b; } /** * Returns true if an exception will be thrown in case of a compilation * error. */ public boolean getFailOnError() { return failOnError; } /** * {@inheritDoc} */ @Override public JspConfig getJspConfig() { return jspConfig; } /** * {@inheritDoc} */ @Override public TagPluginManager getTagPluginManager() { return tagPluginManager; } /** * Adds servlet declaration and mapping for the JSP page servlet to the * generated web.xml fragment. * * @param file * Context-relative path to the JSP file, e.g. * <code>/index.jsp</code> * @param clctxt * Compilation context of the servlet */ public void generateWebMapping( String file, JspCompilationContext clctxt ) throws IOException { if (log.isDebugEnabled()) { log.debug("Generating web mapping for file " + file + " using compilation context " + clctxt); } String className = clctxt.getServletClassName(); String packageName = clctxt.getServletPackageName(); String thisServletName; if ("".equals(packageName)) { thisServletName = className; } else { thisServletName = packageName + '.' + className; } if (servletout != null) { servletout.write("\n <servlet>\n <servlet-name>"); servletout.write(thisServletName); servletout.write("</servlet-name>\n <servlet-class>"); servletout.write(thisServletName); servletout.write("</servlet-class>\n </servlet>\n"); } if (mappingout != null) { mappingout.write("\n <servlet-mapping>\n <servlet-name>"); mappingout.write(thisServletName); mappingout.write("</servlet-name>\n <url-pattern>"); mappingout.write(file.replace('\\', '/')); mappingout.write("</url-pattern>\n </servlet-mapping>\n"); } } /** * Include the generated web.xml inside the webapp's web.xml. */ protected void mergeIntoWebXml() throws IOException { File webappBase = new File(uriRoot); File webXml = new File(webappBase, "WEB-INF/web.xml"); File webXml2 = new File(webappBase, "WEB-INF/web2.xml"); String insertStartMarker = Localizer.getMessage("jspc.webinc.insertStart"); String insertEndMarker = Localizer.getMessage("jspc.webinc.insertEnd"); BufferedReader reader = new BufferedReader(openWebxmlReader(webXml)); BufferedReader fragmentReader = new BufferedReader( openWebxmlReader(new File(webxmlFile))); PrintWriter writer = new PrintWriter(openWebxmlWriter(webXml2)); // Insert the <servlet> and <servlet-mapping> declarations boolean inserted = false; int current = reader.read(); while (current > -1) { if (current == '<') { String element = getElement(reader); if (!inserted && insertBefore.contains(element)) { // Insert generated content here writer.println(insertStartMarker); while (true) { String line = fragmentReader.readLine(); if (line == null) { writer.println(); break; } writer.println(line); } writer.println(insertEndMarker); writer.println(); writer.write(element); inserted = true; } else if (element.equals(insertStartMarker)) { // Skip the previous auto-generated content while (true) { current = reader.read(); if (current < 0) { throw new EOFException(); } if (current == '<') { element = getElement(reader); if (element.equals(insertEndMarker)) { break; } } } current = reader.read(); while (current == '\n' || current == '\r') { current = reader.read(); } continue; } else { writer.write(element); } } else { writer.write(current); } current = reader.read(); } writer.close(); reader.close(); fragmentReader.close(); FileInputStream fis = new FileInputStream(webXml2); FileOutputStream fos = new FileOutputStream(webXml); byte buf[] = new byte[512]; while (true) { int n = fis.read(buf); if (n < 0) { break; } fos.write(buf, 0, n); } fis.close(); fos.close(); if(!webXml2.delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webXml2.toString())); if (!(new File(webxmlFile)).delete() && log.isDebugEnabled()) log.debug(Localizer.getMessage("jspc.delete.fail", webxmlFile)); } /* * Assumes valid xml */ private String getElement(Reader reader) throws IOException { StringBuilder result = new StringBuilder(); result.append('<'); boolean done = false; while (!done) { int current = reader.read(); while (current != '>') { if (current < 0) { throw new EOFException(); } result.append((char) current); current = reader.read(); } result.append((char) current); int len = result.length(); if (len > 4 && result.substring(0, 4).equals("<!--")) { // This is a comment - make sure we are at the end if (len >= 7 && result.substring(len - 3, len).equals("-->")) { done = true; } } else { done = true; } } return result.toString(); } protected void processFile(String file) throws JasperException { if (log.isDebugEnabled()) { log.debug("Processing file: " + file); } ClassLoader originalClassLoader = null; try { // set up a scratch/output dir if none is provided if (scratchDir == null) { String temp = System.getProperty("java.io.tmpdir"); if (temp == null) { temp = ""; } scratchDir = new File(new File(temp).getAbsolutePath()); } String jspUri=file.replace('\\','/'); JspCompilationContext clctxt = new JspCompilationContext ( jspUri, this, context, null, rctxt ); /* Override the defaults */ if ((targetClassName != null) && (targetClassName.length() > 0)) { clctxt.setServletClassName(targetClassName); targetClassName = null; } if (targetPackage != null) { clctxt.setServletPackageName(targetPackage); } originalClassLoader = Thread.currentThread().getContextClassLoader(); if( loader==null ) { initClassLoader( clctxt ); } Thread.currentThread().setContextClassLoader(loader); clctxt.setClassLoader(loader); clctxt.setClassPath(classPath); Compiler clc = clctxt.createCompiler(); // If compile is set, generate both .java and .class, if // .jsp file is newer than .class file; // Otherwise only generate .java, if .jsp file is newer than // the .java file if( clc.isOutDated(compile) ) { if (log.isDebugEnabled()) { log.debug(jspUri + " is out dated, compiling..."); } clc.compile(compile, true); } // Generate mapping generateWebMapping( file, clctxt ); if ( showSuccess ) { log.info( "Built File: " + file ); } } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { log.error(Localizer.getMessage("jspc.error.generalException", file), rootCause); } // Bugzilla 35114. if(getFailOnError()) { throw je; } else { log.error(je.getMessage()); } } catch (Exception e) { if ((e instanceof FileNotFoundException) && log.isWarnEnabled()) { log.warn(Localizer.getMessage("jspc.error.fileDoesNotExist", e.getMessage())); } throw new JasperException(e); } finally { if(originalClassLoader != null) { Thread.currentThread().setContextClassLoader(originalClassLoader); } } } /** * Locate all jsp files in the webapp. Used if no explicit * jsps are specified. */ public void scanFiles( File base ) { Stack<String> dirs = new Stack<>(); dirs.push(base.toString()); // Make sure default extensions are always included if ((getExtensions() == null) || (getExtensions().size() < 2)) { addExtension("jsp"); addExtension("jspx"); } while (!dirs.isEmpty()) { String s = dirs.pop(); File f = new File(s); if (f.exists() && f.isDirectory()) { String[] files = f.list(); String ext; for (int i = 0; (files != null) && i < files.length; i++) { File f2 = new File(s, files[i]); if (f2.isDirectory()) { dirs.push(f2.getPath()); } else { String path = f2.getPath(); String uri = path.substring(uriRoot.length()); ext = files[i].substring(files[i].lastIndexOf('.') +1); if (getExtensions().contains(ext) || jspConfig.isJspPage(uri)) { pages.add(path); } } } } } } /** * Executes the compilation. */ @Override public void execute() { if(log.isDebugEnabled()) { log.debug("execute() starting for " + pages.size() + " pages."); } try { if (uriRoot == null) { if( pages.size() == 0 ) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.missingTarget")); } String firstJsp = pages.get( 0 ); File firstJspF = new File( firstJsp ); if (!firstJspF.exists()) { throw new JasperException( Localizer.getMessage("jspc.error.fileDoesNotExist", firstJsp)); } locateUriRoot( firstJspF ); } if (uriRoot == null) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.no_uriroot")); } File uriRootF = new File(uriRoot); if (!uriRootF.isDirectory()) { throw new JasperException( Localizer.getMessage("jsp.error.jspc.uriroot_not_dir")); } if (context == null) { initServletContext(); } // No explicit pages, we'll process all .jsp in the webapp if (pages.size() == 0) { scanFiles(uriRootF); } initWebXml(); Iterator<String> iter = pages.iterator(); while (iter.hasNext()) { String nextjsp = iter.next().toString(); File fjsp = new File(nextjsp); if (!fjsp.isAbsolute()) { fjsp = new File(uriRootF, nextjsp); } if (!fjsp.exists()) { if (log.isWarnEnabled()) { log.warn (Localizer.getMessage ("jspc.error.fileDoesNotExist", fjsp.toString())); } continue; } String s = fjsp.getAbsolutePath(); if (s.startsWith(uriRoot)) { nextjsp = s.substring(uriRoot.length()); } if (nextjsp.startsWith("." + File.separatorChar)) { nextjsp = nextjsp.substring(2); } processFile(nextjsp); } completeWebXml(); if (addWebXmlMappings) { mergeIntoWebXml(); } } catch (IOException ioe) { throw new BuildException(ioe); } catch (JasperException je) { Throwable rootCause = je; while (rootCause instanceof JasperException && ((JasperException) rootCause).getRootCause() != null) { rootCause = ((JasperException) rootCause).getRootCause(); } if (rootCause != je) { rootCause.printStackTrace(); } throw new BuildException(je); } finally { if (loader != null) { LogFactory.release(loader); } } } // ==================== protected utility methods ==================== protected String nextArg() { if ((argPos >= args.length) || (fullstop = SWITCH_FULL_STOP.equals(args[argPos]))) { return null; } else { return args[argPos++]; } } protected String nextFile() { if (fullstop) argPos++; if (argPos >= args.length) { return null; } else { return args[argPos++]; } } protected void initWebXml() { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header")); mapout.flush(); } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; } } protected void completeWebXml() { if (mapout != null) { try { servletout.writeTo(mapout); mappingout.writeTo(mapout); if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.footer")); } else if ((webxmlLevel >= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.footer")); } mapout.close(); } catch (IOException ioe) { // nothing to do if it fails since we are done with it } } } protected void initServletContext() throws IOException, JasperException { // TODO: should we use the Ant Project's log? PrintWriter log = new PrintWriter(System.out); URL resourceBase = new File(uriRoot).getCanonicalFile().toURI().toURL(); context = new JspCServletContext(log, resourceBase); rctxt = new JspRuntimeContext(context, this); jspConfig = new JspConfig(context); tagPluginManager = new TagPluginManager(context); } /** * Initializes the classloader as/if needed for the given * compilation context. * * @param clctxt The compilation context * @throws IOException If an error occurs */ protected void initClassLoader(JspCompilationContext clctxt) throws IOException { classPath = getClassPath(); ClassLoader jspcLoader = getClass().getClassLoader(); if (jspcLoader instanceof AntClassLoader) { classPath += File.pathSeparator + ((AntClassLoader) jspcLoader).getClasspath(); } // Turn the classPath into URLs ArrayList<URL> urls = new ArrayList<>(); StringTokenizer tokenizer = new StringTokenizer(classPath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { String path = tokenizer.nextToken(); try { File libFile = new File(path); urls.add(libFile.toURI().toURL()); } catch (IOException ioe) { // Failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak uot throw new RuntimeException(ioe.toString()); } } File webappBase = new File(uriRoot); if (webappBase.exists()) { File classes = new File(webappBase, "/WEB-INF/classes"); try { if (classes.exists()) { classPath = classPath + File.pathSeparator + classes.getCanonicalPath(); urls.add(classes.getCanonicalFile().toURI().toURL()); } } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } File lib = new File(webappBase, "/WEB-INF/lib"); if (lib.exists() && lib.isDirectory()) { String[] libs = lib.list(); for (int i = 0; i < libs.length; i++) { if( libs[i].length() <5 ) continue; String ext=libs[i].substring( libs[i].length() - 4 ); if (! ".jar".equalsIgnoreCase(ext)) { if (".tld".equalsIgnoreCase(ext)) { log.warn("TLD files should not be placed in " + "/WEB-INF/lib"); } continue; } try { File libFile = new File(lib, libs[i]); classPath = classPath + File.pathSeparator + libFile.getAbsolutePath(); urls.add(libFile.getAbsoluteFile().toURI().toURL()); } catch (IOException ioe) { // failing a toCanonicalPath on a file that // exists() should be a JVM regression test, // therefore we have permission to freak out throw new RuntimeException(ioe.toString()); } } } } // What is this ?? urls.add(new File( clctxt.getRealPath("/")).getCanonicalFile().toURI().toURL()); URL urlsA[]=new URL[urls.size()]; urls.toArray(urlsA); loader = new URLClassLoader(urlsA, this.getClass().getClassLoader()); context.setClassLoader(loader); } /** * Find the WEB-INF dir by looking up in the directory tree. * This is used if no explicit docbase is set, but only files. * XXX Maybe we should require the docbase. */ protected void locateUriRoot( File f ) { String tUriBase = uriBase; if (tUriBase == null) { tUriBase = "/"; } try { if (f.exists()) { f = new File(f.getAbsolutePath()); while (true) { File g = new File(f, "WEB-INF"); if (g.exists() && g.isDirectory()) { uriRoot = f.getCanonicalPath(); uriBase = tUriBase; if (log.isInfoEnabled()) { log.info(Localizer.getMessage( "jspc.implicit.uriRoot", uriRoot)); } break; } if (f.exists() && f.isDirectory()) { tUriBase = "/" + f.getName() + "/" + tUriBase; } String fParent = f.getParent(); if (fParent == null) { break; } else { f = new File(fParent); } // If there is no acceptable candidate, uriRoot will // remain null to indicate to the CompilerContext to // use the current working/user dir. } if (uriRoot != null) { File froot = new File(uriRoot); uriRoot = froot.getCanonicalPath(); } } } catch (IOException ioe) { // since this is an optional default and a null value // for uriRoot has a non-error meaning, we can just // pass straight through } } /** * Resolves the relative or absolute pathname correctly * in both Ant and command-line situations. If Ant launched * us, we should use the basedir of the current project * to resolve relative paths. * * See Bugzilla 35571. * * @param s The file * @return The file resolved */ protected File resolveFile(final String s) { if(getProject() == null) { // Note FileUtils.getFileUtils replaces FileUtils.newFileUtils in Ant 1.6.3 return FileUtils.getFileUtils().resolveFile(null, s); } else { return FileUtils.getFileUtils().resolveFile(getProject().getBaseDir(), s); } } private Reader openWebxmlReader(File file) throws IOException { FileInputStream fis = new FileInputStream(file); try { return webxmlEncoding != null ? new InputStreamReader(fis, webxmlEncoding) : new InputStreamReader(fis); } catch (IOException ex) { fis.close(); throw ex; } } private Writer openWebxmlWriter(File file) throws IOException { FileOutputStream fos = new FileOutputStream(file); try { return webxmlEncoding != null ? new OutputStreamWriter(fos, webxmlEncoding) : new OutputStreamWriter(fos); } catch (IOException ex) { fos.close(); throw ex; } } }
55,245
Bug 55245 Add test cases for JspC
The test suite should include tests for the JspC Ant task
resolved fixed
c0c5017
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-12T08:58:10Z
2013-07-12T06:20:00Z
test/org/apache/jasper/TestJspC.java
55,259
Bug 55259 Unnecessary work in JspConfig
JspProperty is the same for all url patterns in a group; the current code creates a new one each iteration
resolved fixed
c6a45a6
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-07-13T22:07:49Z
2013-07-13T07:20:00Z
java/org/apache/jasper/compiler/JspConfig.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.util.Collection; import java.util.Iterator; import java.util.Vector; import javax.servlet.ServletContext; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.descriptor.JspPropertyGroupDescriptor; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * Handles the jsp-config element in WEB_INF/web.xml. This is used * for specifying the JSP configuration information on a JSP page * * @author Kin-man Chung * @author Remy Maucherat */ public class JspConfig { // Logger private final Log log = LogFactory.getLog(JspConfig.class); private Vector<JspPropertyGroup> jspProperties = null; private final ServletContext ctxt; private volatile boolean initialized = false; private static final String defaultIsXml = null; // unspecified private String defaultIsELIgnored = null; // unspecified private static final String defaultIsScriptingInvalid = null; private String defaultDeferedSyntaxAllowedAsLiteral = null; private static final String defaultTrimDirectiveWhitespaces = null; private static final String defaultDefaultContentType = null; private static final String defaultBuffer = null; private static final String defaultErrorOnUndeclaredNamespace = "false"; private JspProperty defaultJspProperty; public JspConfig(ServletContext ctxt) { this.ctxt = ctxt; } private void processWebDotXml() { // Very, very unlikely but just in case... if (ctxt.getEffectiveMajorVersion() < 2) { defaultIsELIgnored = "true"; defaultDeferedSyntaxAllowedAsLiteral = "true"; return; } if (ctxt.getEffectiveMajorVersion() == 2) { if (ctxt.getEffectiveMinorVersion() < 5) { defaultDeferedSyntaxAllowedAsLiteral = "true"; } if (ctxt.getEffectiveMinorVersion() < 4) { defaultIsELIgnored = "true"; return; } } JspConfigDescriptor jspConfig = ctxt.getJspConfigDescriptor(); if (jspConfig == null) { return; } jspProperties = new Vector<>(); Collection<JspPropertyGroupDescriptor> jspPropertyGroups = jspConfig.getJspPropertyGroups(); for (JspPropertyGroupDescriptor jspPropertyGroup : jspPropertyGroups) { Collection<String> urlPatterns = jspPropertyGroup.getUrlPatterns(); if (urlPatterns.size() == 0) { continue; } // Add one JspPropertyGroup for each URL Pattern. This makes // the matching logic easier. for (String urlPattern : urlPatterns) { String path = null; String extension = null; if (urlPattern.indexOf('*') < 0) { // Exact match path = urlPattern; } else { int i = urlPattern.lastIndexOf('/'); String file; if (i >= 0) { path = urlPattern.substring(0,i+1); file = urlPattern.substring(i+1); } else { file = urlPattern; } // pattern must be "*", or of the form "*.jsp" if (file.equals("*")) { extension = "*"; } else if (file.startsWith("*.")) { extension = file.substring(file.indexOf('.')+1); } // The url patterns are reconstructed as the following: // path != null, extension == null: / or /foo/bar.ext // path == null, extension != null: *.ext // path != null, extension == "*": /foo/* boolean isStar = "*".equals(extension); if ((path == null && (extension == null || isStar)) || (path != null && !isStar)) { if (log.isWarnEnabled()) { log.warn(Localizer.getMessage( "jsp.warning.bad.urlpattern.propertygroup", urlPattern)); } continue; } } Vector<String> includePreludes = new Vector<>(); includePreludes.addAll(jspPropertyGroup.getIncludePreludes()); Vector<String> includeCodas = new Vector<>(); includeCodas.addAll(jspPropertyGroup.getIncludeCodas()); JspProperty property = new JspProperty(jspPropertyGroup.getIsXml(), jspPropertyGroup.getElIgnored(), jspPropertyGroup.getScriptingInvalid(), jspPropertyGroup.getPageEncoding(), includePreludes, includeCodas, jspPropertyGroup.getDeferredSyntaxAllowedAsLiteral(), jspPropertyGroup.getTrimDirectiveWhitespaces(), jspPropertyGroup.getDefaultContentType(), jspPropertyGroup.getBuffer(), jspPropertyGroup.getErrorOnUndeclaredNamespace()); JspPropertyGroup propertyGroup = new JspPropertyGroup(path, extension, property); jspProperties.addElement(propertyGroup); } } } private void init() { if (!initialized) { synchronized (this) { if (!initialized) { processWebDotXml(); defaultJspProperty = new JspProperty(defaultIsXml, defaultIsELIgnored, defaultIsScriptingInvalid, null, null, null, defaultDeferedSyntaxAllowedAsLiteral, defaultTrimDirectiveWhitespaces, defaultDefaultContentType, defaultBuffer, defaultErrorOnUndeclaredNamespace); initialized = true; } } } } /** * Select the property group that has more restrictive url-pattern. * In case of tie, select the first. */ @SuppressWarnings("null") // NPE not possible private JspPropertyGroup selectProperty(JspPropertyGroup prev, JspPropertyGroup curr) { if (prev == null) { return curr; } if (prev.getExtension() == null) { // exact match return prev; } if (curr.getExtension() == null) { // exact match return curr; } String prevPath = prev.getPath(); String currPath = curr.getPath(); if (prevPath == null && currPath == null) { // Both specifies a *.ext, keep the first one return prev; } if (prevPath == null && currPath != null) { return curr; } if (prevPath != null && currPath == null) { return prev; } if (prevPath.length() >= currPath.length()) { return prev; } return curr; } /** * Find a property that best matches the supplied resource. * @param uri the resource supplied. * @return a JspProperty indicating the best match, or some default. */ public JspProperty findJspProperty(String uri) { init(); // JSP Configuration settings do not apply to tag files if (jspProperties == null || uri.endsWith(".tag") || uri.endsWith(".tagx")) { return defaultJspProperty; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Vector<String> includePreludes = new Vector<>(); Vector<String> includeCodas = new Vector<>(); JspPropertyGroup isXmlMatch = null; JspPropertyGroup elIgnoredMatch = null; JspPropertyGroup scriptingInvalidMatch = null; JspPropertyGroup pageEncodingMatch = null; JspPropertyGroup deferedSyntaxAllowedAsLiteralMatch = null; JspPropertyGroup trimDirectiveWhitespacesMatch = null; JspPropertyGroup defaultContentTypeMatch = null; JspPropertyGroup bufferMatch = null; JspPropertyGroup errorOnUndeclaredNamespaceMatch = null; Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); JspProperty jp = jpg.getJspProperty(); // (arrays will be the same length) String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { // exact match pattern: /a/foo.jsp if (!uri.equals(path)) { // not matched; continue; } } else { // Matching patterns *.ext or /p/* if (path != null && uriPath != null && ! uriPath.startsWith(path)) { // not matched continue; } if (!extension.equals("*") && !extension.equals(uriExtension)) { // not matched continue; } } // We have a match // Add include-preludes and include-codas if (jp.getIncludePrelude() != null) { includePreludes.addAll(jp.getIncludePrelude()); } if (jp.getIncludeCoda() != null) { includeCodas.addAll(jp.getIncludeCoda()); } // If there is a previous match for the same property, remember // the one that is more restrictive. if (jp.isXml() != null) { isXmlMatch = selectProperty(isXmlMatch, jpg); } if (jp.isELIgnored() != null) { elIgnoredMatch = selectProperty(elIgnoredMatch, jpg); } if (jp.isScriptingInvalid() != null) { scriptingInvalidMatch = selectProperty(scriptingInvalidMatch, jpg); } if (jp.getPageEncoding() != null) { pageEncodingMatch = selectProperty(pageEncodingMatch, jpg); } if (jp.isDeferedSyntaxAllowedAsLiteral() != null) { deferedSyntaxAllowedAsLiteralMatch = selectProperty(deferedSyntaxAllowedAsLiteralMatch, jpg); } if (jp.isTrimDirectiveWhitespaces() != null) { trimDirectiveWhitespacesMatch = selectProperty(trimDirectiveWhitespacesMatch, jpg); } if (jp.getDefaultContentType() != null) { defaultContentTypeMatch = selectProperty(defaultContentTypeMatch, jpg); } if (jp.getBuffer() != null) { bufferMatch = selectProperty(bufferMatch, jpg); } if (jp.isErrorOnUndeclaredNamespace() != null) { errorOnUndeclaredNamespaceMatch = selectProperty(errorOnUndeclaredNamespaceMatch, jpg); } } String isXml = defaultIsXml; String isELIgnored = defaultIsELIgnored; String isScriptingInvalid = defaultIsScriptingInvalid; String pageEncoding = null; String isDeferedSyntaxAllowedAsLiteral = defaultDeferedSyntaxAllowedAsLiteral; String isTrimDirectiveWhitespaces = defaultTrimDirectiveWhitespaces; String defaultContentType = defaultDefaultContentType; String buffer = defaultBuffer; String errorOnUndelcaredNamespace = defaultErrorOnUndeclaredNamespace; if (isXmlMatch != null) { isXml = isXmlMatch.getJspProperty().isXml(); } if (elIgnoredMatch != null) { isELIgnored = elIgnoredMatch.getJspProperty().isELIgnored(); } if (scriptingInvalidMatch != null) { isScriptingInvalid = scriptingInvalidMatch.getJspProperty().isScriptingInvalid(); } if (pageEncodingMatch != null) { pageEncoding = pageEncodingMatch.getJspProperty().getPageEncoding(); } if (deferedSyntaxAllowedAsLiteralMatch != null) { isDeferedSyntaxAllowedAsLiteral = deferedSyntaxAllowedAsLiteralMatch.getJspProperty().isDeferedSyntaxAllowedAsLiteral(); } if (trimDirectiveWhitespacesMatch != null) { isTrimDirectiveWhitespaces = trimDirectiveWhitespacesMatch.getJspProperty().isTrimDirectiveWhitespaces(); } if (defaultContentTypeMatch != null) { defaultContentType = defaultContentTypeMatch.getJspProperty().getDefaultContentType(); } if (bufferMatch != null) { buffer = bufferMatch.getJspProperty().getBuffer(); } if (errorOnUndeclaredNamespaceMatch != null) { errorOnUndelcaredNamespace = errorOnUndeclaredNamespaceMatch.getJspProperty().isErrorOnUndeclaredNamespace(); } return new JspProperty(isXml, isELIgnored, isScriptingInvalid, pageEncoding, includePreludes, includeCodas, isDeferedSyntaxAllowedAsLiteral, isTrimDirectiveWhitespaces, defaultContentType, buffer, errorOnUndelcaredNamespace); } /** * To find out if an uri matches an url pattern in jsp config. If so, * then the uri is a JSP page. This is used primarily for jspc. */ public boolean isJspPage(String uri) { init(); if (jspProperties == null) { return false; } String uriPath = null; int index = uri.lastIndexOf('/'); if (index >=0 ) { uriPath = uri.substring(0, index+1); } String uriExtension = null; index = uri.lastIndexOf('.'); if (index >=0) { uriExtension = uri.substring(index+1); } Iterator<JspPropertyGroup> iter = jspProperties.iterator(); while (iter.hasNext()) { JspPropertyGroup jpg = iter.next(); String extension = jpg.getExtension(); String path = jpg.getPath(); if (extension == null) { if (uri.equals(path)) { // There is an exact match return true; } } else { if ((path == null || path.equals(uriPath)) && (extension.equals("*") || extension.equals(uriExtension))) { // Matches *, *.ext, /p/*, or /p/*.ext return true; } } } return false; } public static class JspPropertyGroup { private final String path; private final String extension; private final JspProperty jspProperty; JspPropertyGroup(String path, String extension, JspProperty jspProperty) { this.path = path; this.extension = extension; this.jspProperty = jspProperty; } public String getPath() { return path; } public String getExtension() { return extension; } public JspProperty getJspProperty() { return jspProperty; } } public static class JspProperty { private final String isXml; private final String elIgnored; private final String scriptingInvalid; private final String pageEncoding; private final Vector<String> includePrelude; private final Vector<String> includeCoda; private final String deferedSyntaxAllowedAsLiteral; private final String trimDirectiveWhitespaces; private final String defaultContentType; private final String buffer; private final String errorOnUndeclaredNamespace; public JspProperty(String isXml, String elIgnored, String scriptingInvalid, String pageEncoding, Vector<String> includePrelude, Vector<String> includeCoda, String deferedSyntaxAllowedAsLiteral, String trimDirectiveWhitespaces, String defaultContentType, String buffer, String errorOnUndeclaredNamespace) { this.isXml = isXml; this.elIgnored = elIgnored; this.scriptingInvalid = scriptingInvalid; this.pageEncoding = pageEncoding; this.includePrelude = includePrelude; this.includeCoda = includeCoda; this.deferedSyntaxAllowedAsLiteral = deferedSyntaxAllowedAsLiteral; this.trimDirectiveWhitespaces = trimDirectiveWhitespaces; this.defaultContentType = defaultContentType; this.buffer = buffer; this.errorOnUndeclaredNamespace = errorOnUndeclaredNamespace; } public String isXml() { return isXml; } public String isELIgnored() { return elIgnored; } public String isScriptingInvalid() { return scriptingInvalid; } public String getPageEncoding() { return pageEncoding; } public Vector<String> getIncludePrelude() { return includePrelude; } public Vector<String> getIncludeCoda() { return includeCoda; } public String isDeferedSyntaxAllowedAsLiteral() { return deferedSyntaxAllowedAsLiteral; } public String isTrimDirectiveWhitespaces() { return trimDirectiveWhitespaces; } public String getDefaultContentType() { return defaultContentType; } public String getBuffer() { return buffer; } public String isErrorOnUndeclaredNamespace() { return errorOnUndeclaredNamespace; } } }