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,438
Bug 54438 Bug fix 52953 introduces NullPointerException in RealmBase.java line 409 when user not found in JDBC
null
resolved fixed
c8d5d88
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-17T14:30:39Z
2013-01-17T02:33:20Z
java/org/apache/catalina/realm/RealmBase.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.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Locale; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Host; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Realm; import org.apache.catalina.Server; import org.apache.catalina.Service; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.deploy.SecurityCollection; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.catalina.util.MD5Encoder; import org.apache.catalina.util.SessionConfig; 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.HexUtils; import org.apache.tomcat.util.res.StringManager; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSName; /** * Simple implementation of <b>Realm</b> that reads an XML file to configure * the valid users, passwords, and roles. The file format (and default file * location) are identical to those currently supported by Tomcat 3.X. * * @author Craig R. McClanahan * @version $Id$ */ public abstract class RealmBase extends LifecycleMBeanBase implements Realm { private static final Log log = LogFactory.getLog(RealmBase.class); // ----------------------------------------------------- Instance Variables /** * The Container with which this Realm is associated. */ protected Container container = null; /** * Container log */ protected Log containerLog = null; /** * Digest algorithm used in storing passwords in a non-plaintext format. * Valid values are those accepted for the algorithm name by the * MessageDigest class, or <code>null</code> if no digesting should * be performed. */ protected String digest = null; /** * The encoding charset for the digest. */ protected String digestEncoding = null; /** * The MessageDigest object for digesting user credentials (passwords). */ protected volatile MessageDigest md = null; /** * MD5 message digest provider. */ protected static volatile MessageDigest md5Helper; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The property change support for this component. */ protected final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * Should we validate client certificate chains when they are presented? */ protected boolean validate = true; /** * The name of the class to use for retrieving user names from X509 * certificates. */ protected String x509UsernameRetrieverClassName; /** * The object that will extract user names from X509 client certificates. */ protected X509UsernameRetriever x509UsernameRetriever; /** * The all role mode. */ protected AllRolesMode allRolesMode = AllRolesMode.STRICT_MODE; /** * When processing users authenticated via the GSS-API, should any * &quot;@...&quot; be stripped from the end of the user name? */ protected boolean stripRealmForGss = true; // ------------------------------------------------------------- Properties /** * Return the Container with which this Realm has been associated. */ @Override public Container getContainer() { return (container); } /** * Set the Container with which this Realm has been associated. * * @param container The associated Container */ @Override public void setContainer(Container container) { Container oldContainer = this.container; this.container = container; support.firePropertyChange("container", oldContainer, this.container); } /** * Return the all roles mode. */ public String getAllRolesMode() { return allRolesMode.toString(); } /** * Set the all roles mode. */ public void setAllRolesMode(String allRolesMode) { this.allRolesMode = AllRolesMode.toMode(allRolesMode); } /** * Return the digest algorithm used for storing credentials. */ public String getDigest() { return digest; } /** * Set the digest algorithm used for storing credentials. * * @param digest The new digest algorithm */ public void setDigest(String digest) { this.digest = digest; } /** * Returns the digest encoding charset. * * @return The charset (may be null) for platform default */ public String getDigestEncoding() { return digestEncoding; } /** * Sets the digest encoding charset. * * @param charset The charset (null for platform default) */ public void setDigestEncoding(String charset) { digestEncoding = charset; } protected Charset getDigestCharset() throws UnsupportedEncodingException { if (digestEncoding == null) { return B2CConverter.ISO_8859_1; } else { return B2CConverter.getCharset(getDigestEncoding()); } } /** * Return the "validate certificate chains" flag. */ public boolean getValidate() { return (this.validate); } /** * Set the "validate certificate chains" flag. * * @param validate The new validate certificate chains flag */ public void setValidate(boolean validate) { this.validate = validate; } /** * Gets the name of the class that will be used to extract user names * from X509 client certificates. * @return The name of the class that will be used to extract user names * from X509 client certificates. */ public String getX509UsernameRetrieverClassName() { return x509UsernameRetrieverClassName; } /** * Sets the name of the class that will be used to extract user names * from X509 client certificates. The class must implement * X509UsernameRetriever. * * @param className The name of the class that will be used to extract user names * from X509 client certificates. * @see X509UsernameRetriever */ public void setX509UsernameRetrieverClassName(String className) { this.x509UsernameRetrieverClassName = className; } public boolean isStripRealmForGss() { return stripRealmForGss; } public void setStripRealmForGss(boolean stripRealmForGss) { this.stripRealmForGss = stripRealmForGss; } // --------------------------------------------------------- Public Methods /** * Add a property change listener to this component. * * @param listener The listener to add */ @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } /** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ @Override public Principal authenticate(String username, String credentials) { String serverCredentials = getPassword(username); boolean validated ; if ( serverCredentials == null ) { validated = false; } else if(hasMessageDigest()) { validated = serverCredentials.equalsIgnoreCase(digest(credentials)); } else { validated = serverCredentials.equals(credentials); } if(! validated ) { if (containerLog.isTraceEnabled()) { containerLog.trace(sm.getString("realmBase.authenticateFailure", username)); } return null; } if (containerLog.isTraceEnabled()) { containerLog.trace(sm.getString("realmBase.authenticateSuccess", username)); } return getPrincipal(username); } /** * Return the Principal associated with the specified username, which * matches the digest calculated using the given parameters using the * method described in RFC 2069; otherwise return <code>null</code>. * * @param username Username of the Principal to look up * @param clientDigest Digest which has been submitted by the client * @param nonce Unique (or supposedly unique) token which has been used * for this request * @param realm 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 realm, String md5a2) { // In digest auth, digests are always lower case String md5a1 = getDigest(username, realm).toLowerCase(Locale.ENGLISH); if (md5a1 == null) return null; String serverDigestValue; if (qop == null) { serverDigestValue = md5a1 + ":" + nonce + ":" + md5a2; } else { serverDigestValue = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2; } byte[] valueBytes = null; try { valueBytes = serverDigestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } String serverDigest = null; // Bugzilla 32137 synchronized(md5Helper) { serverDigest = MD5Encoder.encode(md5Helper.digest(valueBytes)); } if (log.isDebugEnabled()) { log.debug("Digest : " + clientDigest + " Username:" + username + " ClientSigest:" + clientDigest + " nonce:" + nonce + " nc:" + nc + " cnonce:" + cnonce + " qop:" + qop + " realm:" + realm + "md5a2:" + md5a2 + " Server digest:" + serverDigest); } if (serverDigest.equals(clientDigest)) { return getPrincipal(username); } return null; } /** * Return the Principal associated with the specified chain of X509 * client certificates. If there is none, return <code>null</code>. * * @param certs Array of client certificates, with the first one in * the array being the certificate of the client itself. */ @Override public Principal authenticate(X509Certificate certs[]) { if ((certs == null) || (certs.length < 1)) return (null); // Check the validity of each certificate in the chain if (log.isDebugEnabled()) log.debug("Authenticating client certificate chain"); if (validate) { for (int i = 0; i < certs.length; i++) { if (log.isDebugEnabled()) log.debug(" Checking validity for '" + certs[i].getSubjectDN().getName() + "'"); try { certs[i].checkValidity(); } catch (Exception e) { if (log.isDebugEnabled()) log.debug(" Validity exception", e); return (null); } } } // Check the existence of the client Principal in our database return (getPrincipal(certs[0])); } /** * {@inheritDoc} */ @Override public Principal authenticate(GSSContext gssContext, boolean storeCred) { if (gssContext.isEstablished()) { GSSName gssName = null; try { gssName = gssContext.getSrcName(); } catch (GSSException e) { log.warn(sm.getString("realmBase.gssNameFail"), e); } if (gssName!= null) { String name = gssName.toString(); if (isStripRealmForGss()) { int i = name.indexOf('@'); if (i > 0) { // Zero so we don;t leave a zero length name name = name.substring(0, i); } } GSSCredential gssCredential = null; if (storeCred && gssContext.getCredDelegState()) { try { gssCredential = gssContext.getDelegCred(); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString( "realmBase.delegatedCredentialFail", name), e); } } } return getPrincipal(name, gssCredential); } } // Fail in all other cases return null; } /** * 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 void backgroundProcess() { // NOOP in base class } /** * Return the SecurityConstraints configured to guard the request URI for * this request, or <code>null</code> if there is no such constraint. * * @param request Request we are processing * @param context Context the Request is mapped to */ @Override public SecurityConstraint [] findSecurityConstraints(Request request, Context context) { ArrayList<SecurityConstraint> results = null; // Are there any defined security constraints? SecurityConstraint constraints[] = context.findConstraints(); if ((constraints == null) || (constraints.length == 0)) { if (log.isDebugEnabled()) log.debug(" No applicable constraints defined"); return (null); } // Check each defined security constraint String uri = request.getRequestPathMB().toString(); // Bug47080 - in rare cases this may be null // Mapper treats as '/' do the same to prevent NPE if (uri == null) { uri = "/"; } String method = request.getMethod(); int i; boolean found = false; for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } for(int k=0; k < patterns.length; k++) { if(uri.equals(patterns[k])) { found = true; if(collection[j].findMethod(method)) { if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } } } if(found) { return resultsToArray(results); } int longest = -1; for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } boolean matched = false; int length = -1; for(int k=0; k < patterns.length; k++) { String pattern = patterns[k]; if(pattern.startsWith("/") && pattern.endsWith("/*") && pattern.length() >= longest) { if(pattern.length() == 2) { matched = true; length = pattern.length(); } else if(pattern.regionMatches(0,uri,0, pattern.length()-1) || (pattern.length()-2 == uri.length() && pattern.regionMatches(0,uri,0, pattern.length()-2))) { matched = true; length = pattern.length(); } } } if(matched) { if(length > longest) { found = false; if(results != null) { results.clear(); } longest = length; } if(collection[j].findMethod(method)) { found = true; if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } } if(found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } boolean matched = false; int pos = -1; for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } for(int k=0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if(pattern.startsWith("*.")){ int slash = uri.lastIndexOf("/"); int dot = uri.lastIndexOf("."); if(slash >= 0 && dot > slash && dot != uri.length()-1 && uri.length()-dot == pattern.length()-1) { if(pattern.regionMatches(1,uri,dot,uri.length()-dot)) { matched = true; pos = j; } } } } } if(matched) { found = true; if(collection[pos].findMethod(method)) { if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } if(found) { return resultsToArray(results); } for (i = 0; i < constraints.length; i++) { SecurityCollection [] collection = constraints[i].findCollections(); // If collection is null, continue to avoid an NPE // See Bugzilla 30624 if ( collection == null) { continue; } if (log.isDebugEnabled()) { log.debug(" Checking constraint '" + constraints[i] + "' against " + method + " " + uri + " --> " + constraints[i].included(uri, method)); } for(int j=0; j < collection.length; j++){ String [] patterns = collection[j].findPatterns(); // If patterns is null, continue to avoid an NPE // See Bugzilla 30624 if ( patterns == null) { continue; } boolean matched = false; for(int k=0; k < patterns.length && !matched; k++) { String pattern = patterns[k]; if(pattern.equals("/")){ matched = true; } } if(matched) { if(results == null) { results = new ArrayList<>(); } results.add(constraints[i]); } } } if(results == null) { // No applicable security constraint was found if (log.isDebugEnabled()) log.debug(" No applicable constraint located"); } return resultsToArray(results); } /** * Convert an ArrayList to a SecurityContraint []. */ private SecurityConstraint [] resultsToArray( ArrayList<SecurityConstraint> results) { if(results == null || results.size() == 0) { return null; } SecurityConstraint [] array = new SecurityConstraint[results.size()]; results.toArray(array); return array; } /** * Perform access control based on the specified authorization constraint. * Return <code>true</code> if this constraint is satisfied and processing * should continue, or <code>false</code> otherwise. * * @param request Request we are processing * @param response Response we are creating * @param constraints Security constraint we are enforcing * @param context The Context to which client of this class is attached. * * @exception IOException if an input/output error occurs */ @Override public boolean hasResourcePermission(Request request, Response response, SecurityConstraint []constraints, Context context) throws IOException { if (constraints == null || constraints.length == 0) return (true); // Which user principal have we already authenticated? Principal principal = request.getPrincipal(); boolean status = false; boolean denyfromall = false; for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[]; if (constraint.getAllRoles()) { // * means all roles defined in web.xml roles = request.getContext().findSecurityRoles(); } else { roles = constraint.findAuthRoles(); } if (roles == null) roles = new String[0]; if (log.isDebugEnabled()) log.debug(" Checking roles " + principal); if (roles.length == 0 && !constraint.getAllRoles()) { if(constraint.getAuthConstraint()) { if( log.isDebugEnabled() ) log.debug("No roles"); status = false; // No listed roles means no access at all denyfromall = true; break; } if(log.isDebugEnabled()) log.debug("Passing all access"); status = true; } else if (principal == null) { if (log.isDebugEnabled()) log.debug(" No user authenticated, cannot grant access"); } else { for (int j = 0; j < roles.length; j++) { if (hasRole(null, principal, roles[j])) { status = true; if( log.isDebugEnabled() ) log.debug( "Role found: " + roles[j]); } else if( log.isDebugEnabled() ) log.debug( "No role found: " + roles[j]); } } } if (!denyfromall && allRolesMode != AllRolesMode.STRICT_MODE && !status && principal != null) { if (log.isDebugEnabled()) { log.debug("Checking for all roles mode: " + allRolesMode); } // Check for an all roles(role-name="*") for (int i = 0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String roles[]; // If the all roles mode exists, sets if (constraint.getAllRoles()) { if (allRolesMode == AllRolesMode.AUTH_ONLY_MODE) { if (log.isDebugEnabled()) { log.debug("Granting access for role-name=*, auth-only"); } status = true; break; } // For AllRolesMode.STRICT_AUTH_ONLY_MODE there must be zero roles roles = request.getContext().findSecurityRoles(); if (roles.length == 0 && allRolesMode == AllRolesMode.STRICT_AUTH_ONLY_MODE) { if (log.isDebugEnabled()) { log.debug("Granting access for role-name=*, strict auth-only"); } status = true; break; } } } } // Return a "Forbidden" message denying access to this resource if(!status) { response.sendError (HttpServletResponse.SC_FORBIDDEN, sm.getString("realmBase.forbidden")); } return status; } /** * Return <code>true</code> if the specified Principal has the specified * security role, within the context of this Realm; otherwise return * <code>false</code>. This method can be overridden by Realm * implementations, but the default is adequate when an instance of * <code>GenericPrincipal</code> is used to represent authenticated * Principals from this Realm. * * @param principal Principal for whom the role is to be checked * @param role Security role to be checked */ @Override public boolean hasRole(Wrapper wrapper, Principal principal, String role) { // Check for a role alias defined in a <security-role-ref> element if (wrapper != null) { String realRole = wrapper.findSecurityReference(role); if (realRole != null) role = realRole; } // Should be overridden in JAASRealm - to avoid pretty inefficient conversions if ((principal == null) || (role == null) || !(principal instanceof GenericPrincipal)) return (false); GenericPrincipal gp = (GenericPrincipal) principal; boolean result = gp.hasRole(role); if (log.isDebugEnabled()) { String name = principal.getName(); if (result) log.debug(sm.getString("realmBase.hasRoleSuccess", name, role)); else log.debug(sm.getString("realmBase.hasRoleFailure", name, role)); } return (result); } /** * Enforce any user data constraint required by the security constraint * guarding this request URI. Return <code>true</code> if this constraint * was not violated and processing should continue, or <code>false</code> * if we have created a response already. * * @param request Request we are processing * @param response Response we are creating * @param constraints Security constraint being checked * * @exception IOException if an input/output error occurs */ @Override public boolean hasUserDataPermission(Request request, Response response, SecurityConstraint []constraints) throws IOException { // Is there a relevant user data constraint? if (constraints == null || constraints.length == 0) { if (log.isDebugEnabled()) log.debug(" No applicable security constraint defined"); return (true); } for(int i=0; i < constraints.length; i++) { SecurityConstraint constraint = constraints[i]; String userConstraint = constraint.getUserConstraint(); if (userConstraint == null) { if (log.isDebugEnabled()) log.debug(" No applicable user data constraint defined"); return (true); } if (userConstraint.equals(Constants.NONE_TRANSPORT)) { if (log.isDebugEnabled()) log.debug(" User data constraint has no restrictions"); return (true); } } // Validate the request against the user data constraint if (request.getRequest().isSecure()) { if (log.isDebugEnabled()) log.debug(" User data constraint already satisfied"); return (true); } // Initialize variables we need to determine the appropriate action int redirectPort = request.getConnector().getRedirectPort(); // Is redirecting disabled? if (redirectPort <= 0) { if (log.isDebugEnabled()) log.debug(" SSL redirect is disabled"); response.sendError (HttpServletResponse.SC_FORBIDDEN, request.getRequestURI()); return (false); } // Redirect to the corresponding SSL port StringBuilder file = new StringBuilder(); String protocol = "https"; String host = request.getServerName(); // Protocol file.append(protocol).append("://").append(host); // Host with port if(redirectPort != 443) { file.append(":").append(redirectPort); } // URI file.append(request.getRequestURI()); String requestedSessionId = request.getRequestedSessionId(); if ((requestedSessionId != null) && request.isRequestedSessionIdFromURL()) { file.append(";"); file.append(SessionConfig.getSessionUriParamName( request.getContext())); file.append("="); file.append(requestedSessionId); } String queryString = request.getQueryString(); if (queryString != null) { file.append('?'); file.append(queryString); } if (log.isDebugEnabled()) log.debug(" Redirecting to " + file.toString()); response.sendRedirect(file.toString()); return (false); } /** * Remove a property change listener from this component. * * @param listener The listener to remove */ @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } @Override protected void initInternal() throws LifecycleException { super.initInternal(); // We want logger as soon as possible if (container != null) { this.containerLog = container.getLogger(); } x509UsernameRetriever = createUsernameRetriever(x509UsernameRetrieverClassName); } /** * 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 { // Create a MessageDigest instance for credentials, if desired if (digest != null) { try { md = MessageDigest.getInstance(digest); } catch (NoSuchAlgorithmException e) { throw new LifecycleException (sm.getString("realmBase.algorithm", digest), e); } } setState(LifecycleState.STARTING); } /** * Gracefully terminate the active use of the public methods of this * component 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 { setState(LifecycleState.STOPPING); // Clean up allocated resources md = null; } /** * Return a String representation of this component. */ @Override public String toString() { StringBuilder sb = new StringBuilder("Realm["); sb.append(getName()); sb.append(']'); return sb.toString(); } // ------------------------------------------------------ Protected Methods /** * Digest the password using the specified algorithm and * convert the result to a corresponding hexadecimal string. * If exception, the plain credentials string is returned. * * @param credentials Password or other credentials to use in * authenticating this username */ protected String digest(String credentials) { // If no MessageDigest instance is specified, return unchanged if (hasMessageDigest() == false) return (credentials); // Digest the user credentials and return as hexadecimal synchronized (this) { try { md.reset(); byte[] bytes = null; try { bytes = credentials.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } md.update(bytes); return (HexUtils.toHexString(md.digest())); } catch (Exception e) { log.error(sm.getString("realmBase.digest"), e); return (credentials); } } } protected boolean hasMessageDigest() { return !(md == null); } /** * Return the digest associated with given principal's user name. */ protected String getDigest(String username, String realmName) { if (md5Helper == null) { try { md5Helper = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { log.error("Couldn't get MD5 digest: ", e); throw new IllegalStateException(e.getMessage()); } } if (hasMessageDigest()) { // Use pre-generated digest return getPassword(username); } String digestValue = username + ":" + realmName + ":" + getPassword(username); byte[] valueBytes = null; try { valueBytes = digestValue.getBytes(getDigestCharset()); } catch (UnsupportedEncodingException uee) { log.error("Illegal digestEncoding: " + getDigestEncoding(), uee); throw new IllegalArgumentException(uee.getMessage()); } byte[] digest; // Bugzilla 32137 synchronized(md5Helper) { digest = md5Helper.digest(valueBytes); } return MD5Encoder.encode(digest); } /** * Return a short name for this Realm implementation, for use in * log messages. */ protected abstract String getName(); /** * Return the password associated with the given principal's user name. */ protected abstract String getPassword(String username); /** * Return the Principal associated with the given certificate. */ protected Principal getPrincipal(X509Certificate usercert) { String username = x509UsernameRetriever.getUsername(usercert); if(log.isDebugEnabled()) log.debug(sm.getString("realmBase.gotX509Username", username)); return(getPrincipal(username)); } /** * Return the Principal associated with the given user name. */ protected abstract Principal getPrincipal(String username); protected Principal getPrincipal(String username, GSSCredential gssCredential) { Principal p = getPrincipal(username); if (p instanceof GenericPrincipal) { ((GenericPrincipal) p).setGssCredential(gssCredential); } return p; } /** * Return the Server object that is the ultimate parent for the container * with which this Realm is associated. If the server cannot be found (eg * because the container hierarchy is not complete), <code>null</code> is * returned. */ protected Server getServer() { Container c = container; if (c instanceof Context) { c = c.getParent(); } if (c instanceof Host) { c = c.getParent(); } if (c instanceof Engine) { Service s = ((Engine)c).getService(); if (s != null) { return s.getServer(); } } return null; } // --------------------------------------------------------- Static Methods /** * Digest password using the algorithm specified and * convert the result to a corresponding hex string. * If exception, the plain credentials string is returned * * @param credentials Password or other credentials to use in * authenticating this username * @param algorithm Algorithm used to do the digest * @param encoding Character encoding of the string to digest */ public static final String Digest(String credentials, String algorithm, String encoding) { try { // Obtain a new message digest with "digest" encryption MessageDigest md = (MessageDigest) MessageDigest.getInstance(algorithm).clone(); // encode the credentials // Should use the digestEncoding, but that's not a static field if (encoding == null) { md.update(credentials.getBytes()); } else { md.update(credentials.getBytes(encoding)); } // Digest the credentials and return as hexadecimal return (HexUtils.toHexString(md.digest())); } catch(Exception ex) { log.error(ex); return credentials; } } /** * Digest password using the algorithm specified and * convert the result to a corresponding hex string. * If exception, the plain credentials string is returned */ public static void main(String args[]) { String encoding = null; int firstCredentialArg = 2; if (args.length > 4 && args[2].equalsIgnoreCase("-e")) { encoding = args[3]; firstCredentialArg = 4; } if(args.length > firstCredentialArg && args[0].equalsIgnoreCase("-a")) { for(int i=firstCredentialArg; i < args.length ; i++){ System.out.print(args[i]+":"); System.out.println(Digest(args[i], args[1], encoding)); } } else { System.out.println ("Usage: RealmBase -a <algorithm> [-e <encoding>] <credentials>"); } } // -------------------- JMX and Registration -------------------- @Override public String getObjectNameKeyProperties() { StringBuilder keyProperties = new StringBuilder("type=Realm"); keyProperties.append(getRealmSuffix()); keyProperties.append(container.getMBeanKeyProperties()); return keyProperties.toString(); } @Override public String getDomainInternal() { return container.getDomain(); } protected String realmPath = "/realm0"; public String getRealmPath() { return realmPath; } public void setRealmPath(String theRealmPath) { realmPath = theRealmPath; } protected String getRealmSuffix() { return ",realmPath=" + getRealmPath(); } protected static class AllRolesMode { private final String name; /** Use the strict servlet spec interpretation which requires that the user * have one of the web-app/security-role/role-name */ public static final AllRolesMode STRICT_MODE = new AllRolesMode("strict"); /** Allow any authenticated user */ public static final AllRolesMode AUTH_ONLY_MODE = new AllRolesMode("authOnly"); /** Allow any authenticated user only if there are no web-app/security-roles */ public static final AllRolesMode STRICT_AUTH_ONLY_MODE = new AllRolesMode("strictAuthOnly"); static AllRolesMode toMode(String name) { AllRolesMode mode; if( name.equalsIgnoreCase(STRICT_MODE.name) ) mode = STRICT_MODE; else if( name.equalsIgnoreCase(AUTH_ONLY_MODE.name) ) mode = AUTH_ONLY_MODE; else if( name.equalsIgnoreCase(STRICT_AUTH_ONLY_MODE.name) ) mode = STRICT_AUTH_ONLY_MODE; else throw new IllegalStateException("Unknown mode, must be one of: strict, authOnly, strictAuthOnly"); return mode; } private AllRolesMode(String name) { this.name = name; } @Override public boolean equals(Object o) { boolean equals = false; if( o instanceof AllRolesMode ) { AllRolesMode mode = (AllRolesMode) o; equals = name.equals(mode.name); } return equals; } @Override public int hashCode() { return name.hashCode(); } @Override public String toString() { return name; } } private static X509UsernameRetriever createUsernameRetriever(String className) throws LifecycleException { if(null == className || "".equals(className.trim())) return new X509SubjectDnRetriever(); try { Class<? extends X509UsernameRetriever> clazz = (Class<? extends X509UsernameRetriever>)Class.forName(className); return clazz.newInstance(); } catch (ClassNotFoundException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassNotFoundException", className), e); } catch (InstantiationException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.InstantiationException", className), e); } catch (IllegalAccessException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.IllegalAccessException", className), e); } catch (ClassCastException e) { throw new LifecycleException(sm.getString("realmBase.createUsernameRetriever.ClassCastException", className), e); } } }
54,324
Bug 54324 Support is required to disable TLS compression to prevent against CRIME attacks
null
resolved fixed
ab44514
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-17T20:03:00Z
2012-12-19T04:06:40Z
java/org/apache/coyote/http11/Http11AprProtocol.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 javax.servlet.http.ProtocolHandler; import org.apache.coyote.AbstractProtocol; import org.apache.coyote.Processor; import org.apache.coyote.http11.upgrade.AprProcessor; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.AprEndpoint; import org.apache.tomcat.util.net.AprEndpoint.Handler; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; /** * Abstract the protocol implementation, including threading, etc. * Processor is single threaded and specific to stream-based protocols, * will not fit Jk protocols like JNI. * * @author Remy Maucherat * @author Costin Manolache */ public class Http11AprProtocol extends AbstractHttp11Protocol<Long> { private static final Log log = LogFactory.getLog(Http11AprProtocol.class); @Override protected Log getLog() { return log; } @Override protected AbstractEndpoint.Handler getHandler() { return cHandler; } @Override public boolean isAprRequired() { // Override since this protocol implementation requires the APR/native // library return true; } public Http11AprProtocol() { endpoint = new AprEndpoint(); cHandler = new Http11ConnectionHandler(this); ((AprEndpoint) endpoint).setHandler(cHandler); setSoLinger(Constants.DEFAULT_CONNECTION_LINGER); setSoTimeout(Constants.DEFAULT_CONNECTION_TIMEOUT); setTcpNoDelay(Constants.DEFAULT_TCP_NO_DELAY); } private final Http11ConnectionHandler cHandler; public boolean getUseSendfile() { return ((AprEndpoint)endpoint).getUseSendfile(); } public void setUseSendfile(boolean useSendfile) { ((AprEndpoint)endpoint).setUseSendfile(useSendfile); } public int getPollTime() { return ((AprEndpoint)endpoint).getPollTime(); } public void setPollTime(int pollTime) { ((AprEndpoint)endpoint).setPollTime(pollTime); } public void setPollerSize(int pollerSize) { endpoint.setMaxConnections(pollerSize); } public int getPollerSize() { return endpoint.getMaxConnections(); } public int getSendfileSize() { return ((AprEndpoint)endpoint).getSendfileSize(); } public void setSendfileSize(int sendfileSize) { ((AprEndpoint)endpoint).setSendfileSize(sendfileSize); } public void setSendfileThreadCount(int sendfileThreadCount) { ((AprEndpoint)endpoint).setSendfileThreadCount(sendfileThreadCount); } public int getSendfileThreadCount() { return ((AprEndpoint)endpoint).getSendfileThreadCount(); } public boolean getDeferAccept() { return ((AprEndpoint)endpoint).getDeferAccept(); } public void setDeferAccept(boolean deferAccept) { ((AprEndpoint)endpoint).setDeferAccept(deferAccept); } // -------------------- SSL related properties -------------------- /** * SSL protocol. */ public String getSSLProtocol() { return ((AprEndpoint)endpoint).getSSLProtocol(); } public void setSSLProtocol(String SSLProtocol) { ((AprEndpoint)endpoint).setSSLProtocol(SSLProtocol); } /** * SSL password (if a cert is encrypted, and no password has been provided, a callback * will ask for a password). */ public String getSSLPassword() { return ((AprEndpoint)endpoint).getSSLPassword(); } public void setSSLPassword(String SSLPassword) { ((AprEndpoint)endpoint).setSSLPassword(SSLPassword); } /** * SSL cipher suite. */ public String getSSLCipherSuite() { return ((AprEndpoint)endpoint).getSSLCipherSuite(); } public void setSSLCipherSuite(String SSLCipherSuite) { ((AprEndpoint)endpoint).setSSLCipherSuite(SSLCipherSuite); } public String[] getCiphersUsed() { return endpoint.getCiphersUsed();} /** * SSL honor cipher order. * * Set to <code>true</code> to enforce the <i>server's</i> cipher order * instead of the default which is to allow the client to choose a * preferred cipher. */ public boolean getSSLHonorCipherOrder() { return ((AprEndpoint)endpoint).getSSLHonorCipherOrder(); } public void setSSLHonorCipherOrder(boolean SSLHonorCipherOrder) { ((AprEndpoint)endpoint).setSSLHonorCipherOrder(SSLHonorCipherOrder); } /** * SSL certificate file. */ public String getSSLCertificateFile() { return ((AprEndpoint)endpoint).getSSLCertificateFile(); } public void setSSLCertificateFile(String SSLCertificateFile) { ((AprEndpoint)endpoint).setSSLCertificateFile(SSLCertificateFile); } /** * SSL certificate key file. */ public String getSSLCertificateKeyFile() { return ((AprEndpoint)endpoint).getSSLCertificateKeyFile(); } public void setSSLCertificateKeyFile(String SSLCertificateKeyFile) { ((AprEndpoint)endpoint).setSSLCertificateKeyFile(SSLCertificateKeyFile); } /** * SSL certificate chain file. */ public String getSSLCertificateChainFile() { return ((AprEndpoint)endpoint).getSSLCertificateChainFile(); } public void setSSLCertificateChainFile(String SSLCertificateChainFile) { ((AprEndpoint)endpoint).setSSLCertificateChainFile(SSLCertificateChainFile); } /** * SSL CA certificate path. */ public String getSSLCACertificatePath() { return ((AprEndpoint)endpoint).getSSLCACertificatePath(); } public void setSSLCACertificatePath(String SSLCACertificatePath) { ((AprEndpoint)endpoint).setSSLCACertificatePath(SSLCACertificatePath); } /** * SSL CA certificate file. */ public String getSSLCACertificateFile() { return ((AprEndpoint)endpoint).getSSLCACertificateFile(); } public void setSSLCACertificateFile(String SSLCACertificateFile) { ((AprEndpoint)endpoint).setSSLCACertificateFile(SSLCACertificateFile); } /** * SSL CA revocation path. */ public String getSSLCARevocationPath() { return ((AprEndpoint)endpoint).getSSLCARevocationPath(); } public void setSSLCARevocationPath(String SSLCARevocationPath) { ((AprEndpoint)endpoint).setSSLCARevocationPath(SSLCARevocationPath); } /** * SSL CA revocation file. */ public String getSSLCARevocationFile() { return ((AprEndpoint)endpoint).getSSLCARevocationFile(); } public void setSSLCARevocationFile(String SSLCARevocationFile) { ((AprEndpoint)endpoint).setSSLCARevocationFile(SSLCARevocationFile); } /** * SSL verify client. */ public String getSSLVerifyClient() { return ((AprEndpoint)endpoint).getSSLVerifyClient(); } public void setSSLVerifyClient(String SSLVerifyClient) { ((AprEndpoint)endpoint).setSSLVerifyClient(SSLVerifyClient); } /** * SSL verify depth. */ public int getSSLVerifyDepth() { return ((AprEndpoint)endpoint).getSSLVerifyDepth(); } public void setSSLVerifyDepth(int SSLVerifyDepth) { ((AprEndpoint)endpoint).setSSLVerifyDepth(SSLVerifyDepth); } // ----------------------------------------------------- JMX related methods @Override protected String getNamePrefix() { return ("http-apr"); } @Override public void start() throws Exception { super.start(); if (npnHandler != null) { long sslCtx = ((AprEndpoint) endpoint).getJniSslContext(); npnHandler.init(endpoint, sslCtx, getAdapter()); } } // -------------------- Connection handler -------------------- protected static class Http11ConnectionHandler extends AbstractConnectionHandler<Long,Http11AprProcessor> implements Handler { protected Http11AprProtocol proto; Http11ConnectionHandler(Http11AprProtocol proto) { this.proto = proto; } @Override protected AbstractProtocol getProtocol() { return proto; } @Override protected Log getLog() { return log; } @Override public void recycle() { recycledProcessors.clear(); } /** * Expected to be used by the handler once the processor is no longer * required. * * @param socket * @param processor * @param isSocketClosing Not used in HTTP * @param addToPoller */ @Override public void release(SocketWrapper<Long> socket, Processor<Long> processor, boolean isSocketClosing, boolean addToPoller) { processor.recycle(isSocketClosing); recycledProcessors.push(processor); if (addToPoller && proto.endpoint.isRunning()) { ((AprEndpoint)proto.endpoint).getPoller().add( socket.getSocket().longValue(), proto.endpoint.getKeepAliveTimeout(), true, false); } } @Override public SocketState process(SocketWrapper<Long> socket, SocketStatus status) { if (proto.npnHandler != null) { Processor<Long> processor = null; if (status == SocketStatus.OPEN_READ) { processor = connections.get(socket.getSocket()); } if (processor == null) { // if not null - this is a former comet request, handled by http11 SocketState socketState = proto.npnHandler.process(socket, status); // handled by npn protocol. if (socketState == SocketState.CLOSED || socketState == SocketState.LONG) { return socketState; } } } return super.process(socket, status); } @Override protected void initSsl(SocketWrapper<Long> socket, Processor<Long> processor) { // NOOP for APR } @Override protected void longPoll(SocketWrapper<Long> socket, Processor<Long> processor) { if (processor.isAsync()) { // Async socket.setAsync(true); } else if (processor.isComet()) { // Comet if (proto.endpoint.isRunning()) { socket.setComet(true); ((AprEndpoint) proto.endpoint).getPoller().add( socket.getSocket().longValue(), proto.endpoint.getSoTimeout(), true, false); } else { // Process a STOP directly ((AprEndpoint) proto.endpoint).processSocket( socket.getSocket().longValue(), SocketStatus.STOP); } } else { // Upgraded ((AprEndpoint) proto.endpoint).getPoller().add( socket.getSocket().longValue(), -1, true, false); } } @Override protected Http11AprProcessor createProcessor() { Http11AprProcessor processor = new Http11AprProcessor( proto.getMaxHttpHeaderSize(), (AprEndpoint)proto.endpoint, proto.getMaxTrailerSize()); processor.setAdapter(proto.getAdapter()); processor.setMaxKeepAliveRequests(proto.getMaxKeepAliveRequests()); processor.setKeepAliveTimeout(proto.getKeepAliveTimeout()); processor.setConnectionUploadTimeout( proto.getConnectionUploadTimeout()); processor.setDisableUploadTimeout(proto.getDisableUploadTimeout()); processor.setCompressionMinSize(proto.getCompressionMinSize()); processor.setCompression(proto.getCompression()); processor.setNoCompressionUserAgents(proto.getNoCompressionUserAgents()); processor.setCompressableMimeTypes(proto.getCompressableMimeTypes()); processor.setRestrictedUserAgents(proto.getRestrictedUserAgents()); processor.setSocketBuffer(proto.getSocketBuffer()); processor.setMaxSavePostSize(proto.getMaxSavePostSize()); processor.setServer(proto.getServer()); processor.setClientCertProvider(proto.getClientCertProvider()); register(processor); return processor; } @Override protected Processor<Long> createUpgradeProcessor( SocketWrapper<Long> socket, ProtocolHandler httpUpgradeProcessor) throws IOException { return new AprProcessor(socket, httpUpgradeProcessor, (AprEndpoint) proto.endpoint); } } }
54,324
Bug 54324 Support is required to disable TLS compression to prevent against CRIME attacks
null
resolved fixed
ab44514
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-17T20:03:00Z
2012-12-19T04:06:40Z
java/org/apache/tomcat/jni/SSL.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.jni; /** SSL * * @author Mladen Turk * @version $Id$ */ public final class SSL { /* * Type definitions mostly from mod_ssl */ public static final int UNSET = -1; /* * Define the certificate algorithm types */ public static final int SSL_ALGO_UNKNOWN = 0; public static final int SSL_ALGO_RSA = (1<<0); public static final int SSL_ALGO_DSA = (1<<1); public static final int SSL_ALGO_ALL = (SSL_ALGO_RSA|SSL_ALGO_DSA); public static final int SSL_AIDX_RSA = 0; public static final int SSL_AIDX_DSA = 1; public static final int SSL_AIDX_MAX = 2; /* * Define IDs for the temporary RSA keys and DH params */ public static final int SSL_TMP_KEY_RSA_512 = 0; public static final int SSL_TMP_KEY_RSA_1024 = 1; public static final int SSL_TMP_KEY_RSA_2048 = 2; public static final int SSL_TMP_KEY_RSA_4096 = 3; public static final int SSL_TMP_KEY_DH_512 = 4; public static final int SSL_TMP_KEY_DH_1024 = 5; public static final int SSL_TMP_KEY_DH_2048 = 6; public static final int SSL_TMP_KEY_DH_4096 = 7; public static final int SSL_TMP_KEY_MAX = 8; /* * Define the SSL options */ public static final int SSL_OPT_NONE = 0; public static final int SSL_OPT_RELSET = (1<<0); public static final int SSL_OPT_STDENVVARS = (1<<1); public static final int SSL_OPT_EXPORTCERTDATA = (1<<3); public static final int SSL_OPT_FAKEBASICAUTH = (1<<4); public static final int SSL_OPT_STRICTREQUIRE = (1<<5); public static final int SSL_OPT_OPTRENEGOTIATE = (1<<6); public static final int SSL_OPT_ALL = (SSL_OPT_STDENVVARS|SSL_OPT_EXPORTCERTDATA|SSL_OPT_FAKEBASICAUTH|SSL_OPT_STRICTREQUIRE|SSL_OPT_OPTRENEGOTIATE); /* * Define the SSL Protocol options */ public static final int SSL_PROTOCOL_NONE = 0; public static final int SSL_PROTOCOL_SSLV2 = (1<<0); public static final int SSL_PROTOCOL_SSLV3 = (1<<1); public static final int SSL_PROTOCOL_TLSV1 = (1<<2); public static final int SSL_PROTOCOL_ALL = (SSL_PROTOCOL_SSLV3|SSL_PROTOCOL_TLSV1); /* * Define the SSL verify levels */ public static final int SSL_CVERIFY_UNSET = UNSET; public static final int SSL_CVERIFY_NONE = 0; public static final int SSL_CVERIFY_OPTIONAL = 1; public static final int SSL_CVERIFY_REQUIRE = 2; public static final int SSL_CVERIFY_OPTIONAL_NO_CA = 3; /* Use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 2 options * are 'ored' with SSL_VERIFY_PEER if they are desired */ public static final int SSL_VERIFY_NONE = 0; public static final int SSL_VERIFY_PEER = 1; public static final int SSL_VERIFY_FAIL_IF_NO_PEER_CERT = 2; public static final int SSL_VERIFY_CLIENT_ONCE = 4; public static final int SSL_VERIFY_PEER_STRICT = (SSL_VERIFY_PEER|SSL_VERIFY_FAIL_IF_NO_PEER_CERT); public static final int SSL_OP_MICROSOFT_SESS_ID_BUG = 0x00000001; public static final int SSL_OP_NETSCAPE_CHALLENGE_BUG = 0x00000002; public static final int SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG = 0x00000008; public static final int SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG = 0x00000010; public static final int SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER = 0x00000020; public static final int SSL_OP_MSIE_SSLV2_RSA_PADDING = 0x00000040; public static final int SSL_OP_SSLEAY_080_CLIENT_DH_BUG = 0x00000080; public static final int SSL_OP_TLS_D5_BUG = 0x00000100; public static final int SSL_OP_TLS_BLOCK_PADDING_BUG = 0x00000200; /* Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added * in OpenSSL 0.9.6d. Usually (depending on the application protocol) * the workaround is not needed. Unfortunately some broken SSL/TLS * implementations cannot handle it at all, which is why we include * it in SSL_OP_ALL. */ public static final int SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS = 0x00000800; /* SSL_OP_ALL: various bug workarounds that should be rather harmless. * This used to be 0x000FFFFFL before 0.9.7. */ public static final int SSL_OP_ALL = 0x00000FFF; /* As server, disallow session resumption on renegotiation */ public static final int SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION = 0x00010000; /* Permit unsafe legacy renegotiation */ public static final int SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION = 0x00040000; /* If set, always create a new key when using tmp_eddh parameters */ public static final int SSL_OP_SINGLE_ECDH_USE = 0x00080000; /* If set, always create a new key when using tmp_dh parameters */ public static final int SSL_OP_SINGLE_DH_USE = 0x00100000; /* Set to always use the tmp_rsa key when doing RSA operations, * even when this violates protocol specs */ public static final int SSL_OP_EPHEMERAL_RSA = 0x00200000; /* Set on servers to choose the cipher according to the server's * preferences */ public static final int SSL_OP_CIPHER_SERVER_PREFERENCE = 0x00400000; /* If set, a server will allow a client to issue a SSLv3.0 version number * as latest version supported in the premaster secret, even when TLSv1.0 * (version 3.1) was announced in the client hello. Normally this is * forbidden to prevent version rollback attacks. */ public static final int SSL_OP_TLS_ROLLBACK_BUG = 0x00800000; public static final int SSL_OP_NO_SSLv2 = 0x01000000; public static final int SSL_OP_NO_SSLv3 = 0x02000000; public static final int SSL_OP_NO_TLSv1 = 0x04000000; public static final int SSL_OP_NO_TICKET = 0x00004000; /* The next flag deliberately changes the ciphertest, this is a check * for the PKCS#1 attack */ public static final int SSL_OP_PKCS1_CHECK_1 = 0x08000000; public static final int SSL_OP_PKCS1_CHECK_2 = 0x10000000; public static final int SSL_OP_NETSCAPE_CA_DN_BUG = 0x20000000; public static final int SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG = 0x40000000; public static final int SSL_CRT_FORMAT_UNDEF = 0; public static final int SSL_CRT_FORMAT_ASN1 = 1; public static final int SSL_CRT_FORMAT_TEXT = 2; public static final int SSL_CRT_FORMAT_PEM = 3; public static final int SSL_CRT_FORMAT_NETSCAPE = 4; public static final int SSL_CRT_FORMAT_PKCS12 = 5; public static final int SSL_CRT_FORMAT_SMIME = 6; public static final int SSL_CRT_FORMAT_ENGINE = 7; public static final int SSL_MODE_CLIENT = 0; public static final int SSL_MODE_SERVER = 1; public static final int SSL_MODE_COMBINED = 2; public static final int SSL_SHUTDOWN_TYPE_UNSET = 0; public static final int SSL_SHUTDOWN_TYPE_STANDARD = 1; public static final int SSL_SHUTDOWN_TYPE_UNCLEAN = 2; public static final int SSL_SHUTDOWN_TYPE_ACCURATE = 3; public static final int SSL_INFO_SESSION_ID = 0x0001; public static final int SSL_INFO_CIPHER = 0x0002; public static final int SSL_INFO_CIPHER_USEKEYSIZE = 0x0003; public static final int SSL_INFO_CIPHER_ALGKEYSIZE = 0x0004; public static final int SSL_INFO_CIPHER_VERSION = 0x0005; public static final int SSL_INFO_CIPHER_DESCRIPTION = 0x0006; public static final int SSL_INFO_PROTOCOL = 0x0007; /* To obtain the CountryName of the Client Certificate Issuer * use the SSL_INFO_CLIENT_I_DN + SSL_INFO_DN_COUNTRYNAME */ public static final int SSL_INFO_CLIENT_S_DN = 0x0010; public static final int SSL_INFO_CLIENT_I_DN = 0x0020; public static final int SSL_INFO_SERVER_S_DN = 0x0040; public static final int SSL_INFO_SERVER_I_DN = 0x0080; public static final int SSL_INFO_DN_COUNTRYNAME = 0x0001; public static final int SSL_INFO_DN_STATEORPROVINCENAME = 0x0002; public static final int SSL_INFO_DN_LOCALITYNAME = 0x0003; public static final int SSL_INFO_DN_ORGANIZATIONNAME = 0x0004; public static final int SSL_INFO_DN_ORGANIZATIONALUNITNAME = 0x0005; public static final int SSL_INFO_DN_COMMONNAME = 0x0006; public static final int SSL_INFO_DN_TITLE = 0x0007; public static final int SSL_INFO_DN_INITIALS = 0x0008; public static final int SSL_INFO_DN_GIVENNAME = 0x0009; public static final int SSL_INFO_DN_SURNAME = 0x000A; public static final int SSL_INFO_DN_DESCRIPTION = 0x000B; public static final int SSL_INFO_DN_UNIQUEIDENTIFIER = 0x000C; public static final int SSL_INFO_DN_EMAILADDRESS = 0x000D; public static final int SSL_INFO_CLIENT_M_VERSION = 0x0101; public static final int SSL_INFO_CLIENT_M_SERIAL = 0x0102; public static final int SSL_INFO_CLIENT_V_START = 0x0103; public static final int SSL_INFO_CLIENT_V_END = 0x0104; public static final int SSL_INFO_CLIENT_A_SIG = 0x0105; public static final int SSL_INFO_CLIENT_A_KEY = 0x0106; public static final int SSL_INFO_CLIENT_CERT = 0x0107; public static final int SSL_INFO_CLIENT_V_REMAIN = 0x0108; public static final int SSL_INFO_SERVER_M_VERSION = 0x0201; public static final int SSL_INFO_SERVER_M_SERIAL = 0x0202; public static final int SSL_INFO_SERVER_V_START = 0x0203; public static final int SSL_INFO_SERVER_V_END = 0x0204; public static final int SSL_INFO_SERVER_A_SIG = 0x0205; public static final int SSL_INFO_SERVER_A_KEY = 0x0206; public static final int SSL_INFO_SERVER_CERT = 0x0207; /* Return client certificate chain. * Add certificate chain number to that flag (0 ... verify depth) */ public static final int SSL_INFO_CLIENT_CERT_CHAIN = 0x0400; /* Return OpenSSL version number */ public static native int version(); /* Return OpenSSL version string */ public static native String versionString(); /** * Initialize OpenSSL support. * This function needs to be called once for the * lifetime of JVM. Library.init() has to be called before. * @param engine Support for external a Crypto Device ("engine"), * usually * a hardware accelerator card for crypto operations. * @return APR status code */ public static native int initialize(String engine); /** * Enable/Disable FIPS Mode. * * @param mode 1 - enable, 0 - disable * * @return FIPS_mode_set return code */ public static native int fipsModeSet(int mode); /** * Add content of the file to the PRNG * @param filename Filename containing random data. * If null the default file will be tested. * The seed file is $RANDFILE if that environment variable is * set, $HOME/.rnd otherwise. * In case both files are unavailable builtin * random seed generator is used. */ public static native boolean randLoad(String filename); /** * Writes a number of random bytes (currently 1024) to * file <code>filename</code> which can be used to initialize the PRNG * by calling randLoad in a later session. * @param filename Filename to save the data */ public static native boolean randSave(String filename); /** * Creates random data to filename * @param filename Filename to save the data * @param len The length of random sequence in bytes * @param base64 Output the data in Base64 encoded format */ public static native boolean randMake(String filename, int len, boolean base64); /** * Sets global random filename. * @param filename Filename to use. * If set it will be used for SSL initialization * and all contexts where explicitly not set. */ public static native void randSet(String filename); /** * Initialize new BIO * @param pool The pool to use. * @param callback BIOCallback to use * @return New BIO handle */ public static native long newBIO(long pool, BIOCallback callback) throws Exception; /** * Close BIO and dereference callback object * @param bio BIO to close and destroy. * @return APR Status code */ public static native int closeBIO(long bio); /** * Set global Password callback for obtaining passwords. * @param callback PasswordCallback implementation to use. */ public static native void setPasswordCallback(PasswordCallback callback); /** * Set global Password for decrypting certificates and keys. * @param password Password to use. */ public static native void setPassword(String password); /** * Generate temporary RSA key. * <br /> * Index can be one of: * <PRE> * SSL_TMP_KEY_RSA_512 * SSL_TMP_KEY_RSA_1024 * SSL_TMP_KEY_RSA_2048 * SSL_TMP_KEY_RSA_4096 * </PRE> * By default 512 and 1024 keys are generated on startup. * You can use a low priority thread to generate them on the fly. * @param idx temporary key index. */ public static native boolean generateRSATempKey(int idx); /** * Load temporary DSA key from file * <br /> * Index can be one of: * <PRE> * SSL_TMP_KEY_DH_512 * SSL_TMP_KEY_DH_1024 * SSL_TMP_KEY_DH_2048 * SSL_TMP_KEY_DH_4096 * </PRE> * @param idx temporary key index. * @param file File containing DH params. */ public static native boolean loadDSATempKey(int idx, String file); /** * Return last SSL error string */ public static native String getLastError(); /** * Return true if SSL_OP_ if defined. * <p> * Currently used for testing weather the * SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION is supported by OpenSSL. * <p> * @param op SSL_OP to test. * @return true if SSL_OP is supported by OpenSSL library. */ public static native boolean hasOp(int op); }
54,324
Bug 54324 Support is required to disable TLS compression to prevent against CRIME attacks
null
resolved fixed
ab44514
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-17T20:03:00Z
2012-12-19T04:06:40Z
java/org/apache/tomcat/util/net/AprEndpoint.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.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.jni.Address; import org.apache.tomcat.jni.Error; import org.apache.tomcat.jni.File; import org.apache.tomcat.jni.Library; import org.apache.tomcat.jni.OS; import org.apache.tomcat.jni.Poll; import org.apache.tomcat.jni.Pool; import org.apache.tomcat.jni.SSL; import org.apache.tomcat.jni.SSLContext; import org.apache.tomcat.jni.SSLSocket; import org.apache.tomcat.jni.Sockaddr; import org.apache.tomcat.jni.Socket; import org.apache.tomcat.jni.Status; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.net.AbstractEndpoint.Acceptor.AcceptorState; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; /** * APR tailored thread pool, providing the following services: * <ul> * <li>Socket acceptor thread</li> * <li>Socket poller thread</li> * <li>Sendfile 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 */ public class AprEndpoint extends AbstractEndpoint { // -------------------------------------------------------------- Constants private static final Log log = LogFactory.getLog(AprEndpoint.class); // ----------------------------------------------------------------- Fields /** * Root APR memory pool. */ protected long rootPool = 0; /** * Server socket "pointer". */ protected long serverSock = 0; /** * APR memory pool for the server socket. */ protected long serverSockPool = 0; /** * SSL context. */ protected long sslContext = 0; protected ConcurrentLinkedQueue<SocketWrapper<Long>> waitingRequests = new ConcurrentLinkedQueue<>(); private Map<Long,AprSocketWrapper> connections = new ConcurrentHashMap<>(); // ------------------------------------------------------------ Constructor public AprEndpoint() { // Need to override the default for maxConnections to align it with what // was pollerSize (before the two were merged) setMaxConnections(8 * 1024); } // ------------------------------------------------------------- Properties /** * Defer accept. */ protected boolean deferAccept = true; public void setDeferAccept(boolean deferAccept) { this.deferAccept = deferAccept; } @Override public boolean getDeferAccept() { return deferAccept; } /** * Size of the sendfile (= concurrent files which can be served). */ protected int sendfileSize = 1 * 1024; public void setSendfileSize(int sendfileSize) { this.sendfileSize = sendfileSize; } public int getSendfileSize() { return sendfileSize; } /** * Handling of accepted sockets. */ protected Handler handler = null; public void setHandler(Handler handler ) { this.handler = handler; } public Handler getHandler() { return handler; } /** * Poll interval, in microseconds. The smaller the value, the more CPU the poller * will use, but the more responsive to activity it will be. */ protected int pollTime = 2000; public int getPollTime() { return pollTime; } public void setPollTime(int pollTime) { if (pollTime > 0) { this.pollTime = pollTime; } } /** * Use sendfile for sending static files. */ protected boolean useSendfile = Library.APR_HAS_SENDFILE; public void setUseSendfile(boolean useSendfile) { this.useSendfile = useSendfile; } @Override public boolean getUseSendfile() { return useSendfile; } /** * Allow comet request handling. */ protected boolean useComet = true; public void setUseComet(boolean useComet) { this.useComet = useComet; } @Override public boolean getUseComet() { return useComet; } @Override public boolean getUseCometTimeout() { return false; } // Not supported @Override public boolean getUsePolling() { return true; } // Always supported /** * Sendfile thread count. */ protected int sendfileThreadCount = 0; public void setSendfileThreadCount(int sendfileThreadCount) { this.sendfileThreadCount = sendfileThreadCount; } public int getSendfileThreadCount() { return sendfileThreadCount; } /** * The socket poller. */ protected Poller poller = null; public Poller getPoller() { return poller; } /** * The static file sender. */ protected Sendfile sendfile = null; public Sendfile getSendfile() { return sendfile; } /** * SSL protocols. */ protected String SSLProtocol = "all"; public String getSSLProtocol() { return SSLProtocol; } public void setSSLProtocol(String SSLProtocol) { this.SSLProtocol = SSLProtocol; } /** * SSL password (if a cert is encrypted, and no password has been provided, a callback * will ask for a password). */ protected String SSLPassword = null; public String getSSLPassword() { return SSLPassword; } public void setSSLPassword(String SSLPassword) { this.SSLPassword = SSLPassword; } /** * SSL cipher suite. */ protected String SSLCipherSuite = "ALL"; public String getSSLCipherSuite() { return SSLCipherSuite; } public void setSSLCipherSuite(String SSLCipherSuite) { this.SSLCipherSuite = SSLCipherSuite; } /** * SSL certificate file. */ protected String SSLCertificateFile = null; public String getSSLCertificateFile() { return SSLCertificateFile; } public void setSSLCertificateFile(String SSLCertificateFile) { this.SSLCertificateFile = SSLCertificateFile; } /** * SSL certificate key file. */ protected String SSLCertificateKeyFile = null; public String getSSLCertificateKeyFile() { return SSLCertificateKeyFile; } public void setSSLCertificateKeyFile(String SSLCertificateKeyFile) { this.SSLCertificateKeyFile = SSLCertificateKeyFile; } /** * SSL certificate chain file. */ protected String SSLCertificateChainFile = null; public String getSSLCertificateChainFile() { return SSLCertificateChainFile; } public void setSSLCertificateChainFile(String SSLCertificateChainFile) { this.SSLCertificateChainFile = SSLCertificateChainFile; } /** * SSL CA certificate path. */ protected String SSLCACertificatePath = null; public String getSSLCACertificatePath() { return SSLCACertificatePath; } public void setSSLCACertificatePath(String SSLCACertificatePath) { this.SSLCACertificatePath = SSLCACertificatePath; } /** * SSL CA certificate file. */ protected String SSLCACertificateFile = null; public String getSSLCACertificateFile() { return SSLCACertificateFile; } public void setSSLCACertificateFile(String SSLCACertificateFile) { this.SSLCACertificateFile = SSLCACertificateFile; } /** * SSL CA revocation path. */ protected String SSLCARevocationPath = null; public String getSSLCARevocationPath() { return SSLCARevocationPath; } public void setSSLCARevocationPath(String SSLCARevocationPath) { this.SSLCARevocationPath = SSLCARevocationPath; } /** * SSL CA revocation file. */ protected String SSLCARevocationFile = null; public String getSSLCARevocationFile() { return SSLCARevocationFile; } public void setSSLCARevocationFile(String SSLCARevocationFile) { this.SSLCARevocationFile = SSLCARevocationFile; } /** * SSL verify client. */ protected String SSLVerifyClient = "none"; public String getSSLVerifyClient() { return SSLVerifyClient; } public void setSSLVerifyClient(String SSLVerifyClient) { this.SSLVerifyClient = SSLVerifyClient; } /** * SSL verify depth. */ protected int SSLVerifyDepth = 10; public int getSSLVerifyDepth() { return SSLVerifyDepth; } public void setSSLVerifyDepth(int SSLVerifyDepth) { this.SSLVerifyDepth = SSLVerifyDepth; } /** * SSL allow insecure renegotiation for the the client that does not * support the secure renegotiation. */ protected boolean SSLInsecureRenegotiation = false; public void setSSLInsecureRenegotiation(boolean SSLInsecureRenegotiation) { this.SSLInsecureRenegotiation = SSLInsecureRenegotiation; } public boolean getSSLInsecureRenegotiation() { return SSLInsecureRenegotiation; } protected boolean SSLHonorCipherOrder = false; /** * Set to <code>true</code> to enforce the <i>server's</i> cipher order * instead of the default which is to allow the client to choose a * preferred cipher. */ public void setSSLHonorCipherOrder(boolean SSLHonorCipherOrder) { this.SSLHonorCipherOrder = SSLHonorCipherOrder; } public boolean getSSLHonorCipherOrder() { return SSLHonorCipherOrder; } /** * Port in use. */ @Override public int getLocalPort() { long s = serverSock; if (s == 0) { return -1; } else { long sa; try { sa = Address.get(Socket.APR_LOCAL, s); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception e) { return -1; } } } @Override public String[] getCiphersUsed() { // TODO : Investigate if it is possible to extract the current list of // available ciphers. Native code changes will be required. return new String[] { getSSLCipherSuite() }; } // --------------------------------------------------------- Public Methods /** * Number of keepalive sockets. */ public int getKeepAliveCount() { if (poller == null) { return 0; } return poller.getConnectionCount(); } /** * Number of sendfile sockets. */ public int getSendfileCount() { if (sendfile == null) { return 0; } return sendfile.getSendfileCount(); } // ----------------------------------------------- Public Lifecycle Methods /** * Initialize the endpoint. */ @Override public void bind() throws Exception { // Create the root APR memory pool try { rootPool = Pool.create(0); } catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); } // Create the pool for the server socket serverSockPool = Pool.create(rootPool); // Create the APR address that will be bound String addressStr = null; if (getAddress() != null) { addressStr = getAddress().getHostAddress(); } int family = Socket.APR_INET; if (Library.APR_HAVE_IPV6) { if (addressStr == null) { if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64) family = Socket.APR_UNSPEC; } else if (addressStr.indexOf(':') >= 0) { family = Socket.APR_UNSPEC; } } long inetAddress = Address.info(addressStr, family, getPort(), 0, rootPool); // Create the APR server socket serverSock = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, rootPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret))); } // Start listening on the server socket ret = Socket.listen(serverSock, getBacklog()); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret))); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Initialize thread count default for acceptor if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } // Initialize SSL if needed if (isSSLEnabled()) { if (SSLCertificateFile == null) { // This is required throw new Exception(sm.getString("endpoint.apr.noSslCertFile")); } // SSL protocol int value = SSL.SSL_PROTOCOL_NONE; if (SSLProtocol == null || SSLProtocol.length() == 0) { value = SSL.SSL_PROTOCOL_ALL; } else { for (String protocol : SSLProtocol.split("\\+")) { protocol = protocol.trim(); if ("SSLv2".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_TLSV1; } else if ("all".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_ALL; } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } } // Create SSL Context sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER); if (SSLInsecureRenegotiation) { boolean legacyRenegSupported = false; try { legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); if (legacyRenegSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!legacyRenegSupported) { // OpenSSL does not support unsafe legacy renegotiation. log.warn(sm.getString("endpoint.warn.noInsecureReneg", SSL.versionString())); } } // Set cipher order: client (default) or server if (SSLHonorCipherOrder) { boolean orderCiphersSupported = false; try { orderCiphersSupported = SSL.hasOp(SSL.SSL_OP_CIPHER_SERVER_PREFERENCE); if (orderCiphersSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE); } catch (UnsatisfiedLinkError e) { // Ignore } if (!orderCiphersSupported) { // OpenSSL does not support ciphers ordering. log.warn(sm.getString("endpoint.warn.noHonorCipherOrder", SSL.versionString())); } } // List the ciphers that the client is permitted to negotiate SSLContext.setCipherSuite(sslContext, SSLCipherSuite); // Load Server key and certificate SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA); // Set certificate chain file SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false); // Support Client Certificates SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath); // Set revocation SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification value = SSL.SSL_CVERIFY_NONE; if ("optional".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL; } else if ("require".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_REQUIRE; } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA; } SSLContext.setVerify(sslContext, value, SSLVerifyDepth); // For now, sendfile is not supported with SSL useSendfile = false; } } public long getJniSslContext() { return sslContext; } /** * Start the APR endpoint, creating acceptor, poller and sendfile threads. */ @Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); // Start poller thread poller = new Poller(); poller.init(); Thread pollerThread = new Thread(poller, getName() + "-Poller"); pollerThread.setPriority(threadPriority); pollerThread.setDaemon(true); pollerThread.start(); // Start sendfile thread if (useSendfile) { sendfile = new Sendfile(); sendfile.init(); Thread sendfileThread = new Thread(sendfile, getName() + "-Sendfile"); sendfileThread.setPriority(threadPriority); sendfileThread.setDaemon(true); sendfileThread.start(); } startAcceptorThreads(); // Start async timeout thread Thread timeoutThread = new Thread(new AsyncTimeout(), getName() + "-AsyncTimeout"); timeoutThread.setPriority(threadPriority); timeoutThread.setDaemon(true); timeoutThread.start(); } } /** * 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 (AbstractEndpoint.Acceptor acceptor : acceptors) { long waitLeft = 10000; while (waitLeft > 0 && acceptor.getState() != AcceptorState.ENDED && serverSock != 0) { try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore } waitLeft -= 50; } if (waitLeft == 0) { log.warn(sm.getString("endpoint.warn.unlockAcceptorFailed", acceptor.getThreadName())); // If the Acceptor is still running force // the hard socket close. if (serverSock != 0) { Socket.shutdown(serverSock, Socket.APR_SHUTDOWN_READ); serverSock = 0; } } } try { poller.destroy(); } catch (Exception e) { // Ignore } poller = null; connections.clear(); if (useSendfile) { try { sendfile.destroy(); } catch (Exception e) { // Ignore } sendfile = null; } } shutdownExecutor(); } /** * Deallocate APR memory pools, and close server socket. */ @Override public void unbind() throws Exception { if (running) { stop(); } // Destroy pool if it was initialised if (serverSockPool != 0) { Pool.destroy(serverSockPool); serverSockPool = 0; } // Close server socket if it was initialised if (serverSock != 0) { Socket.close(serverSock); serverSock = 0; } sslContext = 0; // Close all APR memory pools and resources if initialised if (rootPool != 0) { Pool.destroy(rootPool); rootPool = 0; } handler.recycle(); } // ------------------------------------------------------ Protected Methods @Override protected AbstractEndpoint.Acceptor createAcceptor() { return new Acceptor(); } /** * Process the specified connection. */ protected boolean setSocketOptions(long socket) { // Process the connection int step = 1; try { // 1: Set socket options: timeout, linger, etc if (socketProperties.getSoLingerOn() && socketProperties.getSoLingerTime() >= 0) Socket.optSet(socket, Socket.APR_SO_LINGER, socketProperties.getSoLingerTime()); if (socketProperties.getTcpNoDelay()) Socket.optSet(socket, Socket.APR_TCP_NODELAY, (socketProperties.getTcpNoDelay() ? 1 : 0)); Socket.timeoutSet(socket, socketProperties.getSoTimeout() * 1000); // 2: SSL handshake step = 2; if (sslContext != 0) { SSLSocket.attach(sslContext, socket); if (SSLSocket.handshake(socket) != 0) { if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake") + ": " + SSL.getLastError()); } return false; } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; } return true; } /** * Allocate a new poller of the specified size. */ protected long allocatePoller(int size, long pool, int timeout) { try { return Poll.create(size, pool, 0, timeout * 1000); } catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } } } /** * Process given socket. This is called when the socket has been * accepted. */ protected boolean processSocketWithOptions(long socket) { try { // During shutdown, executor may be null - avoid NPE if (running) { AprSocketWrapper wrapper = new AprSocketWrapper(Long.valueOf(socket)); wrapper.setKeepAliveLeft(getMaxKeepAliveRequests()); connections.put(Long.valueOf(socket), wrapper); getExecutor().execute(new SocketWithOptionsProcessor(wrapper)); } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); 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; } /** * Process given socket. Called in non-comet mode, typically keep alive * or upgraded protocol. */ public boolean processSocket(long socket, SocketStatus status) { try { Executor executor = getExecutor(); if (executor == null) { log.warn(sm.getString("endpoint.warn.noExector", Long.valueOf(socket), null)); } else { SocketWrapper<Long> wrapper = connections.get(Long.valueOf(socket)); executor.execute(new SocketProcessor(wrapper, status)); } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); 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; } public boolean processSocketAsync(SocketWrapper<Long> socket, SocketStatus status) { try { synchronized (socket) { if (waitingRequests.remove(socket)) { SocketProcessor proc = new SocketProcessor(socket, status); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { //threads should not be created by the webapp classloader if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( getClass().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); } Executor executor = getExecutor(); if (executor == null) { log.warn(sm.getString("endpoint.warn.noExector", socket, status)); return false; } else { executor.execute(proc); } } finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } } } } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for: "+socket, x); 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; } private void destroySocket(long socket) { // If not running the socket will be destroyed by // parent pool or acceptor socket. // In any case disable double free which would cause JVM core. // While the connector is running, destroySocket() will call // countDownConnection(). Once the connector is stopped, the latch is // removed so it does not matter that destroySocket() does not call // countDownConnection() in that case connections.remove(Long.valueOf(socket)); destroySocket(socket, running); } private void destroySocket(long socket, boolean doIt) { // Be VERY careful if you call this method directly. If it is called // twice for the same socket the JVM will core. Currently this is only // called from Poller.closePollset() to ensure kept alive connections // are closed when calling stop() followed by start(). if (doIt && socket != 0) { Socket.destroy(socket); countDownConnection(); } } @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 { private final Log log = LogFactory.getLog(AprEndpoint.Acceptor.class); @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(); long socket = 0; try { // Accept the next incoming connection from the server // socket socket = Socket.accept(serverSock); } catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; } // Successful accept, reset the error delay errorDelay = 0; if (running && !paused) { // Hand this socket off to an appropriate processor if (!processSocketWithOptions(socket)) { // Close socket and pool right away destroySocket(socket); } } else { // Close socket and pool right away destroySocket(socket); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } } // The processor will recycle itself when it finishes } state = AcceptorState.ENDED; } } /** * Async timeout thread */ protected class AsyncTimeout implements Runnable { /** * The background thread that checks async requests and fires the * timeout if there has been no activity. */ @Override public void run() { // Loop until we receive a shutdown command while (running) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } long now = System.currentTimeMillis(); Iterator<SocketWrapper<Long>> sockets = waitingRequests.iterator(); while (sockets.hasNext()) { SocketWrapper<Long> socket = sockets.next(); if (socket.async) { long access = socket.getLastAccess(); if (socket.getTimeout() > 0 && (now-access)>socket.getTimeout()) { processSocketAsync(socket,SocketStatus.TIMEOUT); } } } // Loop if endpoint is paused while (paused && running) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } } } } // -------------------------------------------------- SocketInfo Inner Class public static class SocketInfo { public long socket; public int timeout; public int flags; public boolean read() { return (flags & Poll.APR_POLLIN) == Poll.APR_POLLIN; } public boolean write() { return (flags & Poll.APR_POLLOUT) == Poll.APR_POLLOUT; } public static int merge(int flag1, int flag2) { return ((flag1 & Poll.APR_POLLIN) | (flag2 & Poll.APR_POLLIN)) | ((flag1 & Poll.APR_POLLOUT) | (flag2 & Poll.APR_POLLOUT)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Socket: ["); sb.append(socket); sb.append("], timeout: ["); sb.append(timeout); sb.append("], flags: ["); sb.append(flags); return sb.toString(); } } // ---------------------------------------------- SocketTimeouts Inner Class public class SocketTimeouts { protected int size; protected long[] sockets; protected long[] timeouts; protected int pos = 0; public SocketTimeouts(int size) { this.size = 0; sockets = new long[size]; timeouts = new long[size]; } public void add(long socket, long timeout) { sockets[size] = socket; timeouts[size] = timeout; size++; } public boolean remove(long socket) { for (int i = 0; i < size; i++) { if (sockets[i] == socket) { sockets[i] = sockets[size - 1]; timeouts[i] = timeouts[size - 1]; size--; return true; } } return false; } public long check(long date) { while (pos < size) { if (date >= timeouts[pos]) { long result = sockets[pos]; sockets[pos] = sockets[size - 1]; timeouts[pos] = timeouts[size - 1]; size--; return result; } pos++; } pos = 0; return 0; } } // -------------------------------------------------- SocketList Inner Class public class SocketList { protected int size; protected int pos; protected long[] sockets; protected int[] timeouts; protected int[] flags; protected SocketInfo info = new SocketInfo(); public SocketList(int size) { this.size = 0; pos = 0; sockets = new long[size]; timeouts = new int[size]; flags = new int[size]; } public int size() { return this.size; } public SocketInfo get() { if (pos == size) { return null; } else { info.socket = sockets[pos]; info.timeout = timeouts[pos]; info.flags = flags[pos]; pos++; return info; } } public void clear() { size = 0; pos = 0; } public boolean add(long socket, int timeout, int flag) { if (size == sockets.length) { return false; } else { for (int i = 0; i < size; i++) { if (sockets[i] == socket) { flags[i] = SocketInfo.merge(flags[i], flag); return true; } } sockets[size] = socket; timeouts[size] = timeout; flags[size] = flag; size++; return true; } } public void duplicate(SocketList copy) { copy.size = size; copy.pos = pos; System.arraycopy(sockets, 0, copy.sockets, 0, size); System.arraycopy(timeouts, 0, copy.timeouts, 0, size); System.arraycopy(flags, 0, copy.flags, 0, size); } } // ------------------------------------------------------ Poller Inner Class public class Poller implements Runnable { /** * Pointers to the pollers. */ protected long[] pollers = null; /** * Actual poller size. */ protected int actualPollerSize = 0; /** * Amount of spots left in the poller. */ protected int[] pollerSpace = null; /** * Amount of low level pollers in use by this poller. */ protected int pollerCount; /** * Timeout value for the poll call. */ protected int pollerTime; /** * Root pool. */ protected long pool = 0; /** * Socket descriptors. */ protected long[] desc; /** * List of sockets to be added to the poller. */ protected SocketList addList = null; /** * List of sockets to be added to the poller. */ protected SocketList localAddList = null; /** * Structure used for storing timeouts. */ protected SocketTimeouts timeouts = null; /** * Last run of maintain. Maintain will run usually every 5s. */ protected long lastMaintain = System.currentTimeMillis(); /** * Amount of connections inside this poller. */ protected int connectionCount = 0; public int getConnectionCount() { return connectionCount; } /** * Create the poller. With some versions of APR, the maximum poller size * will be 62 (recompiling APR is necessary to remove this limitation). */ protected void init() { pool = Pool.create(serverSockPool); // Single poller by default int defaultPollerSize = getMaxConnections(); if ((OS.IS_WIN32 || OS.IS_WIN64) && (defaultPollerSize > 1024)) { // The maximum per poller to get reasonable performance is 1024 // Adjust poller size so that it won't reach the limit. This is // a limitation of XP / Server 2003 that has been fixed in // Vista / Server 2008 onwards. defaultPollerSize = 1024; } actualPollerSize = defaultPollerSize; timeouts = new SocketTimeouts(defaultPollerSize); // At the moment, setting the timeout is useless, but it could get // used again as the normal poller could be faster using maintain. // It might not be worth bothering though. long pollset = allocatePoller(actualPollerSize, pool, -1); if (pollset == 0 && actualPollerSize > 1024) { actualPollerSize = 1024; pollset = allocatePoller(actualPollerSize, pool, -1); } if (pollset == 0) { actualPollerSize = 62; pollset = allocatePoller(actualPollerSize, pool, -1); } pollerCount = defaultPollerSize / actualPollerSize; pollerTime = pollTime / pollerCount; pollers = new long[pollerCount]; pollers[0] = pollset; for (int i = 1; i < pollerCount; i++) { pollers[i] = allocatePoller(actualPollerSize, pool, -1); } pollerSpace = new int[pollerCount]; for (int i = 0; i < pollerCount; i++) { pollerSpace[i] = actualPollerSize; } desc = new long[actualPollerSize * 2]; connectionCount = 0; addList = new SocketList(defaultPollerSize); localAddList = new SocketList(defaultPollerSize); } /** * Destroy the poller. */ protected void destroy() { // Wait for pollerTime before doing anything, so that the poller // threads exit, otherwise parallel destruction of sockets which are // still in the poller can cause problems try { synchronized (this) { this.wait(pollTime / 1000); } } catch (InterruptedException e) { // Ignore } // Close all sockets in the add queue SocketInfo info = addList.get(); while (info != null) { boolean comet = connections.get(Long.valueOf(info.socket)).isComet(); if (!comet || (comet && !processSocket( info.socket, SocketStatus.STOP))) { destroySocket(info.socket); } info = addList.get(); } addList.clear(); // Close all sockets still in the poller for (int i = 0; i < pollerCount; i++) { int rv = Poll.pollset(pollers[i], desc); if (rv > 0) { for (int n = 0; n < rv; n++) { boolean comet = connections.get( Long.valueOf(desc[n*2+1])).isComet(); if (!comet || (comet && !processSocket( desc[n*2+1], SocketStatus.STOP))) { destroySocket(desc[n*2+1]); } } } } Pool.destroy(pool); connectionCount = 0; } /** * 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(long socket) { int timeout = getKeepAliveTimeout(); if (timeout <= 0) { timeout = getSoTimeout(); } if (timeout <= 0) { // Always put a timeout in timeout = Integer.MAX_VALUE; } boolean ok = false; synchronized (this) { // Add socket to the list. Newly added sockets will wait // at most for pollTime before being polled if (addList.add(socket, timeout, Poll.APR_POLLIN)) { ok = true; this.notify(); } } if (!ok) { // Can't do anything: close the socket right away boolean comet = connections.get( Long.valueOf(socket)).isComet(); if (!comet || (comet && !processSocket( socket, SocketStatus.ERROR))) { destroySocket(socket); } } } /** * 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). Note: If both read and write are false, the socket * will only be checked for timeout; if the socket was already present * in the poller, a callback event will be generated and the socket will * be removed from the poller. * * @param socket to add to the poller * @param timeout to use for this connection * @param read to do read polling * @param write to do write polling */ public void add(long socket, int timeout, boolean read, boolean write) { add(socket, timeout, (read ? Poll.APR_POLLIN : 0) | (write ? Poll.APR_POLLOUT : 0)); } private void add(long socket, int timeout, int flags) { if (timeout < 0) { timeout = getSoTimeout(); } if (timeout <= 0) { // Always put a timeout in timeout = Integer.MAX_VALUE; } boolean ok = false; synchronized (this) { // Add socket to the list. Newly added sockets will wait // at most for pollTime before being polled if (addList.add(socket, timeout, flags)) { ok = true; this.notify(); } } if (!ok) { // Can't do anything: close the socket right away boolean comet = connections.get( Long.valueOf(socket)).isComet(); if (!comet || (comet && !processSocket( socket, SocketStatus.ERROR))) { destroySocket(socket); } } } /** * Add specified socket to one of the pollers. */ protected boolean addToPoller(long socket, int events) { int rv = -1; for (int i = 0; i < pollers.length; i++) { if (pollerSpace[i] > 0) { rv = Poll.add(pollers[i], socket, events); if (rv == Status.APR_SUCCESS) { pollerSpace[i]--; connectionCount++; return true; } } } return false; } /** * Remove specified socket from the pollers. */ protected boolean removeFromPoller(long socket) { int rv = -1; for (int i = 0; i < pollers.length; i++) { if (pollerSpace[i] < actualPollerSize) { rv = Poll.remove(pollers[i], socket); if (rv != Status.APR_NOTFOUND) { pollerSpace[i]++; connectionCount--; break; } } } return (rv == Status.APR_SUCCESS); } /** * Timeout checks. */ protected void maintain() { long date = System.currentTimeMillis(); // Maintain runs at most once every 5s, although it will likely get // called more if ((date - lastMaintain) < 5000L) { return; } else { lastMaintain = date; } long socket = timeouts.check(date); while (socket != 0) { removeFromPoller(socket); boolean comet = connections.get( Long.valueOf(socket)).isComet(); if (!comet || (comet && !processSocket( socket, SocketStatus.TIMEOUT))) { destroySocket(socket); } socket = timeouts.check(date); } } /** * Displays the list of sockets in the pollers. */ @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("Poller"); long[] res = new long[actualPollerSize * 2]; for (int i = 0; i < pollers.length; i++) { int count = Poll.pollset(pollers[i], res); buf.append(" [ "); for (int j = 0; j < count; j++) { buf.append(desc[2*j+1]).append(" "); } buf.append("]"); } return buf.toString(); } /** * The background thread that listens for incoming TCP/IP connections * and hands them off to an appropriate processor. */ @Override public void run() { int maintain = 0; // Loop until we receive a shutdown command while (running) { // Loop if endpoint is paused while (paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Check timeouts if the poller is empty while (connectionCount < 1 && addList.size() < 1) { // Reset maintain time. try { if (getSoTimeout() > 0 && running) { maintain(); } synchronized (this) { this.wait(10000); } } catch (InterruptedException e) { // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().warn(sm.getString("endpoint.timeout.err")); } } try { // Add sockets which are waiting to the poller if (addList.size() > 0) { synchronized (this) { // Duplicate to another list, so that the syncing is // minimal addList.duplicate(localAddList); addList.clear(); } SocketInfo info = localAddList.get(); while (info != null) { if (info.read() || info.write()) { AprSocketWrapper wrapper = connections.get( Long.valueOf(info.socket)); boolean comet = wrapper.isComet(); // Store timeout if (comet) { removeFromPoller(info.socket); } wrapper.pollerFlags = wrapper.pollerFlags | (info.read() ? Poll.APR_POLLIN : 0) | (info.write() ? Poll.APR_POLLOUT : 0); if (!addToPoller(info.socket, wrapper.pollerFlags)) { // Can't do anything: close the socket right // away if (!comet || (comet && !processSocket( info.socket, SocketStatus.ERROR))) { destroySocket(info.socket); } } else { timeouts.add(info.socket, System.currentTimeMillis() + info.timeout); } } else { // Should never happen. timeouts.remove(info.socket); destroySocket(info.socket); getLog().warn(sm.getString( "endpoint.apr.pollAddInvalid", info)); } info = localAddList.get(); } } // Poll for the specified interval for (int i = 0; i < pollers.length; i++) { // Flags to ask to reallocate the pool boolean reset = false; //ArrayList<Long> skip = null; int rv = 0; // Iterate on each pollers, but no need to poll empty pollers if (pollerSpace[i] < actualPollerSize) { rv = Poll.poll(pollers[i], pollerTime, desc, true); } if (rv > 0) { pollerSpace[i] += rv; connectionCount -= rv; for (int n = 0; n < rv; n++) { timeouts.remove(desc[n*2+1]); AprSocketWrapper wrapper = connections.get( Long.valueOf(desc[n*2+1])); wrapper.pollerFlags = wrapper.pollerFlags & ~((int) desc[n*2]); if (wrapper.pollerFlags != 0) { add(desc[n*2+1], 1, wrapper.pollerFlags); } // Check for failed sockets and hand this socket off to a worker if (wrapper.isComet()) { // Event processes either a read or a write depending on what the poller returns if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP) || ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR) || ((desc[n*2] & Poll.APR_POLLNVAL) == Poll.APR_POLLNVAL)) { if (!processSocket(desc[n*2+1], SocketStatus.ERROR)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) { if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) { if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else { // Unknown event getLog().warn(sm.getString( "endpoint.apr.pollUnknownEvent", Long.valueOf(desc[n*2]))); if (!processSocket(desc[n*2+1], SocketStatus.ERROR)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } } else if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP) || ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR) || ((desc[n*2] & Poll.APR_POLLNVAL) == Poll.APR_POLLNVAL)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } else if (((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) || ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT)) { boolean error = false; if (((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) && !processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { error = true; // Close socket and clear pool destroySocket(desc[n*2+1]); } if (!error && ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) && !processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else { // Unknown event getLog().warn(sm.getString( "endpoint.apr.pollUnknownEvent", Long.valueOf(desc[n*2]))); // Close socket and clear pool destroySocket(desc[n*2+1]); } } } else if (rv < 0) { int errn = -rv; // Any non timeup or interrupted error is critical if ((errn != Status.TIMEUP) && (errn != Status.EINTR)) { if (errn > Status.APR_OS_START_USERERR) { errn -= Status.APR_OS_START_USERERR; } getLog().error(sm.getString( "endpoint.apr.pollError", Integer.valueOf(errn), Error.strerror(errn))); // Destroy and reallocate the poller reset = true; } } if (reset) { // Reallocate the current poller int count = Poll.pollset(pollers[i], desc); long newPoller = allocatePoller(actualPollerSize, pool, -1); // Don't restore connections for now, since I have not tested it pollerSpace[i] = actualPollerSize; connectionCount -= count; Poll.destroy(pollers[i]); pollers[i] = newPoller; } } // Process socket timeouts if (getSoTimeout() > 0 && maintain++ > 1000 && running) { // This works and uses only one timeout mechanism for everything, but the // non event poller might be a bit faster by using the old maintain. maintain = 0; maintain(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (maintain == 0) { getLog().warn(sm.getString("endpoint.timeout.error"), t); } else { getLog().warn(sm.getString("endpoint.poll.error"), t); } } } synchronized (this) { this.notifyAll(); } } } // ----------------------------------------------- SendfileData Inner Class /** * SendfileData class. */ public static class SendfileData { // File public String fileName; public long fd; public long fdpool; // Range information public long start; public long end; // Socket and socket pool public long socket; // Position public long pos; // KeepAlive flag public boolean keepAlive; } // --------------------------------------------------- Sendfile Inner Class public class Sendfile implements Runnable { protected long sendfilePollset = 0; protected long pool = 0; protected long[] desc; protected HashMap<Long, SendfileData> sendfileData; protected int sendfileCount; public int getSendfileCount() { return sendfileCount; } protected ArrayList<SendfileData> addS; /** * Create the sendfile poller. With some versions of APR, the maximum * poller size will be 62 (recompiling APR is necessary to remove this * limitation). */ protected void init() { pool = Pool.create(serverSockPool); int size = sendfileSize; if (size <= 0) { size = (OS.IS_WIN32 || OS.IS_WIN64) ? (1 * 1024) : (16 * 1024); } sendfilePollset = allocatePoller(size, pool, getSoTimeout()); if (sendfilePollset == 0 && size > 1024) { size = 1024; sendfilePollset = allocatePoller(size, pool, getSoTimeout()); } if (sendfilePollset == 0) { size = 62; sendfilePollset = allocatePoller(size, pool, getSoTimeout()); } desc = new long[size * 2]; sendfileData = new HashMap<>(size); addS = new ArrayList<>(); } /** * Destroy the poller. */ protected void destroy() { // Wait for polltime before doing anything, so that the poller threads // exit, otherwise parallel destruction of sockets which are still // in the poller can cause problems try { synchronized (this) { this.wait(pollTime / 1000); } } catch (InterruptedException e) { // Ignore } // Close any socket remaining in the add queue for (int i = (addS.size() - 1); i >= 0; i--) { SendfileData data = addS.get(i); destroySocket(data.socket); } // Close all sockets still in the poller int rv = Poll.pollset(sendfilePollset, desc); if (rv > 0) { for (int n = 0; n < rv; n++) { destroySocket(desc[n*2+1]); } } Pool.destroy(pool); sendfileData.clear(); } /** * Add the sendfile data to the sendfile poller. Note that in most cases, * the initial non blocking calls to sendfile will return right away, and * will be handled asynchronously inside the kernel. As a result, * the poller will never be used. * * @param data containing the reference to the data which should be snet * @return true if all the data has been sent right away, and false * otherwise */ public boolean add(SendfileData data) { // Initialize fd from data given try { data.fdpool = Socket.pool(data.socket); data.fd = File.open (data.fileName, File.APR_FOPEN_READ | File.APR_FOPEN_SENDFILE_ENABLED | File.APR_FOPEN_BINARY, 0, data.fdpool); data.pos = data.start; // Set the socket to nonblocking mode Socket.timeoutSet(data.socket, 0); while (true) { long nw = Socket.sendfilen(data.socket, data.fd, data.pos, data.end - data.pos, 0); if (nw < 0) { if (!(-nw == Status.EAGAIN)) { Pool.destroy(data.fdpool); data.socket = 0; return false; } else { // Break the loop and add the socket to poller. break; } } else { data.pos = data.pos + nw; if (data.pos >= data.end) { // Entire file has been sent Pool.destroy(data.fdpool); // Set back socket to blocking mode Socket.timeoutSet( data.socket, getSoTimeout() * 1000); return true; } } } } catch (Exception e) { log.warn(sm.getString("endpoint.sendfile.error"), e); return false; } // Add socket to the list. Newly added sockets will wait // at most for pollTime before being polled synchronized (this) { addS.add(data); this.notify(); } return false; } /** * Remove socket from the poller. * * @param data the sendfile data which should be removed */ protected void remove(SendfileData data) { int rv = Poll.remove(sendfilePollset, data.socket); if (rv == Status.APR_SUCCESS) { sendfileCount--; } sendfileData.remove(new Long(data.socket)); } /** * The background thread that listens for incoming TCP/IP connections * and hands them off to an appropriate processor. */ @Override public void run() { long maintainTime = 0; // Loop until we receive a shutdown command while (running) { // Loop if endpoint is paused while (paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Loop if poller is empty while (sendfileCount < 1 && addS.size() < 1) { // Reset maintain time. maintainTime = 0; try { synchronized (this) { this.wait(); } } catch (InterruptedException e) { // Ignore } } try { // Add socket to the poller if (addS.size() > 0) { synchronized (this) { for (int i = (addS.size() - 1); i >= 0; i--) { SendfileData data = addS.get(i); int rv = Poll.add(sendfilePollset, data.socket, Poll.APR_POLLOUT); if (rv == Status.APR_SUCCESS) { sendfileData.put(new Long(data.socket), data); sendfileCount++; } else { getLog().warn(sm.getString( "endpoint.sendfile.addfail", Integer.valueOf(rv), Error.strerror(rv))); // Can't do anything: close the socket right away destroySocket(data.socket); } } addS.clear(); } } maintainTime += pollTime; // Pool for the specified interval int rv = Poll.poll(sendfilePollset, pollTime, desc, false); if (rv > 0) { for (int n = 0; n < rv; n++) { // Get the sendfile state SendfileData state = sendfileData.get(new Long(desc[n*2+1])); // Problem events if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP) || ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR)) { // Close socket and clear pool remove(state); // Destroy file descriptor pool, which should close the file // Close the socket, as the response would be incomplete destroySocket(state.socket); continue; } // Write some data using sendfile long nw = Socket.sendfilen(state.socket, state.fd, state.pos, state.end - state.pos, 0); if (nw < 0) { // Close socket and clear pool remove(state); // Close the socket, as the response would be incomplete // This will close the file too. destroySocket(state.socket); continue; } state.pos = state.pos + nw; if (state.pos >= state.end) { remove(state); if (state.keepAlive) { // Destroy file descriptor pool, which should close the file Pool.destroy(state.fdpool); Socket.timeoutSet(state.socket, getSoTimeout() * 1000); // If all done put the socket back in the poller for // processing of further requests getPoller().add(state.socket); } else { // Close the socket since this is // the end of not keep-alive request. destroySocket(state.socket); } } } } else if (rv < 0) { int errn = -rv; /* Any non timeup or interrupted error is critical */ if ((errn != Status.TIMEUP) && (errn != Status.EINTR)) { if (errn > Status.APR_OS_START_USERERR) { errn -= Status.APR_OS_START_USERERR; } getLog().error(sm.getString( "Unexpected poller error", Integer.valueOf(errn), Error.strerror(errn))); // Handle poll critical failure synchronized (this) { destroy(); init(); } continue; } } // Call maintain for the sendfile poller if (getSoTimeout() > 0 && maintainTime > 1000000L && running) { rv = Poll.maintain(sendfilePollset, desc, false); maintainTime = 0; if (rv > 0) { for (int n = 0; n < rv; n++) { // Get the sendfile state SendfileData state = sendfileData.get(new Long(desc[n])); // Close socket and clear pool remove(state); // Destroy file descriptor pool, which should close the file // Close the socket, as the response would be incomplete destroySocket(state.socket); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("endpoint.poll.error"), t); } } synchronized (this) { this.notifyAll(); } } } // ------------------------------------------------ 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<Long> socket, SocketStatus status); } // --------------------------------- SocketWithOptionsProcessor Inner Class /** * This class is the equivalent of the Worker, but will simply use in an * external Executor thread pool. This will also set the socket options * and do the handshake. * * This is called after an accept(). */ protected class SocketWithOptionsProcessor implements Runnable { protected SocketWrapper<Long> socket = null; public SocketWithOptionsProcessor(SocketWrapper<Long> socket) { this.socket = socket; } @Override public void run() { synchronized (socket) { if (!deferAccept) { if (setSocketOptions(socket.getSocket().longValue())) { getPoller().add(socket.getSocket().longValue(), getSoTimeout(), true, false); } else { // Close socket and pool destroySocket(socket.getSocket().longValue()); socket = null; } } else { // Process the request from this socket if (!setSocketOptions(socket.getSocket().longValue())) { // Close socket and pool destroySocket(socket.getSocket().longValue()); socket = null; return; } // Process the request from this socket Handler.SocketState state = handler.process(socket, SocketStatus.OPEN_READ); if (state == Handler.SocketState.CLOSED) { // Close socket and pool destroySocket(socket.getSocket().longValue()); socket = null; } else if (state == Handler.SocketState.LONG) { socket.access(); if (socket.async) { waitingRequests.add(socket); } } } } } } // -------------------------------------------- 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 final SocketWrapper<Long> socket; private final SocketStatus status; public SocketProcessor(SocketWrapper<Long> socket, SocketStatus status) { this.socket = socket; if (status == null) { // Should never happen throw new NullPointerException(); } this.status = status; } @Override public void run() { // Upgraded connections need to allow multiple threads to access the // connection at the same time to enable blocking IO to be used when // Servlet 3.1 NIO has been configured if (socket.isUpgraded()) { doRun(); } else { synchronized (socket) { doRun(); } } } private void doRun() { // Process the request from this socket SocketState state = handler.process(socket, status); if (state == Handler.SocketState.CLOSED) { // Close socket and pool destroySocket(socket.getSocket().longValue()); } else if (state == Handler.SocketState.LONG) { socket.access(); if (socket.async) { waitingRequests.add(socket); } } else if (state == Handler.SocketState.ASYNC_END) { socket.access(); SocketProcessor proc = new SocketProcessor(socket, SocketStatus.OPEN_READ); getExecutor().execute(proc); } } } private static class AprSocketWrapper extends SocketWrapper<Long> { // This field should only be used by Poller#run() private int pollerFlags = 0; public AprSocketWrapper(Long socket) { super(socket); } } private static class PrivilegedSetTccl implements PrivilegedAction<Void> { private ClassLoader cl; PrivilegedSetTccl(ClassLoader cl) { this.cl = cl; } @Override public Void run() { Thread.currentThread().setContextClassLoader(cl); return null; } } }
54,448
Bug 54448 Field of primitive type, annotated with @Resource is not recognized as env entry
Hi, I have a servlet with one field of primitive type. The field is annotated with @Resource. public class MyServlet extends HttpServlet { @Resource(mappedName = "1") private int envEntry; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ... } } When I request this servlet I receive the following exception: SEVERE: Allocate exception for servlet MyServlet javax.naming.NamingException: Cannot create resource instance at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:117) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at org.apache.naming.NamingContext.lookup(NamingContext.java:843) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:581) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:470) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) That's because in the method below the primitive types are not 'converted' to their corresponding wrappers and this field is interpreted not as env entry but as resource env ref. org.apache.catalina.startup.WebAnnotationSet.addResource(Context, Resource, String, String) I'm attaching a patch that solves this issue and a test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
74f5b3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:09:03Z
2013-01-18T03:33:20Z
java/org/apache/catalina/deploy/NamingResources.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.deploy; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.Serializable; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import javax.naming.NamingException; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.JmxEnabled; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Server; import org.apache.catalina.mbeans.MBeanUtils; import org.apache.catalina.util.Introspection; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.naming.ContextBindings; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * Holds and manages the naming resources defined in the J2EE Enterprise * Naming Context and their associated JNDI context. * * @author Remy Maucherat * @version $Id$ */ public class NamingResources extends LifecycleMBeanBase implements Serializable { private static final long serialVersionUID = 1L; private static final Log log = LogFactory.getLog(NamingResources.class); private static final StringManager sm = StringManager.getManager(Constants.Package); private volatile boolean resourceRequireExplicitRegistration = false; // ----------------------------------------------------------- Constructors /** * Create a new NamingResources instance. */ public NamingResources() { // NOOP } // ----------------------------------------------------- Instance Variables /** * Associated container object. */ private Object container = null; /** * Set of naming entries, keyed by name. */ private final Set<String> entries = new HashSet<>(); /** * The EJB resource references for this web application, keyed by name. */ private final HashMap<String, ContextEjb> ejbs = new HashMap<>(); /** * The environment entries for this web application, keyed by name. */ private final HashMap<String, ContextEnvironment> envs = new HashMap<>(); /** * The local EJB resource references for this web application, keyed by * name. */ private final HashMap<String, ContextLocalEjb> localEjbs = new HashMap<>(); /** * The message destination referencess for this web application, * keyed by name. */ private final HashMap<String, MessageDestinationRef> mdrs = new HashMap<>(); /** * The resource environment references for this web application, * keyed by name. */ private final HashMap<String, ContextResourceEnvRef> resourceEnvRefs = new HashMap<>(); /** * The resource references for this web application, keyed by name. */ private final HashMap<String, ContextResource> resources = new HashMap<>(); /** * The resource links for this web application, keyed by name. */ private final HashMap<String, ContextResourceLink> resourceLinks = new HashMap<>(); /** * The web service references for this web application, keyed by name. */ private final HashMap<String, ContextService> services = new HashMap<>(); /** * The transaction for this webapp. */ private ContextTransaction transaction = null; /** * The property change support for this component. */ protected final PropertyChangeSupport support = new PropertyChangeSupport(this); // ------------------------------------------------------------- Properties /** * Get the container with which the naming resources are associated. */ public Object getContainer() { return container; } /** * Set the container with which the naming resources are associated. */ public void setContainer(Object container) { this.container = container; } /** * Set the transaction object. */ public void setTransaction(ContextTransaction transaction) { this.transaction = transaction; } /** * Get the transaction object. */ public ContextTransaction getTransaction() { return transaction; } /** * Add an EJB resource reference for this web application. * * @param ejb New EJB resource reference */ public void addEjb(ContextEjb ejb) { if (entries.contains(ejb.getName())) { return; } else { entries.add(ejb.getName()); } synchronized (ejbs) { ejb.setNamingResources(this); ejbs.put(ejb.getName(), ejb); } support.firePropertyChange("ejb", null, ejb); } /** * Add an environment entry for this web application. * * @param environment New environment entry */ public void addEnvironment(ContextEnvironment environment) { if (entries.contains(environment.getName())) { ContextEnvironment ce = findEnvironment(environment.getName()); ContextResourceLink rl = findResourceLink(environment.getName()); if (ce != null) { if (ce.getOverride()) { removeEnvironment(environment.getName()); } else { return; } } else if (rl != null) { // Link. Need to look at the global resources NamingResources global = getServer().getGlobalNamingResources(); if (global.findEnvironment(rl.getGlobal()) != null) { if (global.findEnvironment(rl.getGlobal()).getOverride()) { removeResourceLink(environment.getName()); } else { return; } } } else { // It exists but it isn't an env or a res link... return; } } if (!checkResourceType(environment)) { throw new IllegalArgumentException(sm.getString( "namingResources.resourceTypeFail", environment.getName(), environment.getType())); } entries.add(environment.getName()); synchronized (envs) { environment.setNamingResources(this); envs.put(environment.getName(), environment); } support.firePropertyChange("environment", null, environment); // Register with JMX if (resourceRequireExplicitRegistration) { try { MBeanUtils.createMBean(environment); } catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", environment.getName()), e); } } } // Container should be an instance of Server or Context. If it is anything // else, return null which will trigger a NPE. private Server getServer() { if (container instanceof Server) { return (Server) container; } if (container instanceof Context) { // Could do this in one go. Lots of casts so split out for clarity Engine engine = (Engine) ((Context) container).getParent().getParent(); return engine.getService().getServer(); } return null; } /** * Add a local EJB resource reference for this web application. * * @param ejb New EJB resource reference */ public void addLocalEjb(ContextLocalEjb ejb) { if (entries.contains(ejb.getName())) { return; } else { entries.add(ejb.getName()); } synchronized (localEjbs) { ejb.setNamingResources(this); localEjbs.put(ejb.getName(), ejb); } support.firePropertyChange("localEjb", null, ejb); } /** * Add a message destination reference for this web application. * * @param mdr New message destination reference */ public void addMessageDestinationRef(MessageDestinationRef mdr) { if (entries.contains(mdr.getName())) { return; } else { if (!checkResourceType(mdr)) { throw new IllegalArgumentException(sm.getString( "namingResources.resourceTypeFail", mdr.getName(), mdr.getType())); } entries.add(mdr.getName()); } synchronized (mdrs) { mdr.setNamingResources(this); mdrs.put(mdr.getName(), mdr); } support.firePropertyChange("messageDestinationRef", null, mdr); } /** * Add a property change listener to this component. * * @param listener The listener to add */ public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } /** * Add a resource reference for this web application. * * @param resource New resource reference */ public void addResource(ContextResource resource) { if (entries.contains(resource.getName())) { return; } else { if (!checkResourceType(resource)) { throw new IllegalArgumentException(sm.getString( "namingResources.resourceTypeFail", resource.getName(), resource.getType())); } entries.add(resource.getName()); } synchronized (resources) { resource.setNamingResources(this); resources.put(resource.getName(), resource); } support.firePropertyChange("resource", null, resource); // Register with JMX if (resourceRequireExplicitRegistration) { try { MBeanUtils.createMBean(resource); } catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resource.getName()), e); } } } /** * Add a resource environment reference for this web application. * * @param resource The resource */ public void addResourceEnvRef(ContextResourceEnvRef resource) { if (entries.contains(resource.getName())) { return; } else { if (!checkResourceType(resource)) { throw new IllegalArgumentException(sm.getString( "namingResources.resourceTypeFail", resource.getName(), resource.getType())); } entries.add(resource.getName()); } synchronized (resourceEnvRefs) { resource.setNamingResources(this); resourceEnvRefs.put(resource.getName(), resource); } support.firePropertyChange("resourceEnvRef", null, resource); } /** * Add a resource link for this web application. * * @param resourceLink New resource link */ public void addResourceLink(ContextResourceLink resourceLink) { if (entries.contains(resourceLink.getName())) { return; } else { entries.add(resourceLink.getName()); } synchronized (resourceLinks) { resourceLink.setNamingResources(this); resourceLinks.put(resourceLink.getName(), resourceLink); } support.firePropertyChange("resourceLink", null, resourceLink); // Register with JMX if (resourceRequireExplicitRegistration) { try { MBeanUtils.createMBean(resourceLink); } catch (Exception e) { log.warn(sm.getString("namingResources.mbeanCreateFail", resourceLink.getName()), e); } } } /** * Add a web service reference for this web application. * * @param service New web service reference */ public void addService(ContextService service) { if (entries.contains(service.getName())) { return; } else { entries.add(service.getName()); } synchronized (services) { service.setNamingResources(this); services.put(service.getName(), service); } support.firePropertyChange("service", null, service); } /** * Return the EJB resource reference with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired EJB resource reference */ public ContextEjb findEjb(String name) { synchronized (ejbs) { return ejbs.get(name); } } /** * Return the defined EJB resource references for this application. * If there are none, a zero-length array is returned. */ public ContextEjb[] findEjbs() { synchronized (ejbs) { ContextEjb results[] = new ContextEjb[ejbs.size()]; return ejbs.values().toArray(results); } } /** * Return the environment entry with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired environment entry */ public ContextEnvironment findEnvironment(String name) { synchronized (envs) { return envs.get(name); } } /** * Return the set of defined environment entries for this web * application. If none have been defined, a zero-length array * is returned. */ public ContextEnvironment[] findEnvironments() { synchronized (envs) { ContextEnvironment results[] = new ContextEnvironment[envs.size()]; return envs.values().toArray(results); } } /** * Return the local EJB resource reference with the specified name, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired EJB resource reference */ public ContextLocalEjb findLocalEjb(String name) { synchronized (localEjbs) { return localEjbs.get(name); } } /** * Return the defined local EJB resource references for this application. * If there are none, a zero-length array is returned. */ public ContextLocalEjb[] findLocalEjbs() { synchronized (localEjbs) { ContextLocalEjb results[] = new ContextLocalEjb[localEjbs.size()]; return localEjbs.values().toArray(results); } } /** * Return the message destination reference with the specified name, * if any; otherwise, return <code>null</code>. * * @param name Name of the desired message destination reference */ public MessageDestinationRef findMessageDestinationRef(String name) { synchronized (mdrs) { return mdrs.get(name); } } /** * Return the defined message destination references for this application. * If there are none, a zero-length array is returned. */ public MessageDestinationRef[] findMessageDestinationRefs() { synchronized (mdrs) { MessageDestinationRef results[] = new MessageDestinationRef[mdrs.size()]; return mdrs.values().toArray(results); } } /** * Return the resource reference with the specified name, if any; * otherwise return <code>null</code>. * * @param name Name of the desired resource reference */ public ContextResource findResource(String name) { synchronized (resources) { return resources.get(name); } } /** * Return the resource link with the specified name, if any; * otherwise return <code>null</code>. * * @param name Name of the desired resource link */ public ContextResourceLink findResourceLink(String name) { synchronized (resourceLinks) { return resourceLinks.get(name); } } /** * Return the defined resource links for this application. If * none have been defined, a zero-length array is returned. */ public ContextResourceLink[] findResourceLinks() { synchronized (resourceLinks) { ContextResourceLink results[] = new ContextResourceLink[resourceLinks.size()]; return resourceLinks.values().toArray(results); } } /** * Return the defined resource references for this application. If * none have been defined, a zero-length array is returned. */ public ContextResource[] findResources() { synchronized (resources) { ContextResource results[] = new ContextResource[resources.size()]; return resources.values().toArray(results); } } /** * Return the resource environment reference type for the specified * name, if any; otherwise return <code>null</code>. * * @param name Name of the desired resource environment reference */ public ContextResourceEnvRef findResourceEnvRef(String name) { synchronized (resourceEnvRefs) { return resourceEnvRefs.get(name); } } /** * Return the set of resource environment reference names for this * web application. If none have been specified, a zero-length * array is returned. */ public ContextResourceEnvRef[] findResourceEnvRefs() { synchronized (resourceEnvRefs) { ContextResourceEnvRef results[] = new ContextResourceEnvRef[resourceEnvRefs.size()]; return resourceEnvRefs.values().toArray(results); } } /** * Return the web service reference for the specified * name, if any; otherwise return <code>null</code>. * * @param name Name of the desired web service */ public ContextService findService(String name) { synchronized (services) { return services.get(name); } } /** * Return the defined web service references for this application. If * none have been defined, a zero-length array is returned. */ public ContextService[] findServices() { synchronized (services) { ContextService results[] = new ContextService[services.size()]; return services.values().toArray(results); } } /** * Remove any EJB resource reference with the specified name. * * @param name Name of the EJB resource reference to remove */ public void removeEjb(String name) { entries.remove(name); ContextEjb ejb = null; synchronized (ejbs) { ejb = ejbs.remove(name); } if (ejb != null) { support.firePropertyChange("ejb", ejb, null); ejb.setNamingResources(null); } } /** * Remove any environment entry with the specified name. * * @param name Name of the environment entry to remove */ public void removeEnvironment(String name) { entries.remove(name); ContextEnvironment environment = null; synchronized (envs) { environment = envs.remove(name); } if (environment != null) { support.firePropertyChange("environment", environment, null); // De-register with JMX if (resourceRequireExplicitRegistration) { try { MBeanUtils.destroyMBean(environment); } catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", environment.getName()), e); } } environment.setNamingResources(null); } } /** * Remove any local EJB resource reference with the specified name. * * @param name Name of the EJB resource reference to remove */ public void removeLocalEjb(String name) { entries.remove(name); ContextLocalEjb localEjb = null; synchronized (localEjbs) { localEjb = localEjbs.remove(name); } if (localEjb != null) { support.firePropertyChange("localEjb", localEjb, null); localEjb.setNamingResources(null); } } /** * Remove any message destination reference with the specified name. * * @param name Name of the message destination resource reference to remove */ public void removeMessageDestinationRef(String name) { entries.remove(name); MessageDestinationRef mdr = null; synchronized (mdrs) { mdr = mdrs.remove(name); } if (mdr != null) { support.firePropertyChange("messageDestinationRef", mdr, null); mdr.setNamingResources(null); } } /** * Remove a property change listener from this component. * * @param listener The listener to remove */ public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } /** * Remove any resource reference with the specified name. * * @param name Name of the resource reference to remove */ public void removeResource(String name) { entries.remove(name); ContextResource resource = null; synchronized (resources) { resource = resources.remove(name); } if (resource != null) { support.firePropertyChange("resource", resource, null); // De-register with JMX if (resourceRequireExplicitRegistration) { try { MBeanUtils.destroyMBean(resource); } catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e); } } resource.setNamingResources(null); } } /** * Remove any resource environment reference with the specified name. * * @param name Name of the resource environment reference to remove */ public void removeResourceEnvRef(String name) { entries.remove(name); ContextResourceEnvRef resourceEnvRef = null; synchronized (resourceEnvRefs) { resourceEnvRef = resourceEnvRefs.remove(name); } if (resourceEnvRef != null) { support.firePropertyChange("resourceEnvRef", resourceEnvRef, null); resourceEnvRef.setNamingResources(null); } } /** * Remove any resource link with the specified name. * * @param name Name of the resource link to remove */ public void removeResourceLink(String name) { entries.remove(name); ContextResourceLink resourceLink = null; synchronized (resourceLinks) { resourceLink = resourceLinks.remove(name); } if (resourceLink != null) { support.firePropertyChange("resourceLink", resourceLink, null); // De-register with JMX if (resourceRequireExplicitRegistration) { try { MBeanUtils.destroyMBean(resourceLink); } catch (Exception e) { log.warn(sm.getString("namingResources.mbeanDestroyFail", resourceLink.getName()), e); } } resourceLink.setNamingResources(null); } } /** * Remove any web service reference with the specified name. * * @param name Name of the web service reference to remove */ public void removeService(String name) { entries.remove(name); ContextService service = null; synchronized (services) { service = services.remove(name); } if (service != null) { support.firePropertyChange("service", service, null); service.setNamingResources(null); } } // ------------------------------------------------------- Lifecycle methods @Override protected void initInternal() throws LifecycleException { super.initInternal(); // Set this before we register currently known naming resources to avoid // timing issues. Duplication registration is not an issue. resourceRequireExplicitRegistration = true; for (ContextResource cr : resources.values()) { try { MBeanUtils.createMBean(cr); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", cr.getName()), e); } } for (ContextEnvironment ce : envs.values()) { try { MBeanUtils.createMBean(ce); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", ce.getName()), e); } } for (ContextResourceLink crl : resourceLinks.values()) { try { MBeanUtils.createMBean(crl); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanCreateFail", crl.getName()), e); } } } @Override protected void startInternal() throws LifecycleException { fireLifecycleEvent(CONFIGURE_START_EVENT, null); setState(LifecycleState.STARTING); } @Override protected void stopInternal() throws LifecycleException { cleanUp(); setState(LifecycleState.STOPPING); fireLifecycleEvent(CONFIGURE_STOP_EVENT, null); } /** * Close those resources that an explicit close may help clean-up faster. */ private void cleanUp() { if (resources.size() == 0) { return; } javax.naming.Context ctxt; try { if (container instanceof Server) { ctxt = ((Server) container).getGlobalNamingContext(); } else { ctxt = ContextBindings.getClassLoader(); ctxt = (javax.naming.Context) ctxt.lookup("comp/env"); } } catch (NamingException e) { log.warn(sm.getString("namingResources.cleanupNoContext", container), e); return; } for (ContextResource cr: resources.values()) { if (cr.getSingleton()) { String closeMethod = cr.getCloseMethod(); if (closeMethod != null && closeMethod.length() > 0) { String name = cr.getName(); Object resource; try { resource = ctxt.lookup(name); } catch (NamingException e) { log.warn(sm.getString( "namingResources.cleanupNoResource", cr.getName(), container), e); continue; } cleanUp(resource, name, closeMethod); } } } } /** * Clean up a resource by calling the defined close method. For example, * closing a database connection pool will close it's open connections. This * will happen on GC but that leaves db connections open that may cause * issues. * * @param resource The resource to close. */ private void cleanUp(Object resource, String name, String closeMethod) { // Look for a zero-arg close() method Method m = null; try { m = resource.getClass().getMethod(closeMethod, (Class<?>[]) null); } catch (SecurityException e) { log.debug(sm.getString("namingResources.cleanupCloseSecurity", closeMethod, name, container)); return; } catch (NoSuchMethodException e) { log.debug(sm.getString("namingResources.cleanupNoClose", name, container, closeMethod)); return; } if (m != null) { try { m.invoke(resource, (Object[]) null); } catch (IllegalArgumentException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); } catch (IllegalAccessException e) { log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), e); } catch (InvocationTargetException e) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString("namingResources.cleanupCloseFailed", closeMethod, name, container), t); } } } @Override protected void destroyInternal() throws LifecycleException { // Set this before we de-register currently known naming resources to // avoid timing issues. Duplication de-registration is not an issue. resourceRequireExplicitRegistration = false; // Destroy in reverse order to create, although it should not matter for (ContextResourceLink crl : resourceLinks.values()) { try { MBeanUtils.destroyMBean(crl); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", crl.getName()), e); } } for (ContextEnvironment ce : envs.values()) { try { MBeanUtils.destroyMBean(ce); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", ce.getName()), e); } } for (ContextResource cr : resources.values()) { try { MBeanUtils.destroyMBean(cr); } catch (Exception e) { log.warn(sm.getString( "namingResources.mbeanDestroyFail", cr.getName()), e); } } super.destroyInternal(); } @Override protected String getDomainInternal() { // Use the same domain as our associated container if we have one Object c = getContainer(); if (c instanceof JmxEnabled) { return ((JmxEnabled) c).getDomain(); } return null; } @Override protected String getObjectNameKeyProperties() { Object c = getContainer(); if (c instanceof Container) { return "type=NamingResources" + ((Container) c).getMBeanKeyProperties(); } // Server or just unknown return "type=NamingResources"; } /** * Checks that the configuration of the type for the specified resource is * consistent with any injection targets and if the type is not specified, * tries to configure the type based on the injection targets * * @param resource The resource to check * * @return <code>true</code> if the type for the resource is now valid (if * previously <code>null</code> this means it is now set) or * <code>false</code> if the current resource type is inconsistent * with the injection targets and/or cannot be determined */ private boolean checkResourceType(ResourceBase resource) { if (!(container instanceof Context)) { // Only Context's will have injection targets return true; } if (resource.getInjectionTargets() == null || resource.getInjectionTargets().size() == 0) { // No injection targets so use the defined type for the resource return true; } Context context = (Context) container; String typeName = resource.getType(); Class<?> typeClass = null; if (typeName != null) { typeClass = Introspection.loadClass(context, typeName); if (typeClass == null) { // Can't load the type - will trigger a failure later so don't // fail here return true; } } Class<?> compatibleClass = getCompatibleType(context, resource, typeClass); if (compatibleClass == null) { // Indicates that a compatible type could not be identified that // worked for all injection targets return false; } resource.setType(compatibleClass.getCanonicalName()); return true; } private Class<?> getCompatibleType(Context context, ResourceBase resource, Class<?> typeClass) { Class<?> result = null; for (InjectionTarget injectionTarget : resource.getInjectionTargets()) { Class<?> clazz = Introspection.loadClass( context, injectionTarget.getTargetClass()); if (clazz == null) { // Can't load class - therefore ignore this target continue; } // Look for a match String targetName = injectionTarget.getTargetName(); // Look for a setter match first Class<?> targetType = getSetterType(clazz, targetName); if (targetType == null) { // Try a field match if no setter match targetType = getFieldType(clazz,targetName); } if (targetType == null) { // No match - ignore this injection target continue; } targetType = convertPrimitiveType(targetType); if (typeClass == null) { // Need to find a common type amongst the injection targets if (result == null) { result = targetType; } else if (targetType.isAssignableFrom(result)) { // NO-OP - This will work } else if (result.isAssignableFrom(targetType)) { // Need to use more specific type result = targetType; } else { // Incompatible types return null; } } else { // Each injection target needs to be consistent with the defined // type if (targetType.isAssignableFrom(typeClass)) { result = typeClass; } else { // Incompatible types return null; } } } return result; } private Class<?> getSetterType(Class<?> clazz, String name) { Method[] methods = Introspection.getDeclaredMethods(clazz); if (methods != null && methods.length > 0) { for (Method method : methods) { if (Introspection.isValidSetter(method) && Introspection.getPropertyName(method).equals(name)) { return method.getParameterTypes()[0]; } } } return null; } private Class<?> getFieldType(Class<?> clazz, String name) { Field[] fields = Introspection.getDeclaredFields(clazz); if (fields != null && fields.length > 0) { for (Field field : fields) { if (field.getName().equals(name)) { return field.getType(); } } } return null; } private Class<?> convertPrimitiveType(Class<?> clazz) { if (clazz.equals(char.class)) { return Character.class; } else if (clazz.equals(int.class)) { return Integer.class; } else if (clazz.equals(boolean.class)) { return Boolean.class; } else if (clazz.equals(double.class)) { return Double.class; } else if (clazz.equals(byte.class)) { return Byte.class; } else if (clazz.equals(short.class)) { return Short.class; } else if (clazz.equals(long.class)) { return Long.class; } else if (clazz.equals(float.class)) { return Float.class; } else { return clazz; } } }
54,448
Bug 54448 Field of primitive type, annotated with @Resource is not recognized as env entry
Hi, I have a servlet with one field of primitive type. The field is annotated with @Resource. public class MyServlet extends HttpServlet { @Resource(mappedName = "1") private int envEntry; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ... } } When I request this servlet I receive the following exception: SEVERE: Allocate exception for servlet MyServlet javax.naming.NamingException: Cannot create resource instance at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:117) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at org.apache.naming.NamingContext.lookup(NamingContext.java:843) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:581) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:470) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) That's because in the method below the primitive types are not 'converted' to their corresponding wrappers and this field is interpreted not as env entry but as resource env ref. org.apache.catalina.startup.WebAnnotationSet.addResource(Context, Resource, String, String) I'm attaching a patch that solves this issue and a test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
74f5b3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:09:03Z
2013-01-18T03:33:20Z
java/org/apache/catalina/startup/WebAnnotationSet.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.lang.reflect.Field; import java.lang.reflect.Method; import javax.annotation.Resource; import javax.annotation.Resources; import javax.annotation.security.DeclareRoles; import javax.annotation.security.RunAs; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Wrapper; import org.apache.catalina.deploy.ContextEnvironment; import org.apache.catalina.deploy.ContextResource; import org.apache.catalina.deploy.ContextResourceEnvRef; import org.apache.catalina.deploy.ContextService; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.deploy.MessageDestinationRef; import org.apache.catalina.util.Introspection; import org.apache.tomcat.util.res.StringManager; /** * <p><strong>AnnotationSet</strong> for processing the annotations of the web application * classes (<code>/WEB-INF/classes</code> and <code>/WEB-INF/lib</code>).</p> * * @author Fabien Carrion * @version $Id$ */ public class WebAnnotationSet { private static final String SEPARATOR = "/"; /** * The string resources for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); // --------------------------------------------------------- Public Methods /** * Process the annotations on a context. */ public static void loadApplicationAnnotations(Context context) { loadApplicationListenerAnnotations(context); loadApplicationFilterAnnotations(context); loadApplicationServletAnnotations(context); } // -------------------------------------------------------- protected Methods /** * Process the annotations for the listeners. */ protected static void loadApplicationListenerAnnotations(Context context) { Class<?> classClass = null; String[] applicationListeners = context.findApplicationListeners(); for (int i = 0; i < applicationListeners.length; i++) { classClass = Introspection.loadClass(context, applicationListeners[i]); if (classClass == null) { continue; } loadClassAnnotation(context, classClass); loadFieldsAnnotation(context, classClass); loadMethodsAnnotation(context, classClass); } } /** * Process the annotations for the filters. */ protected static void loadApplicationFilterAnnotations(Context context) { Class<?> classClass = null; FilterDef[] filterDefs = context.findFilterDefs(); for (int i = 0; i < filterDefs.length; i++) { classClass = Introspection.loadClass(context, (filterDefs[i]).getFilterClass()); if (classClass == null) { continue; } loadClassAnnotation(context, classClass); loadFieldsAnnotation(context, classClass); loadMethodsAnnotation(context, classClass); } } /** * Process the annotations for the servlets. */ protected static void loadApplicationServletAnnotations(Context context) { Wrapper wrapper = null; Class<?> classClass = null; Container[] children = context.findChildren(); for (int i = 0; i < children.length; i++) { if (children[i] instanceof Wrapper) { wrapper = (Wrapper) children[i]; if (wrapper.getServletClass() == null) { continue; } classClass = Introspection.loadClass(context, wrapper.getServletClass()); if (classClass == null) { continue; } loadClassAnnotation(context, classClass); loadFieldsAnnotation(context, classClass); loadMethodsAnnotation(context, classClass); /* Process RunAs annotation which can be only on servlets. * Ref JSR 250, equivalent to the run-as element in * the deployment descriptor */ if (classClass.isAnnotationPresent(RunAs.class)) { RunAs annotation = classClass.getAnnotation(RunAs.class); wrapper.setRunAs(annotation.value()); } } } } /** * Process the annotations on a context for a given className. */ protected static void loadClassAnnotation(Context context, Class<?> classClass) { // Initialize the annotations if (classClass.isAnnotationPresent(Resource.class)) { Resource annotation = classClass.getAnnotation(Resource.class); addResource(context, annotation); } /* Process Resources annotation. * Ref JSR 250 */ if (classClass.isAnnotationPresent(Resources.class)) { Resources annotation = classClass.getAnnotation(Resources.class); for (int i = 0; annotation.value() != null && i < annotation.value().length; i++) { addResource(context, annotation.value()[i]); } } /* Process EJB annotation. * Ref JSR 224, equivalent to the ejb-ref or ejb-local-ref * element in the deployment descriptor. if (classClass.isAnnotationPresent(EJB.class)) { EJB annotation = (EJB) classClass.getAnnotation(EJB.class); if ((annotation.mappedName().length() == 0) || annotation.mappedName().equals("Local")) { ContextLocalEjb ejb = new ContextLocalEjb(); ejb.setName(annotation.name()); ejb.setType(annotation.beanInterface().getCanonicalName()); ejb.setDescription(annotation.description()); ejb.setHome(annotation.beanName()); context.getNamingResources().addLocalEjb(ejb); } else if (annotation.mappedName().equals("Remote")) { ContextEjb ejb = new ContextEjb(); ejb.setName(annotation.name()); ejb.setType(annotation.beanInterface().getCanonicalName()); ejb.setDescription(annotation.description()); ejb.setHome(annotation.beanName()); context.getNamingResources().addEjb(ejb); } } */ /* Process WebServiceRef annotation. * Ref JSR 224, equivalent to the service-ref element in * the deployment descriptor. * The service-ref registration is not implemented if (classClass.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = (WebServiceRef) classClass.getAnnotation(WebServiceRef.class); ContextService service = new ContextService(); service.setName(annotation.name()); service.setWsdlfile(annotation.wsdlLocation()); service.setType(annotation.type().getCanonicalName()); if (annotation.value() == null) service.setServiceinterface(annotation.type().getCanonicalName()); if (annotation.type().getCanonicalName().equals("Service")) service.setServiceinterface(annotation.type().getCanonicalName()); if (annotation.value().getCanonicalName().equals("Endpoint")) service.setServiceendpoint(annotation.type().getCanonicalName()); service.setPortlink(annotation.type().getCanonicalName()); context.getNamingResources().addService(service); } */ /* Process DeclareRoles annotation. * Ref JSR 250, equivalent to the security-role element in * the deployment descriptor */ if (classClass.isAnnotationPresent(DeclareRoles.class)) { DeclareRoles annotation = classClass.getAnnotation(DeclareRoles.class); for (int i = 0; annotation.value() != null && i < annotation.value().length; i++) { context.addSecurityRole(annotation.value()[i]); } } } protected static void loadFieldsAnnotation(Context context, Class<?> classClass) { // Initialize the annotations Field[] fields = Introspection.getDeclaredFields(classClass); if (fields != null && fields.length > 0) { for (Field field : fields) { if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); String defaultName = classClass.getName() + SEPARATOR + field.getName(); String defaultType = field.getType().getCanonicalName(); addResource(context, annotation, defaultName, defaultType); } } } } protected static void loadMethodsAnnotation(Context context, Class<?> classClass) { // Initialize the annotations Method[] methods = Introspection.getDeclaredMethods(classClass); if (methods != null && methods.length > 0) { for (Method method : methods) { if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); if (!Introspection.isValidSetter(method)) { throw new IllegalArgumentException(sm.getString( "webAnnotationSet.invalidInjection")); } String defaultName = classClass.getName() + SEPARATOR + Introspection.getPropertyName(method); String defaultType = (method.getParameterTypes()[0]).getCanonicalName(); addResource(context, annotation, defaultName, defaultType); } } } } /** * Process a Resource annotation to set up a Resource. * Ref JSR 250, equivalent to the resource-ref, * message-destination-ref, env-ref, resource-env-ref * or service-ref element in the deployment descriptor. */ protected static void addResource(Context context, Resource annotation) { addResource(context, annotation, null, null); } protected static void addResource(Context context, Resource annotation, String defaultName, String defaultType) { String name = getName(annotation, defaultName); String type = getType(annotation, defaultType); if (type.equals("java.lang.String") || type.equals("java.lang.Character") || type.equals("java.lang.Integer") || type.equals("java.lang.Boolean") || type.equals("java.lang.Double") || type.equals("java.lang.Byte") || type.equals("java.lang.Short") || type.equals("java.lang.Long") || type.equals("java.lang.Float")) { // env-ref element ContextEnvironment resource = new ContextEnvironment(); resource.setName(name); resource.setType(type); resource.setDescription(annotation.description()); resource.setValue(annotation.mappedName()); context.getNamingResources().addEnvironment(resource); } else if (type.equals("javax.xml.rpc.Service")) { // service-ref element ContextService service = new ContextService(); service.setName(name); service.setWsdlfile(annotation.mappedName()); service.setType(type); service.setDescription(annotation.description()); context.getNamingResources().addService(service); } else if (type.equals("javax.sql.DataSource") || type.equals("javax.jms.ConnectionFactory") || type.equals("javax.jms.QueueConnectionFactory") || type.equals("javax.jms.TopicConnectionFactory") || type.equals("javax.mail.Session") || type.equals("java.net.URL") || type.equals("javax.resource.cci.ConnectionFactory") || type.equals("org.omg.CORBA_2_3.ORB") || type.endsWith("ConnectionFactory")) { // resource-ref element ContextResource resource = new ContextResource(); resource.setName(name); resource.setType(type); if (annotation.authenticationType() == Resource.AuthenticationType.CONTAINER) { resource.setAuth("Container"); } else if (annotation.authenticationType() == Resource.AuthenticationType.APPLICATION) { resource.setAuth("Application"); } resource.setScope(annotation.shareable() ? "Shareable" : "Unshareable"); resource.setProperty("mappedName", annotation.mappedName()); resource.setDescription(annotation.description()); context.getNamingResources().addResource(resource); } else if (type.equals("javax.jms.Queue") || type.equals("javax.jms.Topic")) { // message-destination-ref MessageDestinationRef resource = new MessageDestinationRef(); resource.setName(name); resource.setType(type); resource.setUsage(annotation.mappedName()); resource.setDescription(annotation.description()); context.getNamingResources().addMessageDestinationRef(resource); } else if (type.equals("javax.resource.cci.InteractionSpec") || type.equals("javax.transaction.UserTransaction") || true) { // resource-env-ref ContextResourceEnvRef resource = new ContextResourceEnvRef(); resource.setName(name); resource.setType(type); resource.setProperty("mappedName", annotation.mappedName()); resource.setDescription(annotation.description()); context.getNamingResources().addResourceEnvRef(resource); } } private static String getType(Resource annotation, String defaultType) { String type = annotation.type().getCanonicalName(); if (type == null || type.equals("java.lang.Object")) { if (defaultType != null) { type = defaultType; } } return type; } private static String getName(Resource annotation, String defaultName) { String name = annotation.name(); if (name == null || name.equals("")) { if (defaultName != null) { name = defaultName; } } return name; } }
54,448
Bug 54448 Field of primitive type, annotated with @Resource is not recognized as env entry
Hi, I have a servlet with one field of primitive type. The field is annotated with @Resource. public class MyServlet extends HttpServlet { @Resource(mappedName = "1") private int envEntry; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ... } } When I request this servlet I receive the following exception: SEVERE: Allocate exception for servlet MyServlet javax.naming.NamingException: Cannot create resource instance at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:117) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at org.apache.naming.NamingContext.lookup(NamingContext.java:843) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:581) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:470) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) That's because in the method below the primitive types are not 'converted' to their corresponding wrappers and this field is interpreted not as env entry but as resource env ref. org.apache.catalina.startup.WebAnnotationSet.addResource(Context, Resource, String, String) I'm attaching a patch that solves this issue and a test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
74f5b3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:09:03Z
2013-01-18T03:33:20Z
java/org/apache/catalina/util/Introspection.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.util; import java.beans.Introspector; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.security.AccessController; import java.security.PrivilegedAction; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.juli.logging.Log; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * Provides introspection utilities that either require knowledge of Tomcat * internals or are solely used by Tomcat internals. */ public class Introspection { private static final StringManager sm = StringManager.getManager("org.apache.catalina.util"); /** * Extract the Java Bean property name from the setter name. * * Note: This method assumes that the method name has already been checked * for correctness. */ public static String getPropertyName(Method setter) { return Introspector.decapitalize(setter.getName().substring(3)); } /** * Determines if a method has a valid name and signature for a Java Bean * setter. * * @param method The method to test * * @return <code>true</code> if the method does have a valid name and * signature, else <code>false</code> */ public static boolean isValidSetter(Method method) { if (method.getName().startsWith("set") && method.getName().length() > 3 && method.getParameterTypes().length == 1 && method.getReturnType().getName().equals("void")) { return true; } return false; } /** * Determines if a method is a valid lifecycle callback method. * * @param method * The method to test * * @return <code>true</code> if the method is a valid lifecycle callback * method, else <code>false</code> */ public static boolean isValidLifecycleCallback(Method method) { if (method.getParameterTypes().length != 0 || Modifier.isStatic(method.getModifiers()) || method.getExceptionTypes().length > 0 || !method.getReturnType().getName().equals("void")) { return false; } return true; } /** * Obtain the declared fields for a class taking account of any security * manager that may be configured. */ public static Field[] getDeclaredFields(final Class<?> clazz) { Field[] fields = null; if (Globals.IS_SECURITY_ENABLED) { fields = AccessController.doPrivileged( new PrivilegedAction<Field[]>(){ @Override public Field[] run(){ return clazz.getDeclaredFields(); } }); } else { fields = clazz.getDeclaredFields(); } return fields; } /** * Obtain the declared methods for a class taking account of any security * manager that may be configured. */ public static Method[] getDeclaredMethods(final Class<?> clazz) { Method[] methods = null; if (Globals.IS_SECURITY_ENABLED) { methods = AccessController.doPrivileged( new PrivilegedAction<Method[]>(){ @Override public Method[] run(){ return clazz.getDeclaredMethods(); } }); } else { methods = clazz.getDeclaredMethods(); } return methods; } /** * Attempt to load a class using the given Container's class loader. If the * class cannot be loaded, a debug level log message will be written to the * Container's log and null will be returned. */ public static Class<?> loadClass(Context context, String className) { ClassLoader cl = context.getLoader().getClassLoader(); Log log = context.getLogger(); Class<?> clazz = null; try { clazz = cl.loadClass(className); } catch (ClassNotFoundException e) { log.debug(sm.getString("introspection.classLoadFailed"), e); } catch (NoClassDefFoundError e) { log.debug(sm.getString("introspection.classLoadFailed"), e); } catch (ClassFormatError e) { log.debug(sm.getString("introspection.classLoadFailed"), e); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.debug(sm.getString("introspection.classLoadFailed"), t); } return clazz; } }
54,448
Bug 54448 Field of primitive type, annotated with @Resource is not recognized as env entry
Hi, I have a servlet with one field of primitive type. The field is annotated with @Resource. public class MyServlet extends HttpServlet { @Resource(mappedName = "1") private int envEntry; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ... } } When I request this servlet I receive the following exception: SEVERE: Allocate exception for servlet MyServlet javax.naming.NamingException: Cannot create resource instance at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:117) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at org.apache.naming.NamingContext.lookup(NamingContext.java:843) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:581) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:470) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) That's because in the method below the primitive types are not 'converted' to their corresponding wrappers and this field is interpreted not as env entry but as resource env ref. org.apache.catalina.startup.WebAnnotationSet.addResource(Context, Resource, String, String) I'm attaching a patch that solves this issue and a test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
74f5b3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:09:03Z
2013-01-18T03:33:20Z
test/org/apache/catalina/startup/TestContextConfig.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.IOException; import java.util.Set; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; 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.core.StandardContext; import org.apache.tomcat.util.buf.ByteChunk; public class TestContextConfig extends TomcatBaseTest { @Test public void testOverrideWithSCIDefaultName() throws Exception { doTestOverrideDefaultServletWithSCI("default"); } @Test public void testOverrideWithSCIDefaultMapping() throws Exception { doTestOverrideDefaultServletWithSCI("anything"); } private void doTestOverrideDefaultServletWithSCI(String servletName) throws Exception{ Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0"); StandardContext ctxt = (StandardContext) tomcat.addContext(null, "/test", appDir.getAbsolutePath()); ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath()); ctxt.addLifecycleListener(new ContextConfig()); ctxt.addServletContainerInitializer( new CustomDefaultServletSCI(servletName), null); tomcat.start(); assertPageContains("/test", "OK - Custom default Servlet"); } @Test public void testBug51396() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments"); // app dir is relative to server home tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); assertPageContains("/test/bug51396.jsp", "<p>OK</p>"); } @Test public void testBug53574() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0"); tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); assertPageContains("/test/bug53574", "OK"); } @Test public void testBug54262() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments-empty-absolute-ordering"); tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); assertPageContains("/test/resourceA.jsp", "resourceA.jsp in resources.jar"); assertPageContains("/test/resources/HelloWorldExample", null, HttpServletResponse.SC_NOT_FOUND); } @Test public void testBug54379() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments"); Context context = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); Tomcat.addServlet(context, "TestServlet", "org.apache.catalina.startup.TesterServletWithLifeCycleMethods"); context.addServletMapping("/testServlet", "TestServlet"); tomcat.enableNaming(); tomcat.start(); assertPageContains("/test/testServlet", "postConstruct1()"); } private static class CustomDefaultServletSCI implements ServletContainerInitializer { private String servletName; public CustomDefaultServletSCI(String servletName) { this.servletName = servletName; } @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { Servlet s = new CustomDefaultServlet(); ServletRegistration.Dynamic r = ctx.addServlet(servletName, s); r.addMapping("/"); } } private static class CustomDefaultServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("OK - Custom default Servlet"); } } private void assertPageContains(String pageUrl, String expectedBody) throws IOException { assertPageContains(pageUrl, expectedBody, HttpServletResponse.SC_OK); } private void assertPageContains(String pageUrl, String expectedBody, int expectedStatus) throws IOException { ByteChunk res = new ByteChunk(); int sc = getUrl("http://localhost:" + getPort() + pageUrl, res, null); Assert.assertEquals(expectedStatus, sc); if (expectedStatus == HttpServletResponse.SC_OK) { String result = res.toString(); Assert.assertTrue(result, result.indexOf(expectedBody) > -1); } } }
54,448
Bug 54448 Field of primitive type, annotated with @Resource is not recognized as env entry
Hi, I have a servlet with one field of primitive type. The field is annotated with @Resource. public class MyServlet extends HttpServlet { @Resource(mappedName = "1") private int envEntry; protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ... } } When I request this servlet I receive the following exception: SEVERE: Allocate exception for servlet MyServlet javax.naming.NamingException: Cannot create resource instance at org.apache.naming.factory.ResourceEnvFactory.getObjectInstance(ResourceEnvFactory.java:117) at javax.naming.spi.NamingManager.getObjectInstance(NamingManager.java:304) at org.apache.naming.NamingContext.lookup(NamingContext.java:843) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupFieldResource(DefaultInstanceManager.java:581) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:470) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) That's because in the method below the primitive types are not 'converted' to their corresponding wrappers and this field is interpreted not as env entry but as resource env ref. org.apache.catalina.startup.WebAnnotationSet.addResource(Context, Resource, String, String) I'm attaching a patch that solves this issue and a test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
74f5b3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:09:03Z
2013-01-18T03:33:20Z
test/org/apache/catalina/startup/TesterServletWithAnnotations.java
54,450
Bug 54450 Injection fails when part of the servlet properties uses @Resource and the other uses 'injection-target'
Hi, I have a servlet with: - annotated properties - and injection-target declarations in web.xml When I try to request this servlet I receive: javax.naming.NameNotFoundException: Name [envEntry1] is not bound in this Context. Unable to find [envEntry1]. at org.apache.naming.NamingContext.lookup(NamingContext.java:820) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupMethodResource(DefaultInstanceManager.java:622) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:466) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) The problem is that when the application uses 'injection-target' declarations in org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(Class<?>, Map<String, String>) only the first setter method is evaluated and the rest are skipped. I would like to propose a patch and test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
ac78456
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:57:27Z
2013-01-18T23:00:00Z
java/org/apache/catalina/core/DefaultInstanceManager.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.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.WeakHashMap; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import javax.annotation.Resource; import javax.ejb.EJB; import javax.naming.Context; import javax.naming.NamingException; import javax.persistence.PersistenceContext; import javax.persistence.PersistenceUnit; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.xml.ws.WebServiceRef; import org.apache.catalina.ContainerServlet; import org.apache.catalina.Globals; import org.apache.catalina.security.SecurityUtil; import org.apache.catalina.util.Introspection; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * @version $Id$ */ public class DefaultInstanceManager implements InstanceManager { // Used when there are no annotations in a class private static final AnnotationCacheEntry[] ANNOTATIONS_EMPTY = new AnnotationCacheEntry[0]; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); private final Context context; private final Map<String, Map<String, String>> injectionMap; protected final ClassLoader classLoader; protected final ClassLoader containerClassLoader; protected final boolean privileged; protected final boolean ignoreAnnotations; private final Properties restrictedFilters = new Properties(); private final Properties restrictedListeners = new Properties(); private final Properties restrictedServlets = new Properties(); private final Map<Class<?>, AnnotationCacheEntry[]> annotationCache = new WeakHashMap<>(); private final Map<String, String> postConstructMethods; private final Map<String, String> preDestroyMethods; public DefaultInstanceManager(Context context, Map<String, Map<String, String>> injectionMap, org.apache.catalina.Context catalinaContext, ClassLoader containerClassLoader) { classLoader = catalinaContext.getLoader().getClassLoader(); privileged = catalinaContext.getPrivileged(); this.containerClassLoader = containerClassLoader; ignoreAnnotations = catalinaContext.getIgnoreAnnotations(); StringManager sm = StringManager.getManager(Constants.Package); try { InputStream is = this.getClass().getClassLoader().getResourceAsStream ("org/apache/catalina/core/RestrictedServlets.properties"); if (is != null) { restrictedServlets.load(is); } else { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource")); } } catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResource"), e); } try { InputStream is = this.getClass().getClassLoader().getResourceAsStream ("org/apache/catalina/core/RestrictedListeners.properties"); if (is != null) { restrictedListeners.load(is); } else { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources")); } } catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedListenersResources"), e); } try { InputStream is = this.getClass().getClassLoader().getResourceAsStream ("org/apache/catalina/core/RestrictedFilters.properties"); if (is != null) { restrictedFilters.load(is); } else { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedFiltersResource")); } } catch (IOException e) { catalinaContext.getLogger().error(sm.getString("defaultInstanceManager.restrictedServletsResources"), e); } this.context = context; this.injectionMap = injectionMap; this.postConstructMethods = catalinaContext.findPostConstructMethods(); this.preDestroyMethods = catalinaContext.findPreDestroyMethods(); } @Override public Object newInstance(String className) throws IllegalAccessException, InvocationTargetException, NamingException, InstantiationException, ClassNotFoundException { Class<?> clazz = loadClassMaybePrivileged(className, classLoader); return newInstance(clazz.newInstance(), clazz); } @Override public Object newInstance(final String className, final ClassLoader classLoader) throws IllegalAccessException, NamingException, InvocationTargetException, InstantiationException, ClassNotFoundException { Class<?> clazz = classLoader.loadClass(className); return newInstance(clazz.newInstance(), clazz); } @Override public void newInstance(Object o) throws IllegalAccessException, InvocationTargetException, NamingException { newInstance(o, o.getClass()); } private Object newInstance(Object instance, Class<?> clazz) throws IllegalAccessException, InvocationTargetException, NamingException { if (!ignoreAnnotations) { Map<String, String> injections = assembleInjectionsFromClassHierarchy(clazz); populateAnnotationsCache(clazz, injections); processAnnotations(instance, injections); postConstruct(instance, clazz); } return instance; } private Map<String, String> assembleInjectionsFromClassHierarchy(Class<?> clazz) { Map<String, String> injections = new HashMap<>(); Map<String, String> currentInjections = null; while (clazz != null) { currentInjections = this.injectionMap.get(clazz.getName()); if (currentInjections != null) { injections.putAll(currentInjections); } clazz = clazz.getSuperclass(); } return injections; } @Override public void destroyInstance(Object instance) throws IllegalAccessException, InvocationTargetException { if (!ignoreAnnotations) { preDestroy(instance, instance.getClass()); } } /** * Call postConstruct method on the specified instance recursively from deepest superclass to actual class. * * @param instance object to call postconstruct methods on * @param clazz (super) class to examine for postConstruct annotation. * @throws IllegalAccessException if postConstruct method is inaccessible. * @throws java.lang.reflect.InvocationTargetException * if call fails */ protected void postConstruct(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { if (context == null) { // No resource injection return; } Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { postConstruct(instance, superClass); } // At the end the postconstruct annotated // method is invoked AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.POST_CONSTRUCT) { Method postConstruct = getMethod(clazz, entry); synchronized (postConstruct) { boolean accessibility = postConstruct.isAccessible(); postConstruct.setAccessible(true); postConstruct.invoke(instance); postConstruct.setAccessible(accessibility); } } } } /** * Call preDestroy method on the specified instance recursively from deepest superclass to actual class. * * @param instance object to call preDestroy methods on * @param clazz (super) class to examine for preDestroy annotation. * @throws IllegalAccessException if preDestroy method is inaccessible. * @throws java.lang.reflect.InvocationTargetException * if call fails */ protected void preDestroy(Object instance, final Class<?> clazz) throws IllegalAccessException, InvocationTargetException { Class<?> superClass = clazz.getSuperclass(); if (superClass != Object.class) { preDestroy(instance, superClass); } // At the end the postconstruct annotated // method is invoked AnnotationCacheEntry[] annotations = null; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } if (annotations == null) { // instance not created through the instance manager return; } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.PRE_DESTROY) { Method preDestroy = getMethod(clazz, entry); synchronized (preDestroy) { boolean accessibility = preDestroy.isAccessible(); preDestroy.setAccessible(true); preDestroy.invoke(instance); preDestroy.setAccessible(accessibility); } } } } /** * Make sure that the annotations cache has been populated for the provided * class. * * @param clazz clazz to populate annotations for * @param injections map of injections for this class from xml deployment * descriptor * @throws IllegalAccessException if injection target is inaccessible * @throws javax.naming.NamingException if value cannot be looked up in jndi * @throws java.lang.reflect.InvocationTargetException * if injection fails */ protected void populateAnnotationsCache(Class<?> clazz, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { List<AnnotationCacheEntry> annotations = null; while (clazz != null) { AnnotationCacheEntry[] annotationsArray = null; synchronized (annotationCache) { annotationsArray = annotationCache.get(clazz); } if (annotationsArray == null) { if (annotations == null) { annotations = new ArrayList<>(); } else { annotations.clear(); } if (context != null) { // Initialize fields annotations for resource injection if // JNDI is enabled Field[] fields = Introspection.getDeclaredFields(clazz); for (Field field : fields) { if (injections != null && injections.containsKey(field.getName())) { annotations.add(new AnnotationCacheEntry( field.getName(), null, injections.get(field.getName()), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(Resource.class)) { Resource annotation = field.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(EJB.class)) { EJB annotation = field.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = field.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = field.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } else if (field.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = field.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( field.getName(), null, annotation.name(), AnnotationCacheEntryType.FIELD)); } } } // Initialize methods annotations Method[] methods = Introspection.getDeclaredMethods(clazz); Method postConstruct = null; String postConstructFromXml = postConstructMethods.get(clazz.getName()); Method preDestroy = null; String preDestroyFromXml = preDestroyMethods.get(clazz.getName()); for (Method method : methods) { if (context != null) { // Resource injection only if JNDI is enabled if (injections != null && Introspection.isValidSetter(method)) { String fieldName = Introspection.getPropertyName(method); if (injections.containsKey(fieldName)) { annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), injections.get(method.getName()), AnnotationCacheEntryType.SETTER)); break; } } if (method.isAnnotationPresent(Resource.class)) { Resource annotation = method.getAnnotation(Resource.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(EJB.class)) { EJB annotation = method.getAnnotation(EJB.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(WebServiceRef.class)) { WebServiceRef annotation = method.getAnnotation(WebServiceRef.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceContext.class)) { PersistenceContext annotation = method.getAnnotation(PersistenceContext.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } else if (method.isAnnotationPresent(PersistenceUnit.class)) { PersistenceUnit annotation = method.getAnnotation(PersistenceUnit.class); annotations.add(new AnnotationCacheEntry( method.getName(), method.getParameterTypes(), annotation.name(), AnnotationCacheEntryType.SETTER)); } } postConstruct = findPostConstruct(postConstruct, postConstructFromXml, method); preDestroy = findPreDestroy(preDestroy, preDestroyFromXml, method); } if (postConstruct != null) { annotations.add(new AnnotationCacheEntry( postConstruct.getName(), postConstruct.getParameterTypes(), null, AnnotationCacheEntryType.POST_CONSTRUCT)); } else if (postConstructFromXml != null) { throw new IllegalArgumentException("Post construct method " + postConstructFromXml + " for class " + clazz.getName() + " is declared in deployment descriptor but cannot be found."); } if (preDestroy != null) { annotations.add(new AnnotationCacheEntry( preDestroy.getName(), preDestroy.getParameterTypes(), null, AnnotationCacheEntryType.PRE_DESTROY)); } else if (preDestroyFromXml != null) { throw new IllegalArgumentException("Pre destroy method " + preDestroyFromXml + " for class " + clazz.getName() + " is declared in deployment descriptor but cannot be found."); } if (annotations.isEmpty()) { // Use common object to save memory annotationsArray = ANNOTATIONS_EMPTY; } else { annotationsArray = annotations.toArray( new AnnotationCacheEntry[annotations.size()]); } synchronized (annotationCache) { annotationCache.put(clazz, annotationsArray); } } clazz = clazz.getSuperclass(); } } /** * Inject resources in specified instance. * * @param instance instance to inject into * @param injections map of injections for this class from xml deployment descriptor * @throws IllegalAccessException if injection target is inaccessible * @throws javax.naming.NamingException if value cannot be looked up in jndi * @throws java.lang.reflect.InvocationTargetException * if injection fails */ protected void processAnnotations(Object instance, Map<String, String> injections) throws IllegalAccessException, InvocationTargetException, NamingException { if (context == null) { // No resource injection return; } Class<?> clazz = instance.getClass(); while (clazz != null) { AnnotationCacheEntry[] annotations; synchronized (annotationCache) { annotations = annotationCache.get(clazz); } for (AnnotationCacheEntry entry : annotations) { if (entry.getType() == AnnotationCacheEntryType.SETTER) { lookupMethodResource(context, instance, getMethod(clazz, entry), entry.getName(), clazz); } else if (entry.getType() == AnnotationCacheEntryType.FIELD) { lookupFieldResource(context, instance, getField(clazz, entry), entry.getName(), clazz); } } clazz = clazz.getSuperclass(); } } /** * Makes cache size available to unit tests. */ protected int getAnnotationCacheSize() { synchronized (annotationCache) { return annotationCache.size(); } } protected Class<?> loadClassMaybePrivileged(final String className, final ClassLoader classLoader) throws ClassNotFoundException { Class<?> clazz; if (SecurityUtil.isPackageProtectionEnabled()) { try { clazz = AccessController.doPrivileged(new PrivilegedExceptionAction<Class<?>>() { @Override public Class<?> run() throws Exception { return loadClass(className, classLoader); } }); } catch (PrivilegedActionException e) { Throwable t = e.getCause(); if (t instanceof ClassNotFoundException) { throw (ClassNotFoundException) t; } throw new RuntimeException(t); } } else { clazz = loadClass(className, classLoader); } checkAccess(clazz); return clazz; } protected Class<?> loadClass(String className, ClassLoader classLoader) throws ClassNotFoundException { if (className.startsWith("org.apache.catalina")) { return containerClassLoader.loadClass(className); } try { Class<?> clazz = containerClassLoader.loadClass(className); if (ContainerServlet.class.isAssignableFrom(clazz)) { return clazz; } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } return classLoader.loadClass(className); } private void checkAccess(Class<?> clazz) { if (privileged) { return; } if (Filter.class.isAssignableFrom(clazz)) { checkAccess(clazz, restrictedFilters); } else if (Servlet.class.isAssignableFrom(clazz)) { if (ContainerServlet.class.isAssignableFrom(clazz)) { throw new SecurityException("Restricted (ContainerServlet) " + clazz); } checkAccess(clazz, restrictedServlets); } else { checkAccess(clazz, restrictedListeners); } } private void checkAccess(Class<?> clazz, Properties restricted) { while (clazz != null) { if ("restricted".equals(restricted.getProperty(clazz.getName()))) { throw new SecurityException("Restricted " + clazz); } clazz = clazz.getSuperclass(); } } /** * Inject resources in specified field. * * @param context jndi context to extract value from * @param instance object to inject into * @param field field target for injection * @param name jndi name value is bound under * @param clazz class annotation is defined in * @throws IllegalAccessException if field is inaccessible * @throws javax.naming.NamingException if value is not accessible in naming context */ protected static void lookupFieldResource(Context context, Object instance, Field field, String name, Class<?> clazz) throws NamingException, IllegalAccessException { Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup(clazz.getName() + "/" + field.getName()); } synchronized (field) { accessibility = field.isAccessible(); field.setAccessible(true); field.set(instance, lookedupResource); field.setAccessible(accessibility); } } /** * Inject resources in specified method. * * @param context jndi context to extract value from * @param instance object to inject into * @param method field target for injection * @param name jndi name value is bound under * @param clazz class annotation is defined in * @throws IllegalAccessException if method is inaccessible * @throws javax.naming.NamingException if value is not accessible in naming context * @throws java.lang.reflect.InvocationTargetException * if setter call fails */ protected static void lookupMethodResource(Context context, Object instance, Method method, String name, Class<?> clazz) throws NamingException, IllegalAccessException, InvocationTargetException { if (!Introspection.isValidSetter(method)) { throw new IllegalArgumentException( sm.getString("defaultInstanceManager.invalidInjection")); } Object lookedupResource; boolean accessibility; String normalizedName = normalize(name); if ((normalizedName != null) && (normalizedName.length() > 0)) { lookedupResource = context.lookup(normalizedName); } else { lookedupResource = context.lookup( clazz.getName() + "/" + Introspection.getPropertyName(method)); } synchronized (method) { accessibility = method.isAccessible(); method.setAccessible(true); method.invoke(instance, lookedupResource); method.setAccessible(accessibility); } } private static String normalize(String jndiName){ if(jndiName != null && jndiName.startsWith("java:comp/env/")){ return jndiName.substring(14); } return jndiName; } private static Method getMethod(final Class<?> clazz, final AnnotationCacheEntry entry) { Method result = null; if (Globals.IS_SECURITY_ENABLED) { result = AccessController.doPrivileged( new PrivilegedAction<Method>() { @Override public Method run() { Method result = null; try { result = clazz.getDeclaredMethod( entry.getAccessibleObjectName(), entry.getParamTypes()); } catch (NoSuchMethodException e) { // Should never happen. On that basis don't log // it. } return result; } }); } else { try { result = clazz.getDeclaredMethod( entry.getAccessibleObjectName(), entry.getParamTypes()); } catch (NoSuchMethodException e) { // Should never happen. On that basis don't log it. } } return result; } private static Field getField(final Class<?> clazz, final AnnotationCacheEntry entry) { Field result = null; if (Globals.IS_SECURITY_ENABLED) { result = AccessController.doPrivileged( new PrivilegedAction<Field>() { @Override public Field run() { Field result = null; try { result = clazz.getDeclaredField( entry.getAccessibleObjectName()); } catch (NoSuchFieldException e) { // Should never happen. On that basis don't log // it. } return result; } }); } else { try { result = clazz.getDeclaredField( entry.getAccessibleObjectName()); } catch (NoSuchFieldException e) { // Should never happen. On that basis don't log it. } } return result; } private static Method findPostConstruct(Method currentPostConstruct, String postConstructFromXml, Method method) { return findLifecycleCallback(currentPostConstruct, postConstructFromXml, method, PostConstruct.class); } private static Method findPreDestroy(Method currentPreDestroy, String preDestroyFromXml, Method method) { return findLifecycleCallback(currentPreDestroy, preDestroyFromXml, method, PreDestroy.class); } private static Method findLifecycleCallback(Method currentMethod, String methodNameFromXml, Method method, Class<? extends Annotation> annotation) { Method result = currentMethod; if (methodNameFromXml != null) { if (method.getName().equals(methodNameFromXml)) { if (!Introspection.isValidLifecycleCallback(method)) { throw new IllegalArgumentException( "Invalid " + annotation.getName() + " annotation"); } result = method; } } else { if (method.isAnnotationPresent(annotation)) { if (currentMethod != null || !Introspection.isValidLifecycleCallback(method)) { throw new IllegalArgumentException( "Invalid " + annotation.getName() + " annotation"); } result = method; } } return result; } private static final class AnnotationCacheEntry { private final String accessibleObjectName; private final Class<?>[] paramTypes; private final String name; private final AnnotationCacheEntryType type; public AnnotationCacheEntry(String accessibleObjectName, Class<?>[] paramTypes, String name, AnnotationCacheEntryType type) { this.accessibleObjectName = accessibleObjectName; this.paramTypes = paramTypes; this.name = name; this.type = type; } public String getAccessibleObjectName() { return accessibleObjectName; } public Class<?>[] getParamTypes() { return paramTypes; } public String getName() { return name; } public AnnotationCacheEntryType getType() { return type; } } private static enum AnnotationCacheEntryType { FIELD, SETTER, POST_CONSTRUCT, PRE_DESTROY } }
54,450
Bug 54450 Injection fails when part of the servlet properties uses @Resource and the other uses 'injection-target'
Hi, I have a servlet with: - annotated properties - and injection-target declarations in web.xml When I try to request this servlet I receive: javax.naming.NameNotFoundException: Name [envEntry1] is not bound in this Context. Unable to find [envEntry1]. at org.apache.naming.NamingContext.lookup(NamingContext.java:820) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupMethodResource(DefaultInstanceManager.java:622) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:466) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) The problem is that when the application uses 'injection-target' declarations in org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(Class<?>, Map<String, String>) only the first setter method is evaluated and the rest are skipped. I would like to propose a patch and test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
ac78456
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:57:27Z
2013-01-18T23:00:00Z
test/org/apache/catalina/startup/TestContextConfig.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.IOException; import java.util.Set; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; 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.core.StandardContext; import org.apache.tomcat.util.buf.ByteChunk; public class TestContextConfig extends TomcatBaseTest { @Test public void testOverrideWithSCIDefaultName() throws Exception { doTestOverrideDefaultServletWithSCI("default"); } @Test public void testOverrideWithSCIDefaultMapping() throws Exception { doTestOverrideDefaultServletWithSCI("anything"); } private void doTestOverrideDefaultServletWithSCI(String servletName) throws Exception{ Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0"); StandardContext ctxt = (StandardContext) tomcat.addContext(null, "/test", appDir.getAbsolutePath()); ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath()); ctxt.addLifecycleListener(new ContextConfig()); ctxt.addServletContainerInitializer( new CustomDefaultServletSCI(servletName), null); tomcat.start(); assertPageContains("/test", "OK - Custom default Servlet"); } @Test public void testBug51396() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments"); // app dir is relative to server home tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); assertPageContains("/test/bug51396.jsp", "<p>OK</p>"); } @Test public void testBug53574() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0"); tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); assertPageContains("/test/bug53574", "OK"); } @Test public void testBug54262() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments-empty-absolute-ordering"); tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); assertPageContains("/test/resourceA.jsp", "resourceA.jsp in resources.jar"); assertPageContains("/test/resources/HelloWorldExample", null, HttpServletResponse.SC_NOT_FOUND); } @Test public void testBug54379() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments"); Context context = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); Tomcat.addServlet(context, "TestServlet", "org.apache.catalina.startup.TesterServletWithLifeCycleMethods"); context.addServletMapping("/testServlet", "TestServlet"); tomcat.enableNaming(); tomcat.start(); assertPageContains("/test/testServlet", "postConstruct1()"); } @Test public void testBug54448() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0-fragments"); Context context = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); Tomcat.addServlet(context, "TestServlet", "org.apache.catalina.startup.TesterServletWithAnnotations"); context.addServletMapping("/testServlet", "TestServlet"); tomcat.enableNaming(); tomcat.start(); assertPageContains("/test/testServlet", "envEntry: 1"); } private static class CustomDefaultServletSCI implements ServletContainerInitializer { private String servletName; public CustomDefaultServletSCI(String servletName) { this.servletName = servletName; } @Override public void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException { Servlet s = new CustomDefaultServlet(); ServletRegistration.Dynamic r = ctx.addServlet(servletName, s); r.addMapping("/"); } } private static class CustomDefaultServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("OK - Custom default Servlet"); } } private void assertPageContains(String pageUrl, String expectedBody) throws IOException { assertPageContains(pageUrl, expectedBody, HttpServletResponse.SC_OK); } private void assertPageContains(String pageUrl, String expectedBody, int expectedStatus) throws IOException { ByteChunk res = new ByteChunk(); int sc = getUrl("http://localhost:" + getPort() + pageUrl, res, null); Assert.assertEquals(expectedStatus, sc); if (expectedStatus == HttpServletResponse.SC_OK) { String result = res.toString(); Assert.assertTrue(result, result.indexOf(expectedBody) > -1); } } }
54,450
Bug 54450 Injection fails when part of the servlet properties uses @Resource and the other uses 'injection-target'
Hi, I have a servlet with: - annotated properties - and injection-target declarations in web.xml When I try to request this servlet I receive: javax.naming.NameNotFoundException: Name [envEntry1] is not bound in this Context. Unable to find [envEntry1]. at org.apache.naming.NamingContext.lookup(NamingContext.java:820) at org.apache.naming.NamingContext.lookup(NamingContext.java:154) at org.apache.naming.NamingContext.lookup(NamingContext.java:831) at org.apache.naming.NamingContext.lookup(NamingContext.java:168) at org.apache.catalina.core.DefaultInstanceManager.lookupMethodResource(DefaultInstanceManager.java:622) at org.apache.catalina.core.DefaultInstanceManager.processAnnotations(DefaultInstanceManager.java:466) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:157) at org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:138) at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1137) at org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:858) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:136) 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.core.StandardEngineValve.invoke(StandardEngineValve.java:118) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407) at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589) at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908) at java.lang.Thread.run(Thread.java:680) The problem is that when the application uses 'injection-target' declarations in org.apache.catalina.core.DefaultInstanceManager.populateAnnotationsCache(Class<?>, Map<String, String>) only the first setter method is evaluated and the rest are skipped. I would like to propose a patch and test case. I'm looking forward to your comments. Regards Violeta
resolved fixed
ac78456
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T10:57:27Z
2013-01-18T23:00:00Z
test/org/apache/catalina/startup/TesterServletWithAnnotations.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.IOException; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class TesterServletWithAnnotations extends HttpServlet { private static final long serialVersionUID = 1L; @Resource(mappedName = "1") private int envEntry; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("envEntry: " + envEntry); } }
54,458
Bug 54458 DataSourceRealm should provide more info on SQLException
The getPassword() method of the DataSourceRealm does not log enough information when it encounters an SQL error. The catch block is: } catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); } finally { it would be really helpful to have some details of what the SQLException is. I am getting this intermittently, and have resorted to subclassing getPassword() in an attempt to figure out what is going wrong.
resolved fixed
07a930d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T15:55:17Z
2013-01-22T02:00:00Z
java/org/apache/catalina/realm/DataSourceRealm.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.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import javax.naming.Context; import javax.sql.DataSource; import org.apache.catalina.LifecycleException; import org.apache.naming.ContextBindings; /** * * Implementation of <b>Realm</b> that works with any JDBC JNDI DataSource. * See the JDBCRealm.howto for more details on how to set up the database and * for configuration options. * * @author Glenn L. Nielsen * @author Craig R. McClanahan * @author Carson McDonald * @author Ignacio Ortega * @version $Revision$ */ public class DataSourceRealm extends RealmBase { // ----------------------------------------------------- Instance Variables /** * The generated string for the roles PreparedStatement */ private String preparedRoles = null; /** * The generated string for the credentials PreparedStatement */ private String preparedCredentials = null; /** * The name of the JNDI JDBC DataSource */ protected String dataSourceName = null; /** * Context local datasource. */ protected boolean localDataSource = false; /** * Descriptive information about this Realm implementation. */ protected static final String name = "DataSourceRealm"; /** * The column in the user role table that names a role */ protected String roleNameCol = null; /** * The column in the user table that holds the user's credentials */ protected String userCredCol = null; /** * The column in the user table that holds the user's name */ protected String userNameCol = null; /** * The table that holds the relation between user's and roles */ protected String userRoleTable = null; /** * The table that holds user data. */ protected String userTable = null; // ------------------------------------------------------------- Properties /** * Return the name of the JNDI JDBC DataSource. * */ public String getDataSourceName() { return dataSourceName; } /** * Set the name of the JNDI JDBC DataSource. * * @param dataSourceName the name of the JNDI JDBC DataSource */ public void setDataSourceName( String dataSourceName) { this.dataSourceName = dataSourceName; } /** * Return if the datasource will be looked up in the webapp JNDI Context. */ public boolean getLocalDataSource() { return localDataSource; } /** * Set to true to cause the datasource to be looked up in the webapp JNDI * Context. * * @param localDataSource the new flag value */ public void setLocalDataSource(boolean localDataSource) { this.localDataSource = localDataSource; } /** * Return the column in the user role table that names a role. * */ public String getRoleNameCol() { return roleNameCol; } /** * Set the column in the user role table that names a role. * * @param roleNameCol The column name */ public void setRoleNameCol( String roleNameCol ) { this.roleNameCol = roleNameCol; } /** * Return the column in the user table that holds the user's credentials. * */ public String getUserCredCol() { return userCredCol; } /** * Set the column in the user table that holds the user's credentials. * * @param userCredCol The column name */ public void setUserCredCol( String userCredCol ) { this.userCredCol = userCredCol; } /** * Return the column in the user table that holds the user's name. * */ public String getUserNameCol() { return userNameCol; } /** * Set the column in the user table that holds the user's name. * * @param userNameCol The column name */ public void setUserNameCol( String userNameCol ) { this.userNameCol = userNameCol; } /** * Return the table that holds the relation between user's and roles. * */ public String getUserRoleTable() { return userRoleTable; } /** * Set the table that holds the relation between user's and roles. * * @param userRoleTable The table name */ public void setUserRoleTable( String userRoleTable ) { this.userRoleTable = userRoleTable; } /** * Return the table that holds user data.. * */ public String getUserTable() { return userTable; } /** * Set the table that holds user data. * * @param userTable The table name */ public void setUserTable( String userTable ) { this.userTable = userTable; } // --------------------------------------------------------- Public Methods /** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * If there are any errors with the JDBC connection, executing * the query or anything we return null (don't authenticate). This * event is also logged, and the connection will be closed so that * a subsequent request will automatically re-open it. * * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ @Override public Principal authenticate(String username, String credentials) { // No user or no credentials // Can't possibly authenticate, don't bother the database then if (username == null || credentials == null) { return null; } Connection dbConnection = null; // Ensure that we have an open database connection dbConnection = open(); if (dbConnection == null) { // If the db connection open fails, return "not authenticated" return null; } // Acquire a Principal object for this user Principal principal = authenticate(dbConnection, username, credentials); close(dbConnection); return principal; } // -------------------------------------------------------- Package Methods // ------------------------------------------------------ Protected Methods /** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * @param dbConnection The database connection to be used * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username */ protected Principal authenticate(Connection dbConnection, String username, String credentials) { String dbCredentials = getPassword(dbConnection, username); // Validate the user's credentials boolean validated = false; if (hasMessageDigest()) { // Hex hashes should be compared case-insensitive validated = (digest(credentials).equalsIgnoreCase(dbCredentials)); } else validated = (digest(credentials).equals(dbCredentials)); if (validated) { if (containerLog.isTraceEnabled()) containerLog.trace( sm.getString("dataSourceRealm.authenticateSuccess", username)); } else { if (containerLog.isTraceEnabled()) containerLog.trace( sm.getString("dataSourceRealm.authenticateFailure", username)); return (null); } ArrayList<String> list = getRoles(dbConnection, username); // Create and return a suitable Principal for this user return (new GenericPrincipal(username, credentials, list)); } /** * Close the specified database connection. * * @param dbConnection The connection to be closed */ protected void close(Connection dbConnection) { // Do nothing if the database connection is already closed if (dbConnection == null) return; // Commit if not auto committed try { if (!dbConnection.getAutoCommit()) { dbConnection.commit(); } } catch (SQLException e) { containerLog.error("Exception committing connection before closing:", e); } // Close this database connection, and log any errors try { dbConnection.close(); } catch (SQLException e) { containerLog.error(sm.getString("dataSourceRealm.close"), e); // Just log it here } } /** * Open the specified database connection. * * @return Connection to the database */ protected Connection open() { try { Context context = null; if (localDataSource) { context = ContextBindings.getClassLoader(); context = (Context) context.lookup("comp/env"); } else { context = getServer().getGlobalNamingContext(); } DataSource dataSource = (DataSource)context.lookup(dataSourceName); return dataSource.getConnection(); } catch (Exception e) { // Log the problem for posterity containerLog.error(sm.getString("dataSourceRealm.exception"), e); } return null; } /** * Return a short name for this Realm implementation. */ @Override protected String getName() { return (name); } /** * Return the password associated with the given principal's user name. */ @Override protected String getPassword(String username) { Connection dbConnection = null; // Ensure that we have an open database connection dbConnection = open(); if (dbConnection == null) { return null; } try { return getPassword(dbConnection, username); } finally { close(dbConnection); } } /** * Return the password associated with the given principal's user name. * @param dbConnection The database connection to be used * @param username Username for which password should be retrieved */ protected String getPassword(Connection dbConnection, String username) { ResultSet rs = null; PreparedStatement stmt = null; String dbCredentials = null; try { stmt = credentials(dbConnection, username); rs = stmt.executeQuery(); if (rs.next()) { dbCredentials = rs.getString(1); } return (dbCredentials != null) ? dbCredentials.trim() : null; } catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getPassword.exception", username)); } } return null; } /** * Return the Principal associated with the given user name. */ @Override protected Principal getPrincipal(String username) { Connection dbConnection = open(); if (dbConnection == null) { return new GenericPrincipal(username, null, null); } try { return (new GenericPrincipal(username, getPassword(dbConnection, username), getRoles(dbConnection, username))); } finally { close(dbConnection); } } /** * Return the roles associated with the given user name. * @param username Username for which roles should be retrieved */ protected ArrayList<String> getRoles(String username) { Connection dbConnection = null; // Ensure that we have an open database connection dbConnection = open(); if (dbConnection == null) { return null; } try { return getRoles(dbConnection, username); } finally { close(dbConnection); } } /** * Return the roles associated with the given user name * @param dbConnection The database connection to be used * @param username Username for which roles should be retrieved */ protected ArrayList<String> getRoles(Connection dbConnection, String username) { if (allRolesMode != AllRolesMode.STRICT_MODE && !isRoleStoreDefined()) { // Using an authentication only configuration and no role store has // been defined so don't spend cycles looking return null; } ResultSet rs = null; PreparedStatement stmt = null; ArrayList<String> list = null; try { stmt = roles(dbConnection, username); rs = stmt.executeQuery(); list = new ArrayList<>(); while (rs.next()) { String role = rs.getString(1); if (role != null) { list.add(role.trim()); } } return list; } catch(SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); } finally { try { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } } catch (SQLException e) { containerLog.error( sm.getString("dataSourceRealm.getRoles.exception", username)); } } return null; } /** * Return a PreparedStatement configured to perform the SELECT required * to retrieve user credentials for the specified username. * * @param dbConnection The database connection to be used * @param username Username for which credentials should be retrieved * * @exception SQLException if a database error occurs */ private PreparedStatement credentials(Connection dbConnection, String username) throws SQLException { PreparedStatement credentials = dbConnection.prepareStatement(preparedCredentials); credentials.setString(1, username); return (credentials); } /** * Return a PreparedStatement configured to perform the SELECT required * to retrieve user roles for the specified username. * * @param dbConnection The database connection to be used * @param username Username for which roles should be retrieved * * @exception SQLException if a database error occurs */ private PreparedStatement roles(Connection dbConnection, String username) throws SQLException { PreparedStatement roles = dbConnection.prepareStatement(preparedRoles); roles.setString(1, username); return (roles); } private boolean isRoleStoreDefined() { return userRoleTable != null || roleNameCol != null; } // ------------------------------------------------------ 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 { // Create the roles PreparedStatement string StringBuilder temp = new StringBuilder("SELECT "); temp.append(roleNameCol); temp.append(" FROM "); temp.append(userRoleTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedRoles = temp.toString(); // Create the credentials PreparedStatement string temp = new StringBuilder("SELECT "); temp.append(userCredCol); temp.append(" FROM "); temp.append(userTable); temp.append(" WHERE "); temp.append(userNameCol); temp.append(" = ?"); preparedCredentials = temp.toString(); super.startInternal(); } }
54,466
Bug 54466 No file name information in detail error when compiling the java file generated from a tag file
null
resolved fixed
d7f744c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-23T19:40:40Z
2013-01-22T13:06:40Z
java/org/apache/jasper/compiler/DefaultErrorHandler.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 org.apache.jasper.Constants; import org.apache.jasper.JasperException; /** * Default implementation of ErrorHandler interface. * * @author Jan Luehe */ class DefaultErrorHandler implements ErrorHandler { /* * Processes the given JSP parse error. * * @param fname Name of the JSP file in which the parse error occurred * @param line Parse error line number * @param column Parse error column number * @param errMsg Parse error message * @param exception Parse exception */ @Override public void jspError(String fname, int line, int column, String errMsg, Exception ex) throws JasperException { throw new JasperException(fname + " (" + Localizer.getMessage("jsp.error.location", Integer.toString(line), Integer.toString(column)) + ") " + errMsg, ex); } /* * Processes the given JSP parse error. * * @param errMsg Parse error message * @param exception Parse exception */ @Override public void jspError(String errMsg, Exception ex) throws JasperException { throw new JasperException(errMsg, ex); } /* * Processes the given javac compilation errors. * * @param details Array of JavacErrorDetail instances corresponding to the * compilation errors */ @Override public void javacError(JavacErrorDetail[] details) throws JasperException { if (details == null) { return; } Object[] args = null; StringBuilder buf = new StringBuilder(); for (int i=0; i < details.length; i++) { if (details[i].getJspBeginLineNumber() >= 0) { args = new Object[] { Integer.valueOf(details[i].getJspBeginLineNumber()), details[i].getJspFileName() }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.single.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); buf.append(Constants.NEWLINE); buf.append(details[i].getJspExtract()); } else { args = new Object[] { Integer.valueOf(details[i].getJavaLineNumber()) }; buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append(Localizer.getMessage("jsp.error.java.line.number", args)); buf.append(Constants.NEWLINE); buf.append(details[i].getErrorMessage()); } } buf.append(Constants.NEWLINE); buf.append(Constants.NEWLINE); buf.append("Stacktrace:"); throw new JasperException( Localizer.getMessage("jsp.error.unable.compile") + ": " + buf); } /** * Processes the given javac error report and exception. * * @param errorReport Compilation error report * @param exception Compilation exception */ @Override public void javacError(String errorReport, Exception exception) throws JasperException { throw new JasperException( Localizer.getMessage("jsp.error.unable.compile"), exception); } }
54,476
Bug 54476 incorrect param specification in javadoc ...tribes.group.GroupChannel send methods
* @param destination Member[] - destination.length > 1 I believe this should be: * @param destination Member[] - destination.length > 0
resolved fixed
6647531
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-24T08:52:26Z
2013-01-24T01:13:20Z
java/org/apache/catalina/tribes/group/GroupChannel.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.group; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import org.apache.catalina.tribes.ByteMessage; import org.apache.catalina.tribes.Channel; import org.apache.catalina.tribes.ChannelException; import org.apache.catalina.tribes.ChannelInterceptor; import org.apache.catalina.tribes.ChannelListener; import org.apache.catalina.tribes.ChannelMessage; import org.apache.catalina.tribes.ChannelReceiver; import org.apache.catalina.tribes.ChannelSender; import org.apache.catalina.tribes.ErrorHandler; import org.apache.catalina.tribes.Heartbeat; import org.apache.catalina.tribes.ManagedChannel; import org.apache.catalina.tribes.Member; import org.apache.catalina.tribes.MembershipListener; import org.apache.catalina.tribes.MembershipService; import org.apache.catalina.tribes.RemoteProcessException; import org.apache.catalina.tribes.UniqueId; import org.apache.catalina.tribes.group.interceptors.MessageDispatchInterceptor; import org.apache.catalina.tribes.io.BufferPool; import org.apache.catalina.tribes.io.ChannelData; import org.apache.catalina.tribes.io.XByteBuffer; import org.apache.catalina.tribes.util.Arrays; import org.apache.catalina.tribes.util.Logs; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * The default implementation of a Channel.<br> * The GroupChannel manages the replication channel. It coordinates * message being sent and received with membership announcements. * The channel has an chain of interceptors that can modify the message or perform other logic.<br> * It manages a complete group, both membership and replication. * @author Filip Hanik * @version $Id$ */ public class GroupChannel extends ChannelInterceptorBase implements ManagedChannel { private static final Log log = LogFactory.getLog(GroupChannel.class); /** * Flag to determine if the channel manages its own heartbeat * If set to true, the channel will start a local thread for the heart beat. */ protected boolean heartbeat = true; /** * If <code>heartbeat == true</code> then how often do we want this * heartbeat to run. default is one minute */ protected long heartbeatSleeptime = 5*1000;//every 5 seconds /** * Internal heartbeat thread */ protected HeartbeatThread hbthread = null; /** * The <code>ChannelCoordinator</code> coordinates the bottom layer components:<br> * - MembershipService<br> * - ChannelSender <br> * - ChannelReceiver<br> */ protected final ChannelCoordinator coordinator = new ChannelCoordinator(); /** * The first interceptor in the interceptor stack. * The interceptors are chained in a linked list, so we only need a reference to the * first one */ protected ChannelInterceptor interceptors = null; /** * A list of membership listeners that subscribe to membership announcements */ protected final ArrayList<Object> membershipListeners = new ArrayList<>(); /** * A list of channel listeners that subscribe to incoming messages */ protected final ArrayList<Object> channelListeners = new ArrayList<>(); /** * If set to true, the GroupChannel will check to make sure that */ protected boolean optionCheck = false; /** * Creates a GroupChannel. This constructor will also * add the first interceptor in the GroupChannel.<br> * The first interceptor is always the channel itself. */ public GroupChannel() { addInterceptor(this); } /** * Adds an interceptor to the stack for message processing<br> * Interceptors are ordered in the way they are added.<br> * <code>channel.addInterceptor(A);</code><br> * <code>channel.addInterceptor(C);</code><br> * <code>channel.addInterceptor(B);</code><br> * Will result in a interceptor stack like this:<br> * <code>A -> C -> B</code><br> * The complete stack will look like this:<br> * <code>Channel -> A -> C -> B -> ChannelCoordinator</code><br> * @param interceptor ChannelInterceptorBase */ @Override public void addInterceptor(ChannelInterceptor interceptor) { if ( interceptors == null ) { interceptors = interceptor; interceptors.setNext(coordinator); interceptors.setPrevious(null); coordinator.setPrevious(interceptors); } else { ChannelInterceptor last = interceptors; while ( last.getNext() != coordinator ) { last = last.getNext(); } last.setNext(interceptor); interceptor.setNext(coordinator); interceptor.setPrevious(last); coordinator.setPrevious(interceptor); } } /** * Sends a heartbeat through the interceptor stack.<br> * Invoke this method from the application on a periodic basis if * you have turned off internal heartbeats <code>channel.setHeartbeat(false)</code> */ @Override public void heartbeat() { super.heartbeat(); Iterator<Object> i = membershipListeners.iterator(); while ( i.hasNext() ) { Object o = i.next(); if ( o instanceof Heartbeat ) ((Heartbeat)o).heartbeat(); } i = channelListeners.iterator(); while ( i.hasNext() ) { Object o = i.next(); if ( o instanceof Heartbeat ) ((Heartbeat)o).heartbeat(); } } /** * Send a message to the destinations specified * @param destination Member[] - destination.length > 1 * @param msg Serializable - the message to send * @param options int - sender options, options can trigger guarantee levels and different interceptors to * react to the message see class documentation for the <code>Channel</code> object.<br> * @return UniqueId - the unique Id that was assigned to this message * @throws ChannelException - if an error occurs processing the message * @see org.apache.catalina.tribes.Channel */ @Override public UniqueId send(Member[] destination, Serializable msg, int options) throws ChannelException { return send(destination,msg,options,null); } /** * * @param destination Member[] - destination.length > 1 * @param msg Serializable - the message to send * @param options int - sender options, options can trigger guarantee levels and different interceptors to * react to the message see class documentation for the <code>Channel</code> object.<br> * @param handler - callback object for error handling and completion notification, used when a message is * sent asynchronously using the <code>Channel.SEND_OPTIONS_ASYNCHRONOUS</code> flag enabled. * @return UniqueId - the unique Id that was assigned to this message * @throws ChannelException - if an error occurs processing the message * @see org.apache.catalina.tribes.Channel */ @Override public UniqueId send(Member[] destination, Serializable msg, int options, ErrorHandler handler) throws ChannelException { if ( msg == null ) throw new ChannelException("Cant send a NULL message"); XByteBuffer buffer = null; try { if ( destination == null || destination.length == 0) throw new ChannelException("No destination given"); ChannelData data = new ChannelData(true);//generates a unique Id data.setAddress(getLocalMember(false)); data.setTimestamp(System.currentTimeMillis()); byte[] b = null; if ( msg instanceof ByteMessage ){ b = ((ByteMessage)msg).getMessage(); options = options | SEND_OPTIONS_BYTE_MESSAGE; } else { b = XByteBuffer.serialize(msg); options = options & (~SEND_OPTIONS_BYTE_MESSAGE); } data.setOptions(options); //XByteBuffer buffer = new XByteBuffer(b.length+128,false); buffer = BufferPool.getBufferPool().getBuffer(b.length+128, false); buffer.append(b,0,b.length); data.setMessage(buffer); InterceptorPayload payload = null; if ( handler != null ) { payload = new InterceptorPayload(); payload.setErrorHandler(handler); } getFirstInterceptor().sendMessage(destination, data, payload); if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Sent msg:" + new UniqueId(data.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " to "+Arrays.toNameString(destination)); Logs.MESSAGES.trace("GroupChannel - Send Message:" + new UniqueId(data.getUniqueId()) + " is " +msg); } return new UniqueId(data.getUniqueId()); }catch ( Exception x ) { if ( x instanceof ChannelException ) throw (ChannelException)x; throw new ChannelException(x); } finally { if ( buffer != null ) BufferPool.getBufferPool().returnBuffer(buffer); } } /** * Callback from the interceptor stack. <br> * When a message is received from a remote node, this method will be invoked by * the previous interceptor.<br> * This method can also be used to send a message to other components within the same application, * but its an extreme case, and you're probably better off doing that logic between the applications itself. * @param msg ChannelMessage */ @Override public void messageReceived(ChannelMessage msg) { if ( msg == null ) return; try { if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Received msg:" + new UniqueId(msg.getUniqueId()) + " at " +new java.sql.Timestamp(System.currentTimeMillis())+ " from "+msg.getAddress().getName()); } Serializable fwd = null; if ( (msg.getOptions() & SEND_OPTIONS_BYTE_MESSAGE) == SEND_OPTIONS_BYTE_MESSAGE ) { fwd = new ByteMessage(msg.getMessage().getBytes()); } else { try { fwd = XByteBuffer.deserialize(msg.getMessage().getBytesDirect(), 0, msg.getMessage().getLength()); }catch (Exception sx) { log.error("Unable to deserialize message:"+msg,sx); return; } } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel - Receive Message:" + new UniqueId(msg.getUniqueId()) + " is " +fwd); } //get the actual member with the correct alive time Member source = msg.getAddress(); boolean rx = false; boolean delivered = false; for ( int i=0; i<channelListeners.size(); i++ ) { ChannelListener channelListener = (ChannelListener)channelListeners.get(i); if (channelListener != null && channelListener.accept(fwd, source)) { channelListener.messageReceived(fwd, source); delivered = true; //if the message was accepted by an RPC channel, that channel //is responsible for returning the reply, otherwise we send an absence reply if ( channelListener instanceof RpcChannel ) rx = true; } }//for if ((!rx) && (fwd instanceof RpcMessage)) { //if we have a message that requires a response, //but none was given, send back an immediate one sendNoRpcChannelReply((RpcMessage)fwd,source); } if ( Logs.MESSAGES.isTraceEnabled() ) { Logs.MESSAGES.trace("GroupChannel delivered["+delivered+"] id:"+new UniqueId(msg.getUniqueId())); } } catch ( Exception x ) { //this could be the channel listener throwing an exception, we should log it //as a warning. if ( log.isWarnEnabled() ) log.warn("Error receiving message:",x); throw new RemoteProcessException("Exception:"+x.getMessage(),x); } } /** * Sends a <code>NoRpcChannelReply</code> message to a member<br> * This method gets invoked by the channel if a RPC message comes in * and no channel listener accepts the message. This avoids timeout * @param msg RpcMessage * @param destination Member - the destination for the reply */ protected void sendNoRpcChannelReply(RpcMessage msg, Member destination) { try { //avoid circular loop if ( msg instanceof RpcMessage.NoRpcChannelReply) return; RpcMessage.NoRpcChannelReply reply = new RpcMessage.NoRpcChannelReply(msg.rpcId,msg.uuid); send(new Member[]{destination},reply,Channel.SEND_OPTIONS_ASYNCHRONOUS); } catch ( Exception x ) { log.error("Unable to find rpc channel, failed to send NoRpcChannelReply.",x); } } /** * memberAdded gets invoked by the interceptor below the channel * and the channel will broadcast it to the membership listeners * @param member Member - the new member */ @Override public void memberAdded(Member member) { //notify upwards for (int i=0; i<membershipListeners.size(); i++ ) { MembershipListener membershipListener = (MembershipListener)membershipListeners.get(i); if (membershipListener != null) membershipListener.memberAdded(member); } } /** * memberDisappeared gets invoked by the interceptor below the channel * and the channel will broadcast it to the membership listeners * @param member Member - the member that left or crashed */ @Override public void memberDisappeared(Member member) { //notify upwards for (int i=0; i<membershipListeners.size(); i++ ) { MembershipListener membershipListener = (MembershipListener)membershipListeners.get(i); if (membershipListener != null) membershipListener.memberDisappeared(member); } } /** * Sets up the default implementation interceptor stack * if no interceptors have been added * @throws ChannelException */ protected synchronized void setupDefaultStack() throws ChannelException { if ( getFirstInterceptor() != null && ((getFirstInterceptor().getNext() instanceof ChannelCoordinator))) { ChannelInterceptor interceptor = null; Class<?> clazz = null; try { clazz = Class.forName("org.apache.catalina.tribes.group.interceptors.MessageDispatch15Interceptor", true,GroupChannel.class.getClassLoader()); clazz.newInstance(); } catch ( Throwable x ) { clazz = MessageDispatchInterceptor.class; }//catch try { interceptor = (ChannelInterceptor) clazz.newInstance(); } catch (Exception x) { throw new ChannelException("Unable to add MessageDispatchInterceptor to interceptor chain.",x); } this.addInterceptor(interceptor); } } /** * Validates the option flags that each interceptor is using and reports * an error if two interceptor share the same flag. * @throws ChannelException */ protected void checkOptionFlags() throws ChannelException { StringBuilder conflicts = new StringBuilder(); ChannelInterceptor first = interceptors; while ( first != null ) { int flag = first.getOptionFlag(); if ( flag != 0 ) { ChannelInterceptor next = first.getNext(); while ( next != null ) { int nflag = next.getOptionFlag(); if (nflag!=0 && (((flag & nflag) == flag ) || ((flag & nflag) == nflag)) ) { conflicts.append("["); conflicts.append(first.getClass().getName()); conflicts.append(":"); conflicts.append(flag); conflicts.append(" == "); conflicts.append(next.getClass().getName()); conflicts.append(":"); conflicts.append(nflag); conflicts.append("] "); }//end if next = next.getNext(); }//while }//end if first = first.getNext(); }//while if ( conflicts.length() > 0 ) throw new ChannelException("Interceptor option flag conflict: "+conflicts.toString()); } /** * Starts the channel * @param svc int - what service to start * @throws ChannelException * @see org.apache.catalina.tribes.Channel#start(int) */ @Override public synchronized void start(int svc) throws ChannelException { setupDefaultStack(); if (optionCheck) checkOptionFlags(); super.start(svc); if ( hbthread == null && heartbeat ) { hbthread = new HeartbeatThread(this,heartbeatSleeptime); hbthread.start(); } } /** * Stops the channel * @param svc int * @throws ChannelException * @see org.apache.catalina.tribes.Channel#stop(int) */ @Override public synchronized void stop(int svc) throws ChannelException { if (hbthread != null) { hbthread.stopHeartbeat(); hbthread = null; } super.stop(svc); } /** * Returns the first interceptor of the stack. Useful for traversal. * @return ChannelInterceptor */ public ChannelInterceptor getFirstInterceptor() { if (interceptors != null) return interceptors; else return coordinator; } /** * Returns the channel receiver component * @return ChannelReceiver */ @Override public ChannelReceiver getChannelReceiver() { return coordinator.getClusterReceiver(); } /** * Returns the channel sender component * @return ChannelSender */ @Override public ChannelSender getChannelSender() { return coordinator.getClusterSender(); } /** * Returns the membership service component * @return MembershipService */ @Override public MembershipService getMembershipService() { return coordinator.getMembershipService(); } /** * Sets the channel receiver component * @param clusterReceiver ChannelReceiver */ @Override public void setChannelReceiver(ChannelReceiver clusterReceiver) { coordinator.setClusterReceiver(clusterReceiver); } /** * Sets the channel sender component * @param clusterSender ChannelSender */ @Override public void setChannelSender(ChannelSender clusterSender) { coordinator.setClusterSender(clusterSender); } /** * Sets the membership component * @param membershipService MembershipService */ @Override public void setMembershipService(MembershipService membershipService) { coordinator.setMembershipService(membershipService); } /** * Adds a membership listener to the channel.<br> * Membership listeners are uniquely identified using the equals(Object) method * @param membershipListener MembershipListener */ @Override public void addMembershipListener(MembershipListener membershipListener) { if (!this.membershipListeners.contains(membershipListener) ) this.membershipListeners.add(membershipListener); } /** * Removes a membership listener from the channel.<br> * Membership listeners are uniquely identified using the equals(Object) method * @param membershipListener MembershipListener */ @Override public void removeMembershipListener(MembershipListener membershipListener) { membershipListeners.remove(membershipListener); } /** * Adds a channel listener to the channel.<br> * Channel listeners are uniquely identified using the equals(Object) method * @param channelListener ChannelListener */ @Override public void addChannelListener(ChannelListener channelListener) { if (!this.channelListeners.contains(channelListener) ) { this.channelListeners.add(channelListener); } else { throw new IllegalArgumentException("Listener already exists:"+channelListener+"["+channelListener.getClass().getName()+"]"); } } /** * * Removes a channel listener from the channel.<br> * Channel listeners are uniquely identified using the equals(Object) method * @param channelListener ChannelListener */ @Override public void removeChannelListener(ChannelListener channelListener) { channelListeners.remove(channelListener); } /** * Returns an iterator of all the interceptors in this stack * @return Iterator */ @Override public Iterator<ChannelInterceptor> getInterceptors() { return new InterceptorIterator(this.getNext(),this.coordinator); } /** * Enables/disables the option check<br> * Setting this to true, will make the GroupChannel perform a conflict check * on the interceptors. If two interceptors are using the same option flag * and throw an error upon start. * @param optionCheck boolean */ public void setOptionCheck(boolean optionCheck) { this.optionCheck = optionCheck; } /** * Configure local heartbeat sleep time<br> * Only used when <code>getHeartbeat()==true</code> * @param heartbeatSleeptime long - time in milliseconds to sleep between heartbeats */ public void setHeartbeatSleeptime(long heartbeatSleeptime) { this.heartbeatSleeptime = heartbeatSleeptime; } /** * Enables or disables local heartbeat. * if <code>setHeartbeat(true)</code> is invoked then the channel will start an internal * thread to invoke <code>Channel.heartbeat()</code> every <code>getHeartbeatSleeptime</code> milliseconds * @param heartbeat boolean */ @Override public void setHeartbeat(boolean heartbeat) { this.heartbeat = heartbeat; } /** * @see #setOptionCheck(boolean) * @return boolean */ public boolean getOptionCheck() { return optionCheck; } /** * @see #setHeartbeat(boolean) * @return boolean */ public boolean getHeartbeat() { return heartbeat; } /** * Returns the sleep time in milliseconds that the internal heartbeat will * sleep in between invocations of <code>Channel.heartbeat()</code> * @return long */ public long getHeartbeatSleeptime() { return heartbeatSleeptime; } /** * * <p>Title: Interceptor Iterator</p> * * <p>Description: An iterator to loop through the interceptors in a channel</p> * * @version 1.0 */ public static class InterceptorIterator implements Iterator<ChannelInterceptor> { private final ChannelInterceptor end; private ChannelInterceptor start; public InterceptorIterator(ChannelInterceptor start, ChannelInterceptor end) { this.end = end; this.start = start; } @Override public boolean hasNext() { return start!=null && start != end; } @Override public ChannelInterceptor next() { ChannelInterceptor result = null; if ( hasNext() ) { result = start; start = start.getNext(); } return result; } @Override public void remove() { //empty operation } } /** * * <p>Title: Internal heartbeat thread</p> * * <p>Description: if <code>Channel.getHeartbeat()==true</code> then a thread of this class * is created</p> * * @version 1.0 */ public static class HeartbeatThread extends Thread { private static final Log log = LogFactory.getLog(HeartbeatThread.class); protected static int counter = 1; protected static synchronized int inc() { return counter++; } protected volatile boolean doRun = true; protected final GroupChannel channel; protected final long sleepTime; public HeartbeatThread(GroupChannel channel, long sleepTime) { super(); this.setPriority(MIN_PRIORITY); setName("GroupChannel-Heartbeat-"+inc()); setDaemon(true); this.channel = channel; this.sleepTime = sleepTime; } public void stopHeartbeat() { doRun = false; interrupt(); } @Override public void run() { while (doRun) { try { Thread.sleep(sleepTime); channel.heartbeat(); } catch ( InterruptedException x ) { // Ignore. Probably triggered by a call to stopHeartbeat(). // In the highly unlikely event it was a different trigger, // simply ignore it and continue. } catch ( Exception x ) { log.error("Unable to send heartbeat through Tribes interceptor stack. Will try to sleep again.",x); }//catch }//while }//run }//HeartbeatThread }
53,869
Bug 53869 Performance tuning solution to resolve too many cascaded JspContextWrapper issue
null
resolved fixed
ce55f25
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-25T12:06:04Z
2012-09-13T18:13:20Z
java/org/apache/jasper/runtime/JspContextWrapper.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.runtime; import java.io.IOException; import java.io.Writer; 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 javax.el.ELContext; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspContext; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.el.ELException; import javax.servlet.jsp.el.ExpressionEvaluator; import javax.servlet.jsp.el.VariableResolver; import javax.servlet.jsp.tagext.BodyContent; import javax.servlet.jsp.tagext.VariableInfo; import org.apache.jasper.compiler.Localizer; /** * Implementation of a JSP Context Wrapper. * * The JSP Context Wrapper is a JspContext created and maintained by a tag * handler implementation. It wraps the Invoking JSP Context, that is, the * JspContext instance passed to the tag handler by the invoking page via * setJspContext(). * * @author Kin-man Chung * @author Jan Luehe * @author Jacob Hookom */ @SuppressWarnings("deprecation") // Have to support old JSP EL API public class JspContextWrapper extends PageContext implements VariableResolver { // Invoking JSP context private final PageContext invokingJspCtxt; private final transient HashMap<String, Object> pageAttributes; // ArrayList of NESTED scripting variables private final ArrayList<String> nestedVars; // ArrayList of AT_BEGIN scripting variables private final ArrayList<String> atBeginVars; // ArrayList of AT_END scripting variables private final ArrayList<String> atEndVars; private final Map<String,String> aliases; private final HashMap<String, Object> originalNestedVars; public JspContextWrapper(JspContext jspContext, ArrayList<String> nestedVars, ArrayList<String> atBeginVars, ArrayList<String> atEndVars, Map<String,String> aliases) { this.invokingJspCtxt = (PageContext) jspContext; this.nestedVars = nestedVars; this.atBeginVars = atBeginVars; this.atEndVars = atEndVars; this.pageAttributes = new HashMap<>(16); this.aliases = aliases; if (nestedVars != null) { this.originalNestedVars = new HashMap<>(nestedVars.size()); } else { this.originalNestedVars = null; } syncBeginTagFile(); } @Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException { } @Override public Object getAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return pageAttributes.get(name); } @Override public Object getAttribute(String name, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { return pageAttributes.get(name); } return invokingJspCtxt.getAttribute(name, scope); } @Override public void setAttribute(String name, Object value) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (value != null) { pageAttributes.put(name, value); } else { removeAttribute(name, PAGE_SCOPE); } } @Override public void setAttribute(String name, Object value, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { if (value != null) { pageAttributes.put(name, value); } else { removeAttribute(name, PAGE_SCOPE); } } else { invokingJspCtxt.setAttribute(name, value, scope); } } @Override public Object findAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } Object o = pageAttributes.get(name); if (o == null) { o = invokingJspCtxt.getAttribute(name, REQUEST_SCOPE); if (o == null) { if (getSession() != null) { o = invokingJspCtxt.getAttribute(name, SESSION_SCOPE); } if (o == null) { o = invokingJspCtxt.getAttribute(name, APPLICATION_SCOPE); } } } return o; } @Override public void removeAttribute(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } pageAttributes.remove(name); invokingJspCtxt.removeAttribute(name, REQUEST_SCOPE); if (getSession() != null) { invokingJspCtxt.removeAttribute(name, SESSION_SCOPE); } invokingJspCtxt.removeAttribute(name, APPLICATION_SCOPE); } @Override public void removeAttribute(String name, int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (scope == PAGE_SCOPE) { pageAttributes.remove(name); } else { invokingJspCtxt.removeAttribute(name, scope); } } @Override public int getAttributesScope(String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (pageAttributes.get(name) != null) { return PAGE_SCOPE; } else { return invokingJspCtxt.getAttributesScope(name); } } @Override public Enumeration<String> getAttributeNamesInScope(int scope) { if (scope == PAGE_SCOPE) { return Collections.enumeration(pageAttributes.keySet()); } return invokingJspCtxt.getAttributeNamesInScope(scope); } @Override public void release() { invokingJspCtxt.release(); } @Override public JspWriter getOut() { return invokingJspCtxt.getOut(); } @Override public HttpSession getSession() { return invokingJspCtxt.getSession(); } @Override public Object getPage() { return invokingJspCtxt.getPage(); } @Override public ServletRequest getRequest() { return invokingJspCtxt.getRequest(); } @Override public ServletResponse getResponse() { return invokingJspCtxt.getResponse(); } @Override public Exception getException() { return invokingJspCtxt.getException(); } @Override public ServletConfig getServletConfig() { return invokingJspCtxt.getServletConfig(); } @Override public ServletContext getServletContext() { return invokingJspCtxt.getServletContext(); } @Override public void forward(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.forward(relativeUrlPath); } @Override public void include(String relativeUrlPath) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath); } @Override public void include(String relativeUrlPath, boolean flush) throws ServletException, IOException { invokingJspCtxt.include(relativeUrlPath, false); } @Override @Deprecated public VariableResolver getVariableResolver() { return this; } @Override public BodyContent pushBody() { return invokingJspCtxt.pushBody(); } @Override public JspWriter pushBody(Writer writer) { return invokingJspCtxt.pushBody(writer); } @Override public JspWriter popBody() { return invokingJspCtxt.popBody(); } @Override @Deprecated public ExpressionEvaluator getExpressionEvaluator() { return invokingJspCtxt.getExpressionEvaluator(); } @Override public void handlePageException(Exception ex) throws IOException, ServletException { // Should never be called since handleException() called with a // Throwable in the generated servlet. handlePageException((Throwable) ex); } @Override public void handlePageException(Throwable t) throws IOException, ServletException { invokingJspCtxt.handlePageException(t); } /** * VariableResolver interface */ @Override @Deprecated public Object resolveVariable(String pName) throws ELException { ELContext ctx = this.getELContext(); return ctx.getELResolver().getValue(ctx, null, pName); } /** * Synchronize variables at begin of tag file */ public void syncBeginTagFile() { saveNestedVariables(); } /** * Synchronize variables before fragment invocation */ public void syncBeforeInvoke() { copyTagToPageScope(VariableInfo.NESTED); copyTagToPageScope(VariableInfo.AT_BEGIN); } /** * Synchronize variables at end of tag file */ public void syncEndTagFile() { copyTagToPageScope(VariableInfo.AT_BEGIN); copyTagToPageScope(VariableInfo.AT_END); restoreNestedVariables(); } /** * Copies the variables of the given scope from the virtual page scope of * this JSP context wrapper to the page scope of the invoking JSP context. * * @param scope * variable scope (one of NESTED, AT_BEGIN, or AT_END) */ private void copyTagToPageScope(int scope) { Iterator<String> iter = null; switch (scope) { case VariableInfo.NESTED: if (nestedVars != null) { iter = nestedVars.iterator(); } break; case VariableInfo.AT_BEGIN: if (atBeginVars != null) { iter = atBeginVars.iterator(); } break; case VariableInfo.AT_END: if (atEndVars != null) { iter = atEndVars.iterator(); } break; } while ((iter != null) && iter.hasNext()) { String varName = iter.next(); Object obj = getAttribute(varName); varName = findAlias(varName); if (obj != null) { invokingJspCtxt.setAttribute(varName, obj); } else { invokingJspCtxt.removeAttribute(varName, PAGE_SCOPE); } } } /** * Saves the values of any NESTED variables that are present in the invoking * JSP context, so they can later be restored. */ private void saveNestedVariables() { if (nestedVars != null) { Iterator<String> iter = nestedVars.iterator(); while (iter.hasNext()) { String varName = iter.next(); varName = findAlias(varName); Object obj = invokingJspCtxt.getAttribute(varName); if (obj != null) { originalNestedVars.put(varName, obj); } } } } /** * Restores the values of any NESTED variables in the invoking JSP context. */ private void restoreNestedVariables() { if (nestedVars != null) { Iterator<String> iter = nestedVars.iterator(); while (iter.hasNext()) { String varName = iter.next(); varName = findAlias(varName); Object obj = originalNestedVars.get(varName); if (obj != null) { invokingJspCtxt.setAttribute(varName, obj); } else { invokingJspCtxt.removeAttribute(varName, PAGE_SCOPE); } } } } /** * Checks to see if the given variable name is used as an alias, and if so, * returns the variable name for which it is used as an alias. * * @param varName * The variable name to check * @return The variable name for which varName is used as an alias, or * varName if it is not being used as an alias */ private String findAlias(String varName) { if (aliases == null) return varName; String alias = aliases.get(varName); if (alias == null) { return varName; } return alias; } //private ELContextImpl elContext; @Override public ELContext getELContext() { // instead decorate!!! return this.invokingJspCtxt.getELContext(); /* if (this.elContext != null) { JspFactory jspFact = JspFactory.getDefaultFactory(); ServletContext servletContext = this.getServletContext(); JspApplicationContextImpl jspCtx = (JspApplicationContextImpl) jspFact .getJspApplicationContext(servletContext); this.elContext = jspCtx.createELContext(this); } return this.elContext; */ } }
54,496
Bug 54496 ..tribes.membership.MemberImpl.toString() might be better using .getClass().getName()
public String toString() { StringBuilder buf = new StringBuilder("org.apache.catalina.tribes.membership.MemberImpl["); Might be better to use .getClass().getName() to cover StaticMember and any other sub-classes that might arise.
resolved fixed
e1e4e4e
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-01-28T15:18:04Z
2013-01-26T00:26:40Z
java/org/apache/catalina/tribes/membership/MemberImpl.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.membership; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Arrays; import org.apache.catalina.tribes.Member; import org.apache.catalina.tribes.io.XByteBuffer; import org.apache.catalina.tribes.transport.SenderState; /** * A <b>membership</b> implementation using simple multicast. * This is the representation of a multicast member. * Carries the host, and port of the this or other cluster nodes. * * @author Filip Hanik * @version $Id$ */ public class MemberImpl implements Member, java.io.Externalizable { /** * Should a call to getName or getHostName try to do a DNS lookup? * default is false */ public static final boolean DO_DNS_LOOKUPS = Boolean.parseBoolean(System.getProperty("org.apache.catalina.tribes.dns_lookups","false")); public static final transient byte[] TRIBES_MBR_BEGIN = new byte[] {84, 82, 73, 66, 69, 83, 45, 66, 1, 0}; public static final transient byte[] TRIBES_MBR_END = new byte[] {84, 82, 73, 66, 69, 83, 45, 69, 1, 0}; /** * The listen host for this member */ protected byte[] host; protected transient String hostname; /** * The tcp listen port for this member */ protected int port; /** * The udp listen port for this member */ protected int udpPort = -1; /** * The tcp/SSL listen port for this member */ protected int securePort = -1; /** * Counter for how many broadcast messages have been sent from this member */ protected int msgCount = 0; /** * The number of milliseconds since this member was * created, is kept track of using the start time */ protected long memberAliveTime = 0; /** * For the local member only */ protected transient long serviceStartTime; /** * To avoid serialization over and over again, once the local dataPkg * has been set, we use that to transmit data */ protected transient byte[] dataPkg = null; /** * Unique session Id for this member */ protected byte[] uniqueId = new byte[16]; /** * Custom payload that an app framework can broadcast * Also used to transport stop command. */ protected byte[] payload = new byte[0]; /** * Command, so that the custom payload doesn't have to be used * This is for internal tribes use, such as SHUTDOWN_COMMAND */ protected byte[] command = new byte[0]; /** * Domain if we want to filter based on domain. */ protected byte[] domain = new byte[0]; /** * Empty constructor for serialization */ public MemberImpl() { } /** * Construct a new member object * @param host - the tcp listen host * @param port - the tcp listen port * @param aliveTime - the number of milliseconds since this member was created */ public MemberImpl(String host, int port, long aliveTime) throws IOException { setHostname(host); this.port = port; this.memberAliveTime=aliveTime; } public MemberImpl(String host, int port, long aliveTime, byte[] payload) throws IOException { this(host,port,aliveTime); setPayload(payload); } @Override public boolean isReady() { return SenderState.getSenderState(this).isReady(); } @Override public boolean isSuspect() { return SenderState.getSenderState(this).isSuspect(); } @Override public boolean isFailing() { return SenderState.getSenderState(this).isFailing(); } /** * Increment the message count. */ protected void inc() { msgCount++; } /** * Create a data package to send over the wire representing this member. * This is faster than serialization. * @return - the bytes for this member deserialized */ public byte[] getData() { return getData(true); } @Override public byte[] getData(boolean getalive) { return getData(getalive,false); } @Override public int getDataLength() { return TRIBES_MBR_BEGIN.length+ //start pkg 4+ //data length 8+ //alive time 4+ //port 4+ //secure port 4+ //udp port 1+ //host length host.length+ //host 4+ //command length command.length+ //command 4+ //domain length domain.length+ //domain 16+ //unique id 4+ //payload length payload.length+ //payload TRIBES_MBR_END.length; //end pkg } @Override public byte[] getData(boolean getalive, boolean reset) { if ( reset ) dataPkg = null; //look in cache first if ( dataPkg!=null ) { if ( getalive ) { //you'd be surprised, but System.currentTimeMillis //shows up on the profiler long alive=System.currentTimeMillis()-getServiceStartTime(); XByteBuffer.toBytes(alive, dataPkg, TRIBES_MBR_BEGIN.length+4); } return dataPkg; } //package looks like //start package TRIBES_MBR_BEGIN.length //package length - 4 bytes //alive - 8 bytes //port - 4 bytes //secure port - 4 bytes //udp port - 4 bytes //host length - 1 byte //host - hl bytes //clen - 4 bytes //command - clen bytes //dlen - 4 bytes //domain - dlen bytes //uniqueId - 16 bytes //payload length - 4 bytes //payload plen bytes //end package TRIBES_MBR_END.length byte[] addr = host; long alive=System.currentTimeMillis()-getServiceStartTime(); byte hl = (byte)addr.length; byte[] data = new byte[getDataLength()]; int bodylength = (getDataLength() - TRIBES_MBR_BEGIN.length - TRIBES_MBR_END.length - 4); int pos = 0; //TRIBES_MBR_BEGIN System.arraycopy(TRIBES_MBR_BEGIN,0,data,pos,TRIBES_MBR_BEGIN.length); pos += TRIBES_MBR_BEGIN.length; //body length XByteBuffer.toBytes(bodylength,data,pos); pos += 4; //alive data XByteBuffer.toBytes(alive,data,pos); pos += 8; //port XByteBuffer.toBytes(port,data,pos); pos += 4; //secure port XByteBuffer.toBytes(securePort,data,pos); pos += 4; //udp port XByteBuffer.toBytes(udpPort,data,pos); pos += 4; //host length data[pos++] = hl; //host System.arraycopy(addr,0,data,pos,addr.length); pos+=addr.length; //clen - 4 bytes XByteBuffer.toBytes(command.length,data,pos); pos+=4; //command - clen bytes System.arraycopy(command,0,data,pos,command.length); pos+=command.length; //dlen - 4 bytes XByteBuffer.toBytes(domain.length,data,pos); pos+=4; //domain - dlen bytes System.arraycopy(domain,0,data,pos,domain.length); pos+=domain.length; //unique Id System.arraycopy(uniqueId,0,data,pos,uniqueId.length); pos+=uniqueId.length; //payload XByteBuffer.toBytes(payload.length,data,pos); pos+=4; System.arraycopy(payload,0,data,pos,payload.length); pos+=payload.length; //TRIBES_MBR_END System.arraycopy(TRIBES_MBR_END,0,data,pos,TRIBES_MBR_END.length); pos += TRIBES_MBR_END.length; //create local data dataPkg = data; return data; } /** * Deserializes a member from data sent over the wire * @param data - the bytes received * @return a member object. */ public static Member getMember(byte[] data, MemberImpl member) { return getMember(data,0,data.length,member); } public static Member getMember(byte[] data, int offset, int length, MemberImpl member) { //package looks like //start package TRIBES_MBR_BEGIN.length //package length - 4 bytes //alive - 8 bytes //port - 4 bytes //secure port - 4 bytes //udp port - 4 bytes //host length - 1 byte //host - hl bytes //clen - 4 bytes //command - clen bytes //dlen - 4 bytes //domain - dlen bytes //uniqueId - 16 bytes //payload length - 4 bytes //payload plen bytes //end package TRIBES_MBR_END.length int pos = offset; if (XByteBuffer.firstIndexOf(data,offset,TRIBES_MBR_BEGIN)!=pos) { throw new IllegalArgumentException("Invalid package, should start with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_BEGIN)); } if ( length < (TRIBES_MBR_BEGIN.length+4) ) { throw new ArrayIndexOutOfBoundsException("Member package to small to validate."); } pos += TRIBES_MBR_BEGIN.length; int bodylength = XByteBuffer.toInt(data,pos); pos += 4; if ( length < (bodylength+4+TRIBES_MBR_BEGIN.length+TRIBES_MBR_END.length) ) { throw new ArrayIndexOutOfBoundsException("Not enough bytes in member package."); } int endpos = pos+bodylength; if (XByteBuffer.firstIndexOf(data,endpos,TRIBES_MBR_END)!=endpos) { throw new IllegalArgumentException("Invalid package, should end with:"+org.apache.catalina.tribes.util.Arrays.toString(TRIBES_MBR_END)); } byte[] alived = new byte[8]; System.arraycopy(data, pos, alived, 0, 8); pos += 8; byte[] portd = new byte[4]; System.arraycopy(data, pos, portd, 0, 4); pos += 4; byte[] sportd = new byte[4]; System.arraycopy(data, pos, sportd, 0, 4); pos += 4; byte[] uportd = new byte[4]; System.arraycopy(data, pos, uportd, 0, 4); pos += 4; byte hl = data[pos++]; byte[] addr = new byte[hl]; System.arraycopy(data, pos, addr, 0, hl); pos += hl; int cl = XByteBuffer.toInt(data, pos); pos += 4; byte[] command = new byte[cl]; System.arraycopy(data, pos, command, 0, command.length); pos += command.length; int dl = XByteBuffer.toInt(data, pos); pos += 4; byte[] domain = new byte[dl]; System.arraycopy(data, pos, domain, 0, domain.length); pos += domain.length; byte[] uniqueId = new byte[16]; System.arraycopy(data, pos, uniqueId, 0, 16); pos += 16; int pl = XByteBuffer.toInt(data, pos); pos += 4; byte[] payload = new byte[pl]; System.arraycopy(data, pos, payload, 0, payload.length); pos += payload.length; member.setHost(addr); member.setPort(XByteBuffer.toInt(portd, 0)); member.setSecurePort(XByteBuffer.toInt(sportd, 0)); member.setUdpPort(XByteBuffer.toInt(uportd, 0)); member.setMemberAliveTime(XByteBuffer.toLong(alived, 0)); member.setUniqueId(uniqueId); member.payload = payload; member.domain = domain; member.command = command; member.dataPkg = new byte[length]; System.arraycopy(data, offset, member.dataPkg, 0, length); return member; } public static Member getMember(byte[] data) { return getMember(data,new MemberImpl()); } public static Member getMember(byte[] data, int offset, int length) { return getMember(data,offset,length,new MemberImpl()); } /** * Return the name of this object * @return a unique name to the cluster */ @Override public String getName() { return "tcp://"+getHostname()+":"+getPort(); } /** * Return the listen port of this member * @return - tcp listen port */ @Override public int getPort() { return this.port; } /** * Return the TCP listen host for this member * @return IP address or host name */ @Override public byte[] getHost() { return host; } public String getHostname() { if ( this.hostname != null ) return hostname; else { try { if (DO_DNS_LOOKUPS) this.hostname = java.net.InetAddress.getByAddress(host).getHostName(); else this.hostname = org.apache.catalina.tribes.util.Arrays.toString(host,0,host.length,true); return this.hostname; }catch ( IOException x ) { throw new RuntimeException("Unable to parse hostname.",x); } } } public int getMsgCount() { return this.msgCount; } /** * Contains information on how long this member has been online. * The result is the number of milli seconds this member has been * broadcasting its membership to the cluster. * @return nr of milliseconds since this member started. */ @Override public long getMemberAliveTime() { return memberAliveTime; } public long getServiceStartTime() { return serviceStartTime; } @Override public byte[] getUniqueId() { return uniqueId; } @Override public byte[] getPayload() { return payload; } @Override public byte[] getCommand() { return command; } @Override public byte[] getDomain() { return domain; } @Override public int getSecurePort() { return securePort; } @Override public int getUdpPort() { return udpPort; } @Override public void setMemberAliveTime(long time) { memberAliveTime=time; } /** * String representation of this object */ @Override public String toString() { StringBuilder buf = new StringBuilder("org.apache.catalina.tribes.membership.MemberImpl["); buf.append(getName()).append(","); buf.append(getHostname()).append(","); buf.append(port).append(", alive="); buf.append(memberAliveTime).append(", "); buf.append("securePort=").append(securePort).append(", "); buf.append("UDP Port=").append(udpPort).append(", "); buf.append("id=").append(bToS(this.uniqueId)).append(", "); buf.append("payload=").append(bToS(this.payload,8)).append(", "); buf.append("command=").append(bToS(this.command,8)).append(", "); buf.append("domain=").append(bToS(this.domain,8)).append(", "); buf.append("]"); return buf.toString(); } public static String bToS(byte[] data) { return bToS(data,data.length); } public static String bToS(byte[] data, int max) { StringBuilder buf = new StringBuilder(4*16); buf.append("{"); for (int i=0; data!=null && i<data.length; i++ ) { buf.append(String.valueOf(data[i])).append(" "); if ( i==max ) { buf.append("...("+data.length+")"); break; } } buf.append("}"); return buf.toString(); } /** * @see java.lang.Object#hashCode() * @return The hash code */ @Override public int hashCode() { return getHost()[0]+getHost()[1]+getHost()[2]+getHost()[3]; } /** * Returns true if the param o is a McastMember with the same name * @param o */ @Override public boolean equals(Object o) { if ( o instanceof MemberImpl ) { return Arrays.equals(this.getHost(),((MemberImpl)o).getHost()) && this.getPort() == ((MemberImpl)o).getPort() && Arrays.equals(this.getUniqueId(),((MemberImpl)o).getUniqueId()); } else return false; } public void setHost(byte[] host) { this.host = host; } public void setHostname(String host) throws IOException { hostname = host; this.host = java.net.InetAddress.getByName(host).getAddress(); } public void setMsgCount(int msgCount) { this.msgCount = msgCount; } public void setPort(int port) { this.port = port; this.dataPkg = null; } public void setServiceStartTime(long serviceStartTime) { this.serviceStartTime = serviceStartTime; } public void setUniqueId(byte[] uniqueId) { this.uniqueId = uniqueId!=null?uniqueId:new byte[16]; getData(true,true); } @Override public void setPayload(byte[] payload) { byte[] oldpayload = this.payload; this.payload = payload!=null?payload:new byte[0]; if ( this.getData(true,true).length > McastServiceImpl.MAX_PACKET_SIZE ) { this.payload = oldpayload; throw new IllegalArgumentException("Payload is to large for tribes to handle."); } } @Override public void setCommand(byte[] command) { this.command = command!=null?command:new byte[0]; getData(true,true); } public void setDomain(byte[] domain) { this.domain = domain!=null?domain:new byte[0]; getData(true,true); } public void setSecurePort(int securePort) { this.securePort = securePort; this.dataPkg = null; } public void setUdpPort(int port) { this.udpPort = port; this.dataPkg = null; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { int length = in.readInt(); byte[] message = new byte[length]; in.readFully(message); getMember(message,this); } @Override public void writeExternal(ObjectOutput out) throws IOException { byte[] data = this.getData(); out.writeInt(data.length); out.write(data); } }
54,497
Bug 54497 RuntimeException in WebappClassLoader.checkThreadLocalMapForLeaks() causes LifecycleException
Observed this when testing Tomcat trunk at r1438747, at WinXP 32-bit, JDK 7u11. (running TestWsWebSocketContainer with APR, Tomcat-Native 1.1.26 RC) There occurred an NPE in WebappClassLoader.checkThreadLocalMapForLeaks(). It was uncaught and caused LifecycleException and ultimately a failure to stop Tomcat. =============== In stderr: SEVERE: A child container failed during stop java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to stop component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]] at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:252) at java.util.concurrent.FutureTask.get(FutureTask.java:111) at org.apache.catalina.core.ContainerBase.stopInternal(ContainerBase.java:974) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232) at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1404) at org.apache.catalina.core.ContainerBase$StopChild.call(ContainerBase.java:1393) at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:334) at java.util.concurrent.FutureTask.run(FutureTask.java:166) 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) Caused by: org.apache.catalina.LifecycleException: Failed to stop component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[]] at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:236) ... 7 more Caused by: org.apache.catalina.LifecycleException: Failed to stop component [WebappLoader[]] at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:236) at org.apache.catalina.core.StandardContext.stopInternal(StandardContext.java:5365) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232) ... 7 more Caused by: java.lang.NullPointerException at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:54) at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) at java.lang.reflect.Field.get(Field.java:372) at org.apache.catalina.loader.WebappClassLoader.checkThreadLocalMapForLeaks(WebappClassLoader.java:2247) at org.apache.catalina.loader.WebappClassLoader.checkThreadLocalsForLeaks(WebappClassLoader.java:2188) at org.apache.catalina.loader.WebappClassLoader.clearReferences(WebappClassLoader.java:1731) at org.apache.catalina.loader.WebappClassLoader.stop(WebappClassLoader.java:1641) at org.apache.catalina.loader.WebappLoader.stopInternal(WebappLoader.java:491) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232) ... 9 more =============== In testcase: Testcase: testSmallTextBufferClientTextMessage took 2,328 sec Caused an ERROR Failed to stop component [StandardServer[-1]] org.apache.catalina.LifecycleException: Failed to stop component [StandardServer[-1]] at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:236) at org.apache.catalina.startup.Tomcat.stop(Tomcat.java:336) at org.apache.catalina.startup.TomcatBaseTest.tearDown(TomcatBaseTest.java:163) Caused by: org.apache.catalina.LifecycleException: Failed to stop component [StandardService[Tomcat]] at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:236) at org.apache.catalina.core.StandardServer.stopInternal(StandardServer.java:766) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232) Caused by: org.apache.catalina.LifecycleException: Failed to stop component [StandardEngine[Tomcat]] at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:236) at org.apache.catalina.core.StandardService.stopInternal(StandardService.java:501) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232) Caused by: org.apache.catalina.LifecycleException: A child container failed during stop at org.apache.catalina.core.ContainerBase.stopInternal(ContainerBase.java:981) at org.apache.catalina.util.LifecycleBase.stop(LifecycleBase.java:232) =============== Thoughts: 1. We should catch throwables in those checkFor**Leaks methods. It should not cause a "failed to stop component" failure. 2. In that method there are many calls to "table[j]". The array member should be evaluated only once, so that it does not become null unexpectedly.
resolved fixed
ea16bda
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-01T12:45:41Z
2013-01-26T03:13:20Z
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.InvocationTargetException; 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 (SecurityException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } catch (NoSuchFieldException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } catch (ClassNotFoundException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } catch (IllegalArgumentException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } catch (IllegalAccessException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } catch (InvocationTargetException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } catch (NoSuchMethodException e) { log.warn(sm.getString("webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), e); } } /** * 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,513
Bug 54513 NullPointerException in AprEndpoint$Poller.run
Trunk at r1441188, running the test suite with APR connector, Native 1.1.26 Windows 32-bit with JDK 7u11. I encountered the following when running org.apache.catalina.loader.TestVirtualContext test On second re-run of the test the same issue happened, so it is as if there is something specific here. I have not encountered the issue with the rest of testsuite yet. [[[ Feb 01, 2013 2:07:26 AM org.apache.tomcat.util.net.AprEndpoint$Poller run WARNING: Unexpected poller error java.lang.NullPointerException at org.apache.tomcat.util.net.AprEndpoint$AprSocketWrapper.access$200(AprEndpoint.java:2198) at org.apache.tomcat.util.net.AprEndpoint$Poller.run(AprEndpoint.java:1632) at java.lang.Thread.run(Thread.java:722) ]]] The code at AprEndpoint$Poller.run(AprEndpoint.java:1632) is 1628 for (int n = 0; n < rv; n++) { 1629 timeouts.remove(desc[n*2+1]); 1630 AprSocketWrapper wrapper = connections.get( 1631 Long.valueOf(desc[n*2+1])); 1632 wrapper.pollerFlags = wrapper.pollerFlags & ~((int) desc[n*2]); I suspect that "wrapper" is null here. The above code is specific to Tomcat trunk and is not present in 7.0.x. When this happened, the test hung for 15 minutes (1000 secs) waiting on a socket read. When time out passed, it continued to run all the other tests. [[[ Testcase: testAdditionalWebInfClassesPaths took 1 006,735 sec Caused an ERROR Read timed out java.net.SocketTimeoutException: Read timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:150) at java.net.SocketInputStream.read(SocketInputStream.java:121) at java.io.BufferedInputStream.fill(BufferedInputStream.java:235) at java.io.BufferedInputStream.read1(BufferedInputStream.java:275) at java.io.BufferedInputStream.read(BufferedInputStream.java:334) at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:633) at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:579) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1322) at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:468) at org.apache.catalina.startup.TomcatBaseTest.methodUrl(TomcatBaseTest.java:247) at org.apache.catalina.startup.TomcatBaseTest.getUrl(TomcatBaseTest.java:219) at org.apache.catalina.startup.TomcatBaseTest.getUrl(TomcatBaseTest.java:213) at org.apache.catalina.startup.TomcatBaseTest.getUrl(TomcatBaseTest.java:202) at org.apache.catalina.loader.TestVirtualContext.assertPageContains(TestVirtualContext.java:326) at org.apache.catalina.loader.TestVirtualContext.assertPageContains(TestVirtualContext.java:320) at org.apache.catalina.loader.TestVirtualContext.testAdditionalWebInfClassesPaths(TestVirtualContext.java:311) ]]]
resolved fixed
bbb13f6
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-02T20:38:29Z
2013-02-01T03:40:00Z
java/org/apache/tomcat/util/net/AprEndpoint.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.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.jni.Address; import org.apache.tomcat.jni.Error; import org.apache.tomcat.jni.File; import org.apache.tomcat.jni.Library; import org.apache.tomcat.jni.OS; import org.apache.tomcat.jni.Poll; import org.apache.tomcat.jni.Pool; import org.apache.tomcat.jni.SSL; import org.apache.tomcat.jni.SSLContext; import org.apache.tomcat.jni.SSLSocket; import org.apache.tomcat.jni.Sockaddr; import org.apache.tomcat.jni.Socket; import org.apache.tomcat.jni.Status; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.net.AbstractEndpoint.Acceptor.AcceptorState; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; /** * APR tailored thread pool, providing the following services: * <ul> * <li>Socket acceptor thread</li> * <li>Socket poller thread</li> * <li>Sendfile 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 */ public class AprEndpoint extends AbstractEndpoint { // -------------------------------------------------------------- Constants private static final Log log = LogFactory.getLog(AprEndpoint.class); // ----------------------------------------------------------------- Fields /** * Root APR memory pool. */ protected long rootPool = 0; /** * Server socket "pointer". */ protected long serverSock = 0; /** * APR memory pool for the server socket. */ protected long serverSockPool = 0; /** * SSL context. */ protected long sslContext = 0; protected ConcurrentLinkedQueue<SocketWrapper<Long>> waitingRequests = new ConcurrentLinkedQueue<>(); private Map<Long,AprSocketWrapper> connections = new ConcurrentHashMap<>(); // ------------------------------------------------------------ Constructor public AprEndpoint() { // Need to override the default for maxConnections to align it with what // was pollerSize (before the two were merged) setMaxConnections(8 * 1024); } // ------------------------------------------------------------- Properties /** * Defer accept. */ protected boolean deferAccept = true; public void setDeferAccept(boolean deferAccept) { this.deferAccept = deferAccept; } @Override public boolean getDeferAccept() { return deferAccept; } /** * Size of the sendfile (= concurrent files which can be served). */ protected int sendfileSize = 1 * 1024; public void setSendfileSize(int sendfileSize) { this.sendfileSize = sendfileSize; } public int getSendfileSize() { return sendfileSize; } /** * Handling of accepted sockets. */ protected Handler handler = null; public void setHandler(Handler handler ) { this.handler = handler; } public Handler getHandler() { return handler; } /** * Poll interval, in microseconds. The smaller the value, the more CPU the poller * will use, but the more responsive to activity it will be. */ protected int pollTime = 2000; public int getPollTime() { return pollTime; } public void setPollTime(int pollTime) { if (pollTime > 0) { this.pollTime = pollTime; } } /** * Use sendfile for sending static files. */ protected boolean useSendfile = Library.APR_HAS_SENDFILE; public void setUseSendfile(boolean useSendfile) { this.useSendfile = useSendfile; } @Override public boolean getUseSendfile() { return useSendfile; } /** * Allow comet request handling. */ protected boolean useComet = true; public void setUseComet(boolean useComet) { this.useComet = useComet; } @Override public boolean getUseComet() { return useComet; } @Override public boolean getUseCometTimeout() { return false; } // Not supported @Override public boolean getUsePolling() { return true; } // Always supported /** * Sendfile thread count. */ protected int sendfileThreadCount = 0; public void setSendfileThreadCount(int sendfileThreadCount) { this.sendfileThreadCount = sendfileThreadCount; } public int getSendfileThreadCount() { return sendfileThreadCount; } /** * The socket poller. */ protected Poller poller = null; public Poller getPoller() { return poller; } /** * The static file sender. */ protected Sendfile sendfile = null; public Sendfile getSendfile() { return sendfile; } /** * SSL protocols. */ protected String SSLProtocol = "all"; public String getSSLProtocol() { return SSLProtocol; } public void setSSLProtocol(String SSLProtocol) { this.SSLProtocol = SSLProtocol; } /** * SSL password (if a cert is encrypted, and no password has been provided, a callback * will ask for a password). */ protected String SSLPassword = null; public String getSSLPassword() { return SSLPassword; } public void setSSLPassword(String SSLPassword) { this.SSLPassword = SSLPassword; } /** * SSL cipher suite. */ protected String SSLCipherSuite = "ALL"; public String getSSLCipherSuite() { return SSLCipherSuite; } public void setSSLCipherSuite(String SSLCipherSuite) { this.SSLCipherSuite = SSLCipherSuite; } /** * SSL certificate file. */ protected String SSLCertificateFile = null; public String getSSLCertificateFile() { return SSLCertificateFile; } public void setSSLCertificateFile(String SSLCertificateFile) { this.SSLCertificateFile = SSLCertificateFile; } /** * SSL certificate key file. */ protected String SSLCertificateKeyFile = null; public String getSSLCertificateKeyFile() { return SSLCertificateKeyFile; } public void setSSLCertificateKeyFile(String SSLCertificateKeyFile) { this.SSLCertificateKeyFile = SSLCertificateKeyFile; } /** * SSL certificate chain file. */ protected String SSLCertificateChainFile = null; public String getSSLCertificateChainFile() { return SSLCertificateChainFile; } public void setSSLCertificateChainFile(String SSLCertificateChainFile) { this.SSLCertificateChainFile = SSLCertificateChainFile; } /** * SSL CA certificate path. */ protected String SSLCACertificatePath = null; public String getSSLCACertificatePath() { return SSLCACertificatePath; } public void setSSLCACertificatePath(String SSLCACertificatePath) { this.SSLCACertificatePath = SSLCACertificatePath; } /** * SSL CA certificate file. */ protected String SSLCACertificateFile = null; public String getSSLCACertificateFile() { return SSLCACertificateFile; } public void setSSLCACertificateFile(String SSLCACertificateFile) { this.SSLCACertificateFile = SSLCACertificateFile; } /** * SSL CA revocation path. */ protected String SSLCARevocationPath = null; public String getSSLCARevocationPath() { return SSLCARevocationPath; } public void setSSLCARevocationPath(String SSLCARevocationPath) { this.SSLCARevocationPath = SSLCARevocationPath; } /** * SSL CA revocation file. */ protected String SSLCARevocationFile = null; public String getSSLCARevocationFile() { return SSLCARevocationFile; } public void setSSLCARevocationFile(String SSLCARevocationFile) { this.SSLCARevocationFile = SSLCARevocationFile; } /** * SSL verify client. */ protected String SSLVerifyClient = "none"; public String getSSLVerifyClient() { return SSLVerifyClient; } public void setSSLVerifyClient(String SSLVerifyClient) { this.SSLVerifyClient = SSLVerifyClient; } /** * SSL verify depth. */ protected int SSLVerifyDepth = 10; public int getSSLVerifyDepth() { return SSLVerifyDepth; } public void setSSLVerifyDepth(int SSLVerifyDepth) { this.SSLVerifyDepth = SSLVerifyDepth; } /** * SSL allow insecure renegotiation for the the client that does not * support the secure renegotiation. */ protected boolean SSLInsecureRenegotiation = false; public void setSSLInsecureRenegotiation(boolean SSLInsecureRenegotiation) { this.SSLInsecureRenegotiation = SSLInsecureRenegotiation; } public boolean getSSLInsecureRenegotiation() { return SSLInsecureRenegotiation; } protected boolean SSLHonorCipherOrder = false; /** * Set to <code>true</code> to enforce the <i>server's</i> cipher order * instead of the default which is to allow the client to choose a * preferred cipher. */ public void setSSLHonorCipherOrder(boolean SSLHonorCipherOrder) { this.SSLHonorCipherOrder = SSLHonorCipherOrder; } public boolean getSSLHonorCipherOrder() { return SSLHonorCipherOrder; } /** * Disables compression of the SSL stream. This thwarts CRIME attack * and possibly improves performance by not compressing uncompressible * content such as JPEG, etc. */ protected boolean SSLDisableCompression = false; /** * Set to <code>true</code> to disable SSL compression. This thwarts CRIME * attack. */ public void setSSLDisableCompression(boolean SSLDisableCompression) { this.SSLDisableCompression = SSLDisableCompression; } public boolean getSSLDisableCompression() { return SSLDisableCompression; } /** * Port in use. */ @Override public int getLocalPort() { long s = serverSock; if (s == 0) { return -1; } else { long sa; try { sa = Address.get(Socket.APR_LOCAL, s); Sockaddr addr = Address.getInfo(sa); return addr.port; } catch (Exception e) { return -1; } } } @Override public String[] getCiphersUsed() { // TODO : Investigate if it is possible to extract the current list of // available ciphers. Native code changes will be required. return new String[] { getSSLCipherSuite() }; } // --------------------------------------------------------- Public Methods /** * Number of keepalive sockets. */ public int getKeepAliveCount() { if (poller == null) { return 0; } return poller.getConnectionCount(); } /** * Number of sendfile sockets. */ public int getSendfileCount() { if (sendfile == null) { return 0; } return sendfile.getSendfileCount(); } // ----------------------------------------------- Public Lifecycle Methods /** * Initialize the endpoint. */ @Override public void bind() throws Exception { // Create the root APR memory pool try { rootPool = Pool.create(0); } catch (UnsatisfiedLinkError e) { throw new Exception(sm.getString("endpoint.init.notavail")); } // Create the pool for the server socket serverSockPool = Pool.create(rootPool); // Create the APR address that will be bound String addressStr = null; if (getAddress() != null) { addressStr = getAddress().getHostAddress(); } int family = Socket.APR_INET; if (Library.APR_HAVE_IPV6) { if (addressStr == null) { if (!OS.IS_BSD && !OS.IS_WIN32 && !OS.IS_WIN64) family = Socket.APR_UNSPEC; } else if (addressStr.indexOf(':') >= 0) { family = Socket.APR_UNSPEC; } } long inetAddress = Address.info(addressStr, family, getPort(), 0, rootPool); // Create the APR server socket serverSock = Socket.create(Address.getInfo(inetAddress).family, Socket.SOCK_STREAM, Socket.APR_PROTO_TCP, rootPool); if (OS.IS_UNIX) { Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Deal with the firewalls that tend to drop the inactive sockets Socket.optSet(serverSock, Socket.APR_SO_KEEPALIVE, 1); // Bind the server socket int ret = Socket.bind(serverSock, inetAddress); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.bind", "" + ret, Error.strerror(ret))); } // Start listening on the server socket ret = Socket.listen(serverSock, getBacklog()); if (ret != 0) { throw new Exception(sm.getString("endpoint.init.listen", "" + ret, Error.strerror(ret))); } if (OS.IS_WIN32 || OS.IS_WIN64) { // On Windows set the reuseaddr flag after the bind/listen Socket.optSet(serverSock, Socket.APR_SO_REUSEADDR, 1); } // Sendfile usage on systems which don't support it cause major problems if (useSendfile && !Library.APR_HAS_SENDFILE) { useSendfile = false; } // Initialize thread count default for acceptor if (acceptorThreadCount == 0) { // FIXME: Doesn't seem to work that well with multiple accept threads acceptorThreadCount = 1; } // Delay accepting of new connections until data is available // Only Linux kernels 2.4 + have that implemented // on other platforms this call is noop and will return APR_ENOTIMPL. if (deferAccept) { if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) { deferAccept = false; } } // Initialize SSL if needed if (isSSLEnabled()) { if (SSLCertificateFile == null) { // This is required throw new Exception(sm.getString("endpoint.apr.noSslCertFile")); } // SSL protocol int value = SSL.SSL_PROTOCOL_NONE; if (SSLProtocol == null || SSLProtocol.length() == 0) { value = SSL.SSL_PROTOCOL_ALL; } else { for (String protocol : SSLProtocol.split("\\+")) { protocol = protocol.trim(); if ("SSLv2".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV2; } else if ("SSLv3".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_SSLV3; } else if ("TLSv1".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_TLSV1; } else if ("all".equalsIgnoreCase(protocol)) { value |= SSL.SSL_PROTOCOL_ALL; } else { // Protocol not recognized, fail to start as it is safer than // continuing with the default which might enable more than the // is required throw new Exception(sm.getString( "endpoint.apr.invalidSslProtocol", SSLProtocol)); } } } // Create SSL Context sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER); if (SSLInsecureRenegotiation) { boolean legacyRenegSupported = false; try { legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); if (legacyRenegSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!legacyRenegSupported) { // OpenSSL does not support unsafe legacy renegotiation. log.warn(sm.getString("endpoint.warn.noInsecureReneg", SSL.versionString())); } } // Set cipher order: client (default) or server if (SSLHonorCipherOrder) { boolean orderCiphersSupported = false; try { orderCiphersSupported = SSL.hasOp(SSL.SSL_OP_CIPHER_SERVER_PREFERENCE); if (orderCiphersSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE); } catch (UnsatisfiedLinkError e) { // Ignore } if (!orderCiphersSupported) { // OpenSSL does not support ciphers ordering. log.warn(sm.getString("endpoint.warn.noHonorCipherOrder", SSL.versionString())); } } // Disable compression if requested if (SSLDisableCompression) { boolean disableCompressionSupported = false; try { disableCompressionSupported = SSL.hasOp(SSL.SSL_OP_NO_COMPRESSION); if (disableCompressionSupported) SSLContext.setOptions(sslContext, SSL.SSL_OP_NO_COMPRESSION); } catch (UnsatisfiedLinkError e) { // Ignore } if (!disableCompressionSupported) { // OpenSSL does not support ciphers ordering. log.warn(sm.getString("endpoint.warn.noDisableCompression", SSL.versionString())); } } // List the ciphers that the client is permitted to negotiate SSLContext.setCipherSuite(sslContext, SSLCipherSuite); // Load Server key and certificate SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA); // Set certificate chain file SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false); // Support Client Certificates SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath); // Set revocation SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath); // Client certificate verification value = SSL.SSL_CVERIFY_NONE; if ("optional".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL; } else if ("require".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_REQUIRE; } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) { value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA; } SSLContext.setVerify(sslContext, value, SSLVerifyDepth); // For now, sendfile is not supported with SSL useSendfile = false; } } public long getJniSslContext() { return sslContext; } /** * Start the APR endpoint, creating acceptor, poller and sendfile threads. */ @Override public void startInternal() throws Exception { if (!running) { running = true; paused = false; // Create worker collection if (getExecutor() == null) { createExecutor(); } initializeConnectionLatch(); // Start poller thread poller = new Poller(); poller.init(); Thread pollerThread = new Thread(poller, getName() + "-Poller"); pollerThread.setPriority(threadPriority); pollerThread.setDaemon(true); pollerThread.start(); // Start sendfile thread if (useSendfile) { sendfile = new Sendfile(); sendfile.init(); Thread sendfileThread = new Thread(sendfile, getName() + "-Sendfile"); sendfileThread.setPriority(threadPriority); sendfileThread.setDaemon(true); sendfileThread.start(); } startAcceptorThreads(); // Start async timeout thread Thread timeoutThread = new Thread(new AsyncTimeout(), getName() + "-AsyncTimeout"); timeoutThread.setPriority(threadPriority); timeoutThread.setDaemon(true); timeoutThread.start(); } } /** * 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 (AbstractEndpoint.Acceptor acceptor : acceptors) { long waitLeft = 10000; while (waitLeft > 0 && acceptor.getState() != AcceptorState.ENDED && serverSock != 0) { try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore } waitLeft -= 50; } if (waitLeft == 0) { log.warn(sm.getString("endpoint.warn.unlockAcceptorFailed", acceptor.getThreadName())); // If the Acceptor is still running force // the hard socket close. if (serverSock != 0) { Socket.shutdown(serverSock, Socket.APR_SHUTDOWN_READ); serverSock = 0; } } } try { poller.destroy(); } catch (Exception e) { // Ignore } poller = null; connections.clear(); if (useSendfile) { try { sendfile.destroy(); } catch (Exception e) { // Ignore } sendfile = null; } } shutdownExecutor(); } /** * Deallocate APR memory pools, and close server socket. */ @Override public void unbind() throws Exception { if (running) { stop(); } // Destroy pool if it was initialised if (serverSockPool != 0) { Pool.destroy(serverSockPool); serverSockPool = 0; } // Close server socket if it was initialised if (serverSock != 0) { Socket.close(serverSock); serverSock = 0; } sslContext = 0; // Close all APR memory pools and resources if initialised if (rootPool != 0) { Pool.destroy(rootPool); rootPool = 0; } handler.recycle(); } // ------------------------------------------------------ Protected Methods @Override protected AbstractEndpoint.Acceptor createAcceptor() { return new Acceptor(); } /** * Process the specified connection. */ protected boolean setSocketOptions(long socket) { // Process the connection int step = 1; try { // 1: Set socket options: timeout, linger, etc if (socketProperties.getSoLingerOn() && socketProperties.getSoLingerTime() >= 0) Socket.optSet(socket, Socket.APR_SO_LINGER, socketProperties.getSoLingerTime()); if (socketProperties.getTcpNoDelay()) Socket.optSet(socket, Socket.APR_TCP_NODELAY, (socketProperties.getTcpNoDelay() ? 1 : 0)); Socket.timeoutSet(socket, socketProperties.getSoTimeout() * 1000); // 2: SSL handshake step = 2; if (sslContext != 0) { SSLSocket.attach(sslContext, socket); if (SSLSocket.handshake(socket) != 0) { if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.err.handshake") + ": " + SSL.getLastError()); } return false; } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) { if (step == 2) { log.debug(sm.getString("endpoint.err.handshake"), t); } else { log.debug(sm.getString("endpoint.err.unexpected"), t); } } // Tell to close the socket return false; } return true; } /** * Allocate a new poller of the specified size. */ protected long allocatePoller(int size, long pool, int timeout) { try { return Poll.create(size, pool, 0, timeout * 1000); } catch (Error e) { if (Status.APR_STATUS_IS_EINVAL(e.getError())) { log.info(sm.getString("endpoint.poll.limitedpollsize", "" + size)); return 0; } else { log.error(sm.getString("endpoint.poll.initfail"), e); return -1; } } } /** * Process given socket. This is called when the socket has been * accepted. */ protected boolean processSocketWithOptions(long socket) { try { // During shutdown, executor may be null - avoid NPE if (running) { AprSocketWrapper wrapper = new AprSocketWrapper(Long.valueOf(socket)); wrapper.setKeepAliveLeft(getMaxKeepAliveRequests()); connections.put(Long.valueOf(socket), wrapper); getExecutor().execute(new SocketWithOptionsProcessor(wrapper)); } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); 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; } /** * Process given socket. Called in non-comet mode, typically keep alive * or upgraded protocol. */ public boolean processSocket(long socket, SocketStatus status) { try { Executor executor = getExecutor(); if (executor == null) { log.warn(sm.getString("endpoint.warn.noExector", Long.valueOf(socket), null)); } else { SocketWrapper<Long> wrapper = connections.get(Long.valueOf(socket)); executor.execute(new SocketProcessor(wrapper, status)); } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for:"+socket,x); 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; } public boolean processSocketAsync(SocketWrapper<Long> socket, SocketStatus status) { try { synchronized (socket) { if (waitingRequests.remove(socket)) { SocketProcessor proc = new SocketProcessor(socket, status); ClassLoader loader = Thread.currentThread().getContextClassLoader(); try { //threads should not be created by the webapp classloader if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( getClass().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader( getClass().getClassLoader()); } Executor executor = getExecutor(); if (executor == null) { log.warn(sm.getString("endpoint.warn.noExector", socket, status)); return false; } else { executor.execute(proc); } } finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } } } } } catch (RejectedExecutionException x) { log.warn("Socket processing request was rejected for: "+socket, x); 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; } private void destroySocket(long socket) { // If not running the socket will be destroyed by // parent pool or acceptor socket. // In any case disable double free which would cause JVM core. // While the connector is running, destroySocket() will call // countDownConnection(). Once the connector is stopped, the latch is // removed so it does not matter that destroySocket() does not call // countDownConnection() in that case connections.remove(Long.valueOf(socket)); destroySocket(socket, running); } private void destroySocket(long socket, boolean doIt) { // Be VERY careful if you call this method directly. If it is called // twice for the same socket the JVM will core. Currently this is only // called from Poller.closePollset() to ensure kept alive connections // are closed when calling stop() followed by start(). if (doIt && socket != 0) { Socket.destroy(socket); countDownConnection(); } } @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 { private final Log log = LogFactory.getLog(AprEndpoint.Acceptor.class); @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(); long socket = 0; try { // Accept the next incoming connection from the server // socket socket = Socket.accept(serverSock); } catch (Exception e) { //we didn't get a socket countDownConnection(); // Introduce delay if necessary errorDelay = handleExceptionWithDelay(errorDelay); // re-throw throw e; } // Successful accept, reset the error delay errorDelay = 0; if (running && !paused) { // Hand this socket off to an appropriate processor if (!processSocketWithOptions(socket)) { // Close socket and pool right away destroySocket(socket); } } else { // Close socket and pool right away destroySocket(socket); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (running) { String msg = sm.getString("endpoint.accept.fail"); if (t instanceof Error) { Error e = (Error) t; if (e.getError() == 233) { // Not an error on HP-UX so log as a warning // so it can be filtered out on that platform // See bug 50273 log.warn(msg, t); } else { log.error(msg, t); } } else { log.error(msg, t); } } } // The processor will recycle itself when it finishes } state = AcceptorState.ENDED; } } /** * Async timeout thread */ protected class AsyncTimeout implements Runnable { /** * The background thread that checks async requests and fires the * timeout if there has been no activity. */ @Override public void run() { // Loop until we receive a shutdown command while (running) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } long now = System.currentTimeMillis(); Iterator<SocketWrapper<Long>> sockets = waitingRequests.iterator(); while (sockets.hasNext()) { SocketWrapper<Long> socket = sockets.next(); if (socket.async) { long access = socket.getLastAccess(); if (socket.getTimeout() > 0 && (now-access)>socket.getTimeout()) { processSocketAsync(socket,SocketStatus.TIMEOUT); } } } // Loop if endpoint is paused while (paused && running) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } } } } // -------------------------------------------------- SocketInfo Inner Class public static class SocketInfo { public long socket; public int timeout; public int flags; public boolean read() { return (flags & Poll.APR_POLLIN) == Poll.APR_POLLIN; } public boolean write() { return (flags & Poll.APR_POLLOUT) == Poll.APR_POLLOUT; } public static int merge(int flag1, int flag2) { return ((flag1 & Poll.APR_POLLIN) | (flag2 & Poll.APR_POLLIN)) | ((flag1 & Poll.APR_POLLOUT) | (flag2 & Poll.APR_POLLOUT)); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("Socket: ["); sb.append(socket); sb.append("], timeout: ["); sb.append(timeout); sb.append("], flags: ["); sb.append(flags); return sb.toString(); } } // ---------------------------------------------- SocketTimeouts Inner Class public class SocketTimeouts { protected int size; protected long[] sockets; protected long[] timeouts; protected int pos = 0; public SocketTimeouts(int size) { this.size = 0; sockets = new long[size]; timeouts = new long[size]; } public void add(long socket, long timeout) { sockets[size] = socket; timeouts[size] = timeout; size++; } public boolean remove(long socket) { for (int i = 0; i < size; i++) { if (sockets[i] == socket) { sockets[i] = sockets[size - 1]; timeouts[i] = timeouts[size - 1]; size--; return true; } } return false; } public long check(long date) { while (pos < size) { if (date >= timeouts[pos]) { long result = sockets[pos]; sockets[pos] = sockets[size - 1]; timeouts[pos] = timeouts[size - 1]; size--; return result; } pos++; } pos = 0; return 0; } } // -------------------------------------------------- SocketList Inner Class public class SocketList { protected int size; protected int pos; protected long[] sockets; protected int[] timeouts; protected int[] flags; protected SocketInfo info = new SocketInfo(); public SocketList(int size) { this.size = 0; pos = 0; sockets = new long[size]; timeouts = new int[size]; flags = new int[size]; } public int size() { return this.size; } public SocketInfo get() { if (pos == size) { return null; } else { info.socket = sockets[pos]; info.timeout = timeouts[pos]; info.flags = flags[pos]; pos++; return info; } } public void clear() { size = 0; pos = 0; } public boolean add(long socket, int timeout, int flag) { if (size == sockets.length) { return false; } else { for (int i = 0; i < size; i++) { if (sockets[i] == socket) { flags[i] = SocketInfo.merge(flags[i], flag); return true; } } sockets[size] = socket; timeouts[size] = timeout; flags[size] = flag; size++; return true; } } public void duplicate(SocketList copy) { copy.size = size; copy.pos = pos; System.arraycopy(sockets, 0, copy.sockets, 0, size); System.arraycopy(timeouts, 0, copy.timeouts, 0, size); System.arraycopy(flags, 0, copy.flags, 0, size); } } // ------------------------------------------------------ Poller Inner Class public class Poller implements Runnable { /** * Pointers to the pollers. */ protected long[] pollers = null; /** * Actual poller size. */ protected int actualPollerSize = 0; /** * Amount of spots left in the poller. */ protected int[] pollerSpace = null; /** * Amount of low level pollers in use by this poller. */ protected int pollerCount; /** * Timeout value for the poll call. */ protected int pollerTime; /** * Root pool. */ protected long pool = 0; /** * Socket descriptors. */ protected long[] desc; /** * List of sockets to be added to the poller. */ protected SocketList addList = null; /** * List of sockets to be added to the poller. */ protected SocketList localAddList = null; /** * Structure used for storing timeouts. */ protected SocketTimeouts timeouts = null; /** * Last run of maintain. Maintain will run usually every 5s. */ protected long lastMaintain = System.currentTimeMillis(); /** * Amount of connections inside this poller. */ protected int connectionCount = 0; public int getConnectionCount() { return connectionCount; } /** * Create the poller. With some versions of APR, the maximum poller size * will be 62 (recompiling APR is necessary to remove this limitation). */ protected void init() { pool = Pool.create(serverSockPool); // Single poller by default int defaultPollerSize = getMaxConnections(); if ((OS.IS_WIN32 || OS.IS_WIN64) && (defaultPollerSize > 1024)) { // The maximum per poller to get reasonable performance is 1024 // Adjust poller size so that it won't reach the limit. This is // a limitation of XP / Server 2003 that has been fixed in // Vista / Server 2008 onwards. defaultPollerSize = 1024; } actualPollerSize = defaultPollerSize; timeouts = new SocketTimeouts(defaultPollerSize); // At the moment, setting the timeout is useless, but it could get // used again as the normal poller could be faster using maintain. // It might not be worth bothering though. long pollset = allocatePoller(actualPollerSize, pool, -1); if (pollset == 0 && actualPollerSize > 1024) { actualPollerSize = 1024; pollset = allocatePoller(actualPollerSize, pool, -1); } if (pollset == 0) { actualPollerSize = 62; pollset = allocatePoller(actualPollerSize, pool, -1); } pollerCount = defaultPollerSize / actualPollerSize; pollerTime = pollTime / pollerCount; pollers = new long[pollerCount]; pollers[0] = pollset; for (int i = 1; i < pollerCount; i++) { pollers[i] = allocatePoller(actualPollerSize, pool, -1); } pollerSpace = new int[pollerCount]; for (int i = 0; i < pollerCount; i++) { pollerSpace[i] = actualPollerSize; } desc = new long[actualPollerSize * 2]; connectionCount = 0; addList = new SocketList(defaultPollerSize); localAddList = new SocketList(defaultPollerSize); } /** * Destroy the poller. */ protected void destroy() { // Wait for pollerTime before doing anything, so that the poller // threads exit, otherwise parallel destruction of sockets which are // still in the poller can cause problems try { synchronized (this) { this.wait(pollTime / 1000); } } catch (InterruptedException e) { // Ignore } // Close all sockets in the add queue SocketInfo info = addList.get(); while (info != null) { boolean comet = connections.get(Long.valueOf(info.socket)).isComet(); if (!comet || (comet && !processSocket( info.socket, SocketStatus.STOP))) { destroySocket(info.socket); } info = addList.get(); } addList.clear(); // Close all sockets still in the poller for (int i = 0; i < pollerCount; i++) { int rv = Poll.pollset(pollers[i], desc); if (rv > 0) { for (int n = 0; n < rv; n++) { boolean comet = connections.get( Long.valueOf(desc[n*2+1])).isComet(); if (!comet || (comet && !processSocket( desc[n*2+1], SocketStatus.STOP))) { destroySocket(desc[n*2+1]); } } } } Pool.destroy(pool); connectionCount = 0; } /** * 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(long socket) { int timeout = getKeepAliveTimeout(); if (timeout <= 0) { timeout = getSoTimeout(); } if (timeout <= 0) { // Always put a timeout in timeout = Integer.MAX_VALUE; } boolean ok = false; synchronized (this) { // Add socket to the list. Newly added sockets will wait // at most for pollTime before being polled if (addList.add(socket, timeout, Poll.APR_POLLIN)) { ok = true; this.notify(); } } if (!ok) { // Can't do anything: close the socket right away boolean comet = connections.get( Long.valueOf(socket)).isComet(); if (!comet || (comet && !processSocket( socket, SocketStatus.ERROR))) { destroySocket(socket); } } } /** * 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). Note: If both read and write are false, the socket * will only be checked for timeout; if the socket was already present * in the poller, a callback event will be generated and the socket will * be removed from the poller. * * @param socket to add to the poller * @param timeout to use for this connection * @param read to do read polling * @param write to do write polling */ public void add(long socket, int timeout, boolean read, boolean write) { add(socket, timeout, (read ? Poll.APR_POLLIN : 0) | (write ? Poll.APR_POLLOUT : 0)); } private void add(long socket, int timeout, int flags) { if (timeout < 0) { timeout = getSoTimeout(); } if (timeout <= 0) { // Always put a timeout in timeout = Integer.MAX_VALUE; } boolean ok = false; synchronized (this) { // Add socket to the list. Newly added sockets will wait // at most for pollTime before being polled if (addList.add(socket, timeout, flags)) { ok = true; this.notify(); } } if (!ok) { // Can't do anything: close the socket right away boolean comet = connections.get( Long.valueOf(socket)).isComet(); if (!comet || (comet && !processSocket( socket, SocketStatus.ERROR))) { destroySocket(socket); } } } /** * Add specified socket to one of the pollers. */ protected boolean addToPoller(long socket, int events) { int rv = -1; for (int i = 0; i < pollers.length; i++) { if (pollerSpace[i] > 0) { rv = Poll.add(pollers[i], socket, events); if (rv == Status.APR_SUCCESS) { pollerSpace[i]--; connectionCount++; return true; } } } return false; } /** * Remove specified socket from the pollers. */ protected boolean removeFromPoller(long socket) { int rv = -1; for (int i = 0; i < pollers.length; i++) { if (pollerSpace[i] < actualPollerSize) { rv = Poll.remove(pollers[i], socket); if (rv != Status.APR_NOTFOUND) { pollerSpace[i]++; connectionCount--; break; } } } return (rv == Status.APR_SUCCESS); } /** * Timeout checks. */ protected void maintain() { long date = System.currentTimeMillis(); // Maintain runs at most once every 5s, although it will likely get // called more if ((date - lastMaintain) < 5000L) { return; } else { lastMaintain = date; } long socket = timeouts.check(date); while (socket != 0) { removeFromPoller(socket); boolean comet = connections.get( Long.valueOf(socket)).isComet(); if (!comet || (comet && !processSocket( socket, SocketStatus.TIMEOUT))) { destroySocket(socket); } socket = timeouts.check(date); } } /** * Displays the list of sockets in the pollers. */ @Override public String toString() { StringBuffer buf = new StringBuffer(); buf.append("Poller"); long[] res = new long[actualPollerSize * 2]; for (int i = 0; i < pollers.length; i++) { int count = Poll.pollset(pollers[i], res); buf.append(" [ "); for (int j = 0; j < count; j++) { buf.append(desc[2*j+1]).append(" "); } buf.append("]"); } return buf.toString(); } /** * The background thread that listens for incoming TCP/IP connections * and hands them off to an appropriate processor. */ @Override public void run() { int maintain = 0; // Loop until we receive a shutdown command while (running) { // Loop if endpoint is paused while (paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Check timeouts if the poller is empty while (connectionCount < 1 && addList.size() < 1) { // Reset maintain time. try { if (getSoTimeout() > 0 && running) { maintain(); } synchronized (this) { this.wait(10000); } } catch (InterruptedException e) { // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().warn(sm.getString("endpoint.timeout.err")); } } try { // Add sockets which are waiting to the poller if (addList.size() > 0) { synchronized (this) { // Duplicate to another list, so that the syncing is // minimal addList.duplicate(localAddList); addList.clear(); } SocketInfo info = localAddList.get(); while (info != null) { if (info.read() || info.write()) { AprSocketWrapper wrapper = connections.get( Long.valueOf(info.socket)); boolean comet = wrapper.isComet(); // Store timeout if (comet) { removeFromPoller(info.socket); } wrapper.pollerFlags = wrapper.pollerFlags | (info.read() ? Poll.APR_POLLIN : 0) | (info.write() ? Poll.APR_POLLOUT : 0); if (!addToPoller(info.socket, wrapper.pollerFlags)) { // Can't do anything: close the socket right // away if (!comet || (comet && !processSocket( info.socket, SocketStatus.ERROR))) { destroySocket(info.socket); } } else { timeouts.add(info.socket, System.currentTimeMillis() + info.timeout); } } else { // Should never happen. timeouts.remove(info.socket); destroySocket(info.socket); getLog().warn(sm.getString( "endpoint.apr.pollAddInvalid", info)); } info = localAddList.get(); } } // Poll for the specified interval for (int i = 0; i < pollers.length; i++) { // Flags to ask to reallocate the pool boolean reset = false; //ArrayList<Long> skip = null; int rv = 0; // Iterate on each pollers, but no need to poll empty pollers if (pollerSpace[i] < actualPollerSize) { rv = Poll.poll(pollers[i], pollerTime, desc, true); } if (rv > 0) { pollerSpace[i] += rv; connectionCount -= rv; for (int n = 0; n < rv; n++) { timeouts.remove(desc[n*2+1]); AprSocketWrapper wrapper = connections.get( Long.valueOf(desc[n*2+1])); wrapper.pollerFlags = wrapper.pollerFlags & ~((int) desc[n*2]); if (wrapper.pollerFlags != 0) { add(desc[n*2+1], 1, wrapper.pollerFlags); } // Check for failed sockets and hand this socket off to a worker if (wrapper.isComet()) { // Event processes either a read or a write depending on what the poller returns if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP) || ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR) || ((desc[n*2] & Poll.APR_POLLNVAL) == Poll.APR_POLLNVAL)) { if (!processSocket(desc[n*2+1], SocketStatus.ERROR)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) { if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) { if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else { // Unknown event getLog().warn(sm.getString( "endpoint.apr.pollUnknownEvent", Long.valueOf(desc[n*2]))); if (!processSocket(desc[n*2+1], SocketStatus.ERROR)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } } else if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP) || ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR) || ((desc[n*2] & Poll.APR_POLLNVAL) == Poll.APR_POLLNVAL)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } else if (((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) || ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT)) { boolean error = false; if (((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) && !processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { error = true; // Close socket and clear pool destroySocket(desc[n*2+1]); } if (!error && ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) && !processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool destroySocket(desc[n*2+1]); } } else { // Unknown event getLog().warn(sm.getString( "endpoint.apr.pollUnknownEvent", Long.valueOf(desc[n*2]))); // Close socket and clear pool destroySocket(desc[n*2+1]); } } } else if (rv < 0) { int errn = -rv; // Any non timeup or interrupted error is critical if ((errn != Status.TIMEUP) && (errn != Status.EINTR)) { if (errn > Status.APR_OS_START_USERERR) { errn -= Status.APR_OS_START_USERERR; } getLog().error(sm.getString( "endpoint.apr.pollError", Integer.valueOf(errn), Error.strerror(errn))); // Destroy and reallocate the poller reset = true; } } if (reset) { // Reallocate the current poller int count = Poll.pollset(pollers[i], desc); long newPoller = allocatePoller(actualPollerSize, pool, -1); // Don't restore connections for now, since I have not tested it pollerSpace[i] = actualPollerSize; connectionCount -= count; Poll.destroy(pollers[i]); pollers[i] = newPoller; } } // Process socket timeouts if (getSoTimeout() > 0 && maintain++ > 1000 && running) { // This works and uses only one timeout mechanism for everything, but the // non event poller might be a bit faster by using the old maintain. maintain = 0; maintain(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (maintain == 0) { getLog().warn(sm.getString("endpoint.timeout.error"), t); } else { getLog().warn(sm.getString("endpoint.poll.error"), t); } } } synchronized (this) { this.notifyAll(); } } } // ----------------------------------------------- SendfileData Inner Class /** * SendfileData class. */ public static class SendfileData { // File public String fileName; public long fd; public long fdpool; // Range information public long start; public long end; // Socket and socket pool public long socket; // Position public long pos; // KeepAlive flag public boolean keepAlive; } // --------------------------------------------------- Sendfile Inner Class public class Sendfile implements Runnable { protected long sendfilePollset = 0; protected long pool = 0; protected long[] desc; protected HashMap<Long, SendfileData> sendfileData; protected int sendfileCount; public int getSendfileCount() { return sendfileCount; } protected ArrayList<SendfileData> addS; /** * Create the sendfile poller. With some versions of APR, the maximum * poller size will be 62 (recompiling APR is necessary to remove this * limitation). */ protected void init() { pool = Pool.create(serverSockPool); int size = sendfileSize; if (size <= 0) { size = (OS.IS_WIN32 || OS.IS_WIN64) ? (1 * 1024) : (16 * 1024); } sendfilePollset = allocatePoller(size, pool, getSoTimeout()); if (sendfilePollset == 0 && size > 1024) { size = 1024; sendfilePollset = allocatePoller(size, pool, getSoTimeout()); } if (sendfilePollset == 0) { size = 62; sendfilePollset = allocatePoller(size, pool, getSoTimeout()); } desc = new long[size * 2]; sendfileData = new HashMap<>(size); addS = new ArrayList<>(); } /** * Destroy the poller. */ protected void destroy() { // Wait for polltime before doing anything, so that the poller threads // exit, otherwise parallel destruction of sockets which are still // in the poller can cause problems try { synchronized (this) { this.wait(pollTime / 1000); } } catch (InterruptedException e) { // Ignore } // Close any socket remaining in the add queue for (int i = (addS.size() - 1); i >= 0; i--) { SendfileData data = addS.get(i); destroySocket(data.socket); } // Close all sockets still in the poller int rv = Poll.pollset(sendfilePollset, desc); if (rv > 0) { for (int n = 0; n < rv; n++) { destroySocket(desc[n*2+1]); } } Pool.destroy(pool); sendfileData.clear(); } /** * Add the sendfile data to the sendfile poller. Note that in most cases, * the initial non blocking calls to sendfile will return right away, and * will be handled asynchronously inside the kernel. As a result, * the poller will never be used. * * @param data containing the reference to the data which should be snet * @return true if all the data has been sent right away, and false * otherwise */ public boolean add(SendfileData data) { // Initialize fd from data given try { data.fdpool = Socket.pool(data.socket); data.fd = File.open (data.fileName, File.APR_FOPEN_READ | File.APR_FOPEN_SENDFILE_ENABLED | File.APR_FOPEN_BINARY, 0, data.fdpool); data.pos = data.start; // Set the socket to nonblocking mode Socket.timeoutSet(data.socket, 0); while (true) { long nw = Socket.sendfilen(data.socket, data.fd, data.pos, data.end - data.pos, 0); if (nw < 0) { if (!(-nw == Status.EAGAIN)) { Pool.destroy(data.fdpool); data.socket = 0; return false; } else { // Break the loop and add the socket to poller. break; } } else { data.pos = data.pos + nw; if (data.pos >= data.end) { // Entire file has been sent Pool.destroy(data.fdpool); // Set back socket to blocking mode Socket.timeoutSet( data.socket, getSoTimeout() * 1000); return true; } } } } catch (Exception e) { log.warn(sm.getString("endpoint.sendfile.error"), e); return false; } // Add socket to the list. Newly added sockets will wait // at most for pollTime before being polled synchronized (this) { addS.add(data); this.notify(); } return false; } /** * Remove socket from the poller. * * @param data the sendfile data which should be removed */ protected void remove(SendfileData data) { int rv = Poll.remove(sendfilePollset, data.socket); if (rv == Status.APR_SUCCESS) { sendfileCount--; } sendfileData.remove(new Long(data.socket)); } /** * The background thread that listens for incoming TCP/IP connections * and hands them off to an appropriate processor. */ @Override public void run() { long maintainTime = 0; // Loop until we receive a shutdown command while (running) { // Loop if endpoint is paused while (paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Loop if poller is empty while (sendfileCount < 1 && addS.size() < 1) { // Reset maintain time. maintainTime = 0; try { synchronized (this) { this.wait(); } } catch (InterruptedException e) { // Ignore } } try { // Add socket to the poller if (addS.size() > 0) { synchronized (this) { for (int i = (addS.size() - 1); i >= 0; i--) { SendfileData data = addS.get(i); int rv = Poll.add(sendfilePollset, data.socket, Poll.APR_POLLOUT); if (rv == Status.APR_SUCCESS) { sendfileData.put(new Long(data.socket), data); sendfileCount++; } else { getLog().warn(sm.getString( "endpoint.sendfile.addfail", Integer.valueOf(rv), Error.strerror(rv))); // Can't do anything: close the socket right away destroySocket(data.socket); } } addS.clear(); } } maintainTime += pollTime; // Pool for the specified interval int rv = Poll.poll(sendfilePollset, pollTime, desc, false); if (rv > 0) { for (int n = 0; n < rv; n++) { // Get the sendfile state SendfileData state = sendfileData.get(new Long(desc[n*2+1])); // Problem events if (((desc[n*2] & Poll.APR_POLLHUP) == Poll.APR_POLLHUP) || ((desc[n*2] & Poll.APR_POLLERR) == Poll.APR_POLLERR)) { // Close socket and clear pool remove(state); // Destroy file descriptor pool, which should close the file // Close the socket, as the response would be incomplete destroySocket(state.socket); continue; } // Write some data using sendfile long nw = Socket.sendfilen(state.socket, state.fd, state.pos, state.end - state.pos, 0); if (nw < 0) { // Close socket and clear pool remove(state); // Close the socket, as the response would be incomplete // This will close the file too. destroySocket(state.socket); continue; } state.pos = state.pos + nw; if (state.pos >= state.end) { remove(state); if (state.keepAlive) { // Destroy file descriptor pool, which should close the file Pool.destroy(state.fdpool); Socket.timeoutSet(state.socket, getSoTimeout() * 1000); // If all done put the socket back in the poller for // processing of further requests getPoller().add(state.socket); } else { // Close the socket since this is // the end of not keep-alive request. destroySocket(state.socket); } } } } else if (rv < 0) { int errn = -rv; /* Any non timeup or interrupted error is critical */ if ((errn != Status.TIMEUP) && (errn != Status.EINTR)) { if (errn > Status.APR_OS_START_USERERR) { errn -= Status.APR_OS_START_USERERR; } getLog().error(sm.getString( "Unexpected poller error", Integer.valueOf(errn), Error.strerror(errn))); // Handle poll critical failure synchronized (this) { destroy(); init(); } continue; } } // Call maintain for the sendfile poller if (getSoTimeout() > 0 && maintainTime > 1000000L && running) { rv = Poll.maintain(sendfilePollset, desc, false); maintainTime = 0; if (rv > 0) { for (int n = 0; n < rv; n++) { // Get the sendfile state SendfileData state = sendfileData.get(new Long(desc[n])); // Close socket and clear pool remove(state); // Destroy file descriptor pool, which should close the file // Close the socket, as the response would be incomplete destroySocket(state.socket); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("endpoint.poll.error"), t); } } synchronized (this) { this.notifyAll(); } } } // ------------------------------------------------ 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<Long> socket, SocketStatus status); } // --------------------------------- SocketWithOptionsProcessor Inner Class /** * This class is the equivalent of the Worker, but will simply use in an * external Executor thread pool. This will also set the socket options * and do the handshake. * * This is called after an accept(). */ protected class SocketWithOptionsProcessor implements Runnable { protected SocketWrapper<Long> socket = null; public SocketWithOptionsProcessor(SocketWrapper<Long> socket) { this.socket = socket; } @Override public void run() { synchronized (socket) { if (!deferAccept) { if (setSocketOptions(socket.getSocket().longValue())) { getPoller().add(socket.getSocket().longValue(), getSoTimeout(), true, false); } else { // Close socket and pool destroySocket(socket.getSocket().longValue()); socket = null; } } else { // Process the request from this socket if (!setSocketOptions(socket.getSocket().longValue())) { // Close socket and pool destroySocket(socket.getSocket().longValue()); socket = null; return; } // Process the request from this socket Handler.SocketState state = handler.process(socket, SocketStatus.OPEN_READ); if (state == Handler.SocketState.CLOSED) { // Close socket and pool destroySocket(socket.getSocket().longValue()); socket = null; } else if (state == Handler.SocketState.LONG) { socket.access(); if (socket.async) { waitingRequests.add(socket); } } } } } } // -------------------------------------------- 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 final SocketWrapper<Long> socket; private final SocketStatus status; public SocketProcessor(SocketWrapper<Long> socket, SocketStatus status) { this.socket = socket; if (status == null) { // Should never happen throw new NullPointerException(); } this.status = status; } @Override public void run() { // Upgraded connections need to allow multiple threads to access the // connection at the same time to enable blocking IO to be used when // Servlet 3.1 NIO has been configured if (socket.isUpgraded()) { doRun(); } else { synchronized (socket) { doRun(); } } } private void doRun() { // Process the request from this socket SocketState state = handler.process(socket, status); if (state == Handler.SocketState.CLOSED) { // Close socket and pool destroySocket(socket.getSocket().longValue()); } else if (state == Handler.SocketState.LONG) { socket.access(); if (socket.async) { waitingRequests.add(socket); } } else if (state == Handler.SocketState.ASYNC_END) { socket.access(); SocketProcessor proc = new SocketProcessor(socket, SocketStatus.OPEN_READ); getExecutor().execute(proc); } } } private static class AprSocketWrapper extends SocketWrapper<Long> { // This field should only be used by Poller#run() private int pollerFlags = 0; public AprSocketWrapper(Long socket) { super(socket); } } private static class PrivilegedSetTccl implements PrivilegedAction<Void> { private ClassLoader cl; PrivilegedSetTccl(ClassLoader cl) { this.cl = cl; } @Override public Void run() { Thread.currentThread().setContextClassLoader(cl); return null; } } }
54,521
Bug 54521 DigestAuthenticator: nonceCountValid() fails in case of simultaneous asynchronous requests of the same client
Concerned components: org.apache.catalina.authenticator.DigestAuthenticator org.apache.catalina.authenticator.DigestAuthenticator.NonceInfo Scenario: A multithreaded client sends two requests within one millisecond. The DigestAuthenticator creates for each request a nonce as well as a NonceInfo instance. The two nonces are equal, as they were created within the same millisecond. When writing data into the cache (method generateNonce()), the second NonceInfo instance overwrites the first one (same key!). Problem: The two client threads then send a second request with a digest authentication header. In both requests, nc (nonce count) is equal 1, as the nonce has been newly created. In the NonceInfo of the first request, array seen is set to true for index ((nonceCount + offset) % seen.length). In the second request the same NonceInfo instance is used, as the instance is retrieved from map nonces using nonce as a key, that is, in both requests the same key is used. Consequently, method nonceCountValid() returns false, as seen[(nonceCount + offset) % seen.length)] has already been set to true. Therefore the authentication fails, although the client has sent a valid digest authentication header. Conclusion: Working with multi-threaded clients with many requests, digest authentication does not function reliably.
resolved fixed
b68bbb8
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-07T11:00:57Z
2013-02-04T15:00:00Z
java/org/apache/catalina/authenticator/DigestAuthenticator.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.io.StringReader; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.Principal; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.LifecycleException; import org.apache.catalina.Realm; import org.apache.catalina.connector.Request; import org.apache.catalina.util.ConcurrentMessageDigest; import org.apache.catalina.util.MD5Encoder; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.http.parser.HttpParser; /** * An <b>Authenticator</b> and <b>Valve</b> implementation of HTTP DIGEST * Authentication (see RFC 2069). * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class DigestAuthenticator extends AuthenticatorBase { private static final Log log = LogFactory.getLog(DigestAuthenticator.class); // -------------------------------------------------------------- Constants /** * Tomcat's DIGEST implementation only supports auth quality of protection. */ protected static final String QOP = "auth"; // ----------------------------------------------------------- Constructors public DigestAuthenticator() { super(); setCache(false); try { if (md5Helper == null) { md5Helper = MessageDigest.getInstance("MD5"); } } catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); } } // ----------------------------------------------------- Instance Variables /** * MD5 message digest provider. * @deprecated Unused - will be removed in Tomcat 8.0.x onwards */ @Deprecated protected static volatile MessageDigest md5Helper; /** * List of server nonce values currently being tracked */ protected Map<String,NonceInfo> nonces; /** * Maximum number of server nonces to keep in the cache. If not specified, * the default value of 1000 is used. */ protected int nonceCacheSize = 1000; /** * The window size to use to track seen nonce count values for a given * nonce. If not specified, the default of 100 is used. */ protected int nonceCountWindowSize = 100; /** * Private key. */ protected String key = null; /** * How long server nonces are valid for in milliseconds. Defaults to 5 * minutes. */ protected long nonceValidity = 5 * 60 * 1000; /** * Opaque string. */ protected String opaque; /** * Should the URI be validated as required by RFC2617? Can be disabled in * reverse proxies where the proxy has modified the URI. */ protected boolean validateUri = true; // ------------------------------------------------------------- Properties public int getNonceCountWindowSize() { return nonceCountWindowSize; } public void setNonceCountWindowSize(int nonceCountWindowSize) { this.nonceCountWindowSize = nonceCountWindowSize; } public int getNonceCacheSize() { return nonceCacheSize; } public void setNonceCacheSize(int nonceCacheSize) { this.nonceCacheSize = nonceCacheSize; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public long getNonceValidity() { return nonceValidity; } public void setNonceValidity(long nonceValidity) { this.nonceValidity = nonceValidity; } public String getOpaque() { return opaque; } public void setOpaque(String opaque) { this.opaque = opaque; } public boolean isValidateUri() { return validateUri; } public void setValidateUri(boolean validateUri) { this.validateUri = validateUri; } // --------------------------------------------------------- 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 in order // to get coordinated session invalidation at logout String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return (true); } // NOTE: We don't try to reauthenticate using any existing SSO session, // because that will only work if the original authentication was // BASIC or FORM, which are less secure than the DIGEST auth-type // specified for this webapp // // Uncomment below to allow previous FORM or BASIC authentications // to authenticate users for this webapp // TODO make this a configurable attribute (in SingleSignOn??) /* // 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 authorization = request.getHeader("authorization"); DigestInfo digestInfo = new DigestInfo(getOpaque(), getNonceValidity(), getKey(), nonces, isValidateUri()); if (authorization != null) { if (digestInfo.parse(request, authorization)) { if (digestInfo.validate(request)) { principal = digestInfo.authenticate(context.getRealm()); } if (principal != null && !digestInfo.isNonceStale()) { register(request, response, principal, HttpServletRequest.DIGEST_AUTH, digestInfo.getUsername(), null); return true; } } } // Send an "unauthorized" response and an appropriate challenge // Next, generate a nonce token (that is a token which is supposed // to be unique). String nonce = generateNonce(request); setAuthenticateHeader(request, response, nonce, principal != null && digestInfo.isNonceStale()); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } @Override protected String getAuthMethod() { return HttpServletRequest.DIGEST_AUTH; } // ------------------------------------------------------ Protected Methods /** * Removes the quotes on a string. RFC2617 states quotes are optional for * all parameters except realm. */ protected static String removeQuotes(String quotedString, boolean quotesRequired) { //support both quoted and non-quoted if (quotedString.length() > 0 && quotedString.charAt(0) != '"' && !quotesRequired) { return quotedString; } else if (quotedString.length() > 2) { return quotedString.substring(1, quotedString.length() - 1); } else { return ""; } } /** * Removes the quotes on a string. */ protected static String removeQuotes(String quotedString) { return removeQuotes(quotedString, false); } /** * Generate a unique token. The token is generated according to the * following pattern. NOnceToken = Base64 ( MD5 ( client-IP ":" * time-stamp ":" private-key ) ). * * @param request HTTP Servlet request */ protected String generateNonce(Request request) { long currentTime = System.currentTimeMillis(); String ipTimeKey = request.getRemoteAddr() + ":" + currentTime + ":" + getKey(); byte[] buffer = ConcurrentMessageDigest.digestMD5( ipTimeKey.getBytes(B2CConverter.ISO_8859_1)); String nonce = currentTime + ":" + MD5Encoder.encode(buffer); NonceInfo info = new NonceInfo(currentTime, getNonceCountWindowSize()); synchronized (nonces) { nonces.put(nonce, info); } return nonce; } /** * Generates the WWW-Authenticate header. * <p> * The header MUST follow this template : * <pre> * WWW-Authenticate = "WWW-Authenticate" ":" "Digest" * digest-challenge * * digest-challenge = 1#( realm | [ domain ] | nonce | * [ digest-opaque ] |[ stale ] | [ algorithm ] ) * * realm = "realm" "=" realm-value * realm-value = quoted-string * domain = "domain" "=" <"> 1#URI <"> * nonce = "nonce" "=" nonce-value * nonce-value = quoted-string * opaque = "opaque" "=" quoted-string * stale = "stale" "=" ( "true" | "false" ) * algorithm = "algorithm" "=" ( "MD5" | token ) * </pre> * * @param request HTTP Servlet request * @param response HTTP Servlet response * @param nonce nonce token */ protected void setAuthenticateHeader(HttpServletRequest request, HttpServletResponse response, String nonce, boolean isNonceStale) { String realmName = getRealmName(context); String authenticateHeader; if (isNonceStale) { authenticateHeader = "Digest realm=\"" + realmName + "\", " + "qop=\"" + QOP + "\", nonce=\"" + nonce + "\", " + "opaque=\"" + getOpaque() + "\", stale=true"; } else { authenticateHeader = "Digest realm=\"" + realmName + "\", " + "qop=\"" + QOP + "\", nonce=\"" + nonce + "\", " + "opaque=\"" + getOpaque() + "\""; } response.setHeader(AUTH_HEADER_NAME, authenticateHeader); } // ------------------------------------------------------- Lifecycle Methods @Override protected synchronized void startInternal() throws LifecycleException { super.startInternal(); // Generate a random secret key if (getKey() == null) { setKey(sessionIdGenerator.generateSessionId()); } // Generate the opaque string the same way if (getOpaque() == null) { setOpaque(sessionIdGenerator.generateSessionId()); } nonces = new LinkedHashMap<String, DigestAuthenticator.NonceInfo>() { private static final long serialVersionUID = 1L; private static final long LOG_SUPPRESS_TIME = 5 * 60 * 1000; private long lastLog = 0; @Override protected boolean removeEldestEntry( Map.Entry<String,NonceInfo> eldest) { // This is called from a sync so keep it simple long currentTime = System.currentTimeMillis(); if (size() > getNonceCacheSize()) { if (lastLog < currentTime && currentTime - eldest.getValue().getTimestamp() < getNonceValidity()) { // Replay attack is possible log.warn(sm.getString( "digestAuthenticator.cacheRemove")); lastLog = currentTime + LOG_SUPPRESS_TIME; } return true; } return false; } }; } private static class DigestInfo { private final String opaque; private final long nonceValidity; private final String key; private final Map<String,NonceInfo> nonces; private boolean validateUri = true; private String userName = null; private String method = null; private String uri = null; private String response = null; private String nonce = null; private String nc = null; private String cnonce = null; private String realmName = null; private String qop = null; private String opaqueReceived = null; private boolean nonceStale = false; public DigestInfo(String opaque, long nonceValidity, String key, Map<String,NonceInfo> nonces, boolean validateUri) { this.opaque = opaque; this.nonceValidity = nonceValidity; this.key = key; this.nonces = nonces; this.validateUri = validateUri; } public String getUsername() { return userName; } public boolean parse(Request request, String authorization) { // Validate the authorization credentials format if (authorization == null) { return false; } Map<String,String> directives; try { directives = HttpParser.parseAuthorizationDigest( new StringReader(authorization)); } catch (IOException e) { return false; } if (directives == null) { return false; } method = request.getMethod(); userName = directives.get("username"); realmName = directives.get("realm"); nonce = directives.get("nonce"); nc = directives.get("nc"); cnonce = directives.get("cnonce"); qop = directives.get("qop"); uri = directives.get("uri"); response = directives.get("response"); opaqueReceived = directives.get("opaque"); return true; } public boolean validate(Request request) { if ( (userName == null) || (realmName == null) || (nonce == null) || (uri == null) || (response == null) ) { return false; } // Validate the URI - should match the request line sent by client if (validateUri) { String uriQuery; String query = request.getQueryString(); if (query == null) { uriQuery = request.getRequestURI(); } else { uriQuery = request.getRequestURI() + "?" + query; } if (!uri.equals(uriQuery)) { // Some clients (older Android) use an absolute URI for // DIGEST but a relative URI in the request line. // request. 2.3.5 < fixed Android version <= 4.0.3 String host = request.getHeader("host"); String scheme = request.getScheme(); if (host != null && !uriQuery.startsWith(scheme)) { StringBuilder absolute = new StringBuilder(); absolute.append(scheme); absolute.append("://"); absolute.append(host); absolute.append(uriQuery); if (!uri.equals(absolute.toString())) { return false; } } else { return false; } } } // Validate the Realm name String lcRealm = getRealmName(request.getContext()); if (!lcRealm.equals(realmName)) { return false; } // Validate the opaque string if (!opaque.equals(opaqueReceived)) { return false; } // Validate nonce int i = nonce.indexOf(":"); if (i < 0 || (i + 1) == nonce.length()) { return false; } long nonceTime; try { nonceTime = Long.parseLong(nonce.substring(0, i)); } catch (NumberFormatException nfe) { return false; } String md5clientIpTimeKey = nonce.substring(i + 1); long currentTime = System.currentTimeMillis(); if ((currentTime - nonceTime) > nonceValidity) { nonceStale = true; synchronized (nonces) { nonces.remove(nonce); } } String serverIpTimeKey = request.getRemoteAddr() + ":" + nonceTime + ":" + key; byte[] buffer = ConcurrentMessageDigest.digestMD5( serverIpTimeKey.getBytes(B2CConverter.ISO_8859_1)); String md5ServerIpTimeKey = MD5Encoder.encode(buffer); if (!md5ServerIpTimeKey.equals(md5clientIpTimeKey)) { return false; } // Validate qop if (qop != null && !QOP.equals(qop)) { return false; } // Validate cnonce and nc // Check if presence of nc and Cnonce is consistent with presence of qop if (qop == null) { if (cnonce != null || nc != null) { return false; } } else { if (cnonce == null || nc == null) { return false; } // RFC 2617 says nc must be 8 digits long. Older Android clients // use 6. 2.3.5 < fixed Android version <= 4.0.3 if (nc.length() < 6 || nc.length() > 8) { return false; } long count; try { count = Long.parseLong(nc, 16); } catch (NumberFormatException nfe) { return false; } NonceInfo info; synchronized (nonces) { info = nonces.get(nonce); } if (info == null) { // Nonce is valid but not in cache. It must have dropped out // of the cache - force a re-authentication nonceStale = true; } else { if (!info.nonceCountValid(count)) { return false; } } } return true; } public boolean isNonceStale() { return nonceStale; } public Principal authenticate(Realm realm) { // Second MD5 digest used to calculate the digest : // MD5(Method + ":" + uri) String a2 = method + ":" + uri; byte[] buffer = ConcurrentMessageDigest.digestMD5( a2.getBytes(B2CConverter.ISO_8859_1)); String md5a2 = MD5Encoder.encode(buffer); return realm.authenticate(userName, response, nonce, nc, cnonce, qop, realmName, md5a2); } } private static class NonceInfo { private volatile long timestamp; private volatile boolean seen[]; private volatile int offset; private volatile int count = 0; public NonceInfo(long currentTime, int seenWindowSize) { this.timestamp = currentTime; seen = new boolean[seenWindowSize]; offset = seenWindowSize / 2; } public synchronized boolean nonceCountValid(long nonceCount) { if ((count - offset) >= nonceCount || (nonceCount > count - offset + seen.length)) { return false; } int checkIndex = (int) ((nonceCount + offset) % seen.length); if (seen[checkIndex]) { return false; } else { seen[checkIndex] = true; seen[count % seen.length] = false; count++; return true; } } public long getTimestamp() { return timestamp; } } }
54,521
Bug 54521 DigestAuthenticator: nonceCountValid() fails in case of simultaneous asynchronous requests of the same client
Concerned components: org.apache.catalina.authenticator.DigestAuthenticator org.apache.catalina.authenticator.DigestAuthenticator.NonceInfo Scenario: A multithreaded client sends two requests within one millisecond. The DigestAuthenticator creates for each request a nonce as well as a NonceInfo instance. The two nonces are equal, as they were created within the same millisecond. When writing data into the cache (method generateNonce()), the second NonceInfo instance overwrites the first one (same key!). Problem: The two client threads then send a second request with a digest authentication header. In both requests, nc (nonce count) is equal 1, as the nonce has been newly created. In the NonceInfo of the first request, array seen is set to true for index ((nonceCount + offset) % seen.length). In the second request the same NonceInfo instance is used, as the instance is retrieved from map nonces using nonce as a key, that is, in both requests the same key is used. Consequently, method nonceCountValid() returns false, as seen[(nonceCount + offset) % seen.length)] has already been set to true. Therefore the authentication fails, although the client has sent a valid digest authentication header. Conclusion: Working with multi-threaded clients with many requests, digest authentication does not function reliably.
resolved fixed
b68bbb8
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-07T11:00:57Z
2013-02-04T15:00:00Z
test/org/apache/catalina/authenticator/TestDigestAuthenticator.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 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.startup.TestTomcat.MapRealm; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.catalina.util.ConcurrentMessageDigest; import org.apache.catalina.util.MD5Encoder; import org.apache.tomcat.util.buf.ByteChunk; public class TestDigestAuthenticator extends TomcatBaseTest { private static String USER = "user"; private static String PWD = "pwd"; private static String ROLE = "role"; private static String URI = "/protected"; private static String QUERY = "?foo=bar"; private static String CONTEXT_PATH = "/foo"; private static String CLIENT_AUTH_HEADER = "authorization"; private static String REALM = "TestRealm"; private static String CNONCE = "cnonce"; private static String NC1 = "00000001"; private static String NC2 = "00000002"; private static String QOP = "auth"; @Test public void testAllValid() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, CNONCE, QOP, true, true); } @Test public void testValidNoQop() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, null, null, true, true); } @Test public void testValidQuery() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI + QUERY, false, true, REALM, true, true, NC1, NC2, CNONCE, QOP, true, true); } @Test public void testInvalidUriFail() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, true, true, REALM, true, true, NC1, NC2, CNONCE, QOP, false, false); } @Test public void testInvalidUriPass() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, true, false, REALM, true, true, NC1, NC2, CNONCE, QOP, true, true); } @Test public void testInvalidRealm() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, "null", true, true, NC1, NC2, CNONCE, QOP, false, false); } @Test public void testInvalidNonce() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, false, true, NC1, NC2, CNONCE, QOP, false, true); } @Test public void testInvalidOpaque() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, false, NC1, NC2, CNONCE, QOP, false, true); } @Test public void testInvalidNc1() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, "null", null, CNONCE, QOP, false, false); } @Test public void testInvalidQop() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, CNONCE, "null", false, false); } @Test public void testInvalidQopCombo1() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, CNONCE, null, false, false); } @Test public void testInvalidQopCombo2() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, null, QOP, false, false); } @Test public void testInvalidQopCombo3() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC2, null, null, false, false); } @Test public void testInvalidQopCombo4() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, CNONCE, QOP, false, false); } @Test public void testInvalidQopCombo5() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, CNONCE, null, false, false); } @Test public void testInvalidQopCombo6() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, null, null, null, QOP, false, false); } @Test public void testReplay() throws Exception { doTest(USER, PWD, CONTEXT_PATH + URI, false, true, REALM, true, true, NC1, NC1, CNONCE, QOP, true, false); } public void doTest(String user, String pwd, String uri, boolean breakUri, boolean validateUri, String realm, boolean useServerNonce, boolean useServerOpaque, String nc1, String nc2, String cnonce, String qop, boolean req2expect200, boolean req3expect200) throws Exception { if (!validateUri) { DigestAuthenticator auth = (DigestAuthenticator) getTomcatInstance().getHost().findChild( CONTEXT_PATH).getPipeline().getFirst(); auth.setValidateUri(false); } getTomcatInstance().start(); String digestUri; if (breakUri) { digestUri = "/broken" + uri; } else { digestUri = uri; } List<String> auth = new ArrayList<>(); auth.add(buildDigestResponse(user, pwd, digestUri, realm, "null", "null", nc1, cnonce, qop)); Map<String,List<String>> reqHeaders = new HashMap<>(); reqHeaders.put(CLIENT_AUTH_HEADER, auth); Map<String,List<String>> respHeaders = new HashMap<>(); // The first request will fail - but we need to extract the nonce ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + uri, bc, reqHeaders, respHeaders); assertEquals(401, rc); assertTrue(bc.getLength() > 0); bc.recycle(); // Second request should succeed (if we use the server nonce) auth.clear(); if (useServerNonce) { if (useServerOpaque) { auth.add(buildDigestResponse(user, pwd, digestUri, realm, getNonce(respHeaders), getOpaque(respHeaders), nc1, cnonce, qop)); } else { auth.add(buildDigestResponse(user, pwd, digestUri, realm, getNonce(respHeaders), "null", nc1, cnonce, qop)); } } else { auth.add(buildDigestResponse(user, pwd, digestUri, realm, "null", getOpaque(respHeaders), nc1, cnonce, QOP)); } rc = getUrl("http://localhost:" + getPort() + uri, bc, reqHeaders, null); if (req2expect200) { assertEquals(200, rc); assertEquals("OK", bc.toString()); } else { assertEquals(401, rc); assertTrue(bc.getLength() > 0); } // Third request should succeed if we increment nc auth.clear(); bc.recycle(); bc.reset(); auth.add(buildDigestResponse(user, pwd, digestUri, realm, getNonce(respHeaders), getOpaque(respHeaders), nc2, cnonce, qop)); rc = getUrl("http://localhost:" + getPort() + uri, bc, reqHeaders, null); if (req3expect200) { assertEquals(200, rc); assertEquals("OK", bc.toString()); } else { assertEquals(401, rc); assertTrue(bc.getLength() > 0); } } @Override public void setUp() throws Exception { super.setUp(); // Configure a context with digest auth and a single protected resource Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctxt = tomcat.addContext(CONTEXT_PATH, System.getProperty("java.io.tmpdir")); // Add protected servlet Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet()); ctxt.addServletMapping(URI, "TesterServlet"); SecurityCollection collection = new SecurityCollection(); collection.addPattern(URI); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); ctxt.addConstraint(sc); // Configure the Realm MapRealm realm = new MapRealm(); realm.addUser(USER, PWD); realm.addUserRole(USER, ROLE); ctxt.setRealm(realm); // Configure the authenticator LoginConfig lc = new LoginConfig(); lc.setAuthMethod("DIGEST"); lc.setRealmName(REALM); ctxt.setLoginConfig(lc); ctxt.getPipeline().addValve(new DigestAuthenticator()); } protected static String getNonce(Map<String,List<String>> respHeaders) { List<String> authHeaders = respHeaders.get(AuthenticatorBase.AUTH_HEADER_NAME); // Assume there is only one String authHeader = authHeaders.iterator().next(); int start = authHeader.indexOf("nonce=\"") + 7; int end = authHeader.indexOf("\"", start); return authHeader.substring(start, end); } protected static String getOpaque(Map<String,List<String>> respHeaders) { List<String> authHeaders = respHeaders.get(AuthenticatorBase.AUTH_HEADER_NAME); // Assume there is only one String authHeader = authHeaders.iterator().next(); int start = authHeader.indexOf("opaque=\"") + 8; int end = authHeader.indexOf("\"", start); return authHeader.substring(start, end); } /* * Notes from RFC2617 * H(data) = MD5(data) * KD(secret, data) = H(concat(secret, ":", data)) * A1 = unq(username-value) ":" unq(realm-value) ":" passwd * A2 = Method ":" digest-uri-value * request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" nc-value ":" unq(cnonce-value) ":" unq(qop-value) ":" H(A2) ) <"> */ private static String buildDigestResponse(String user, String pwd, String uri, String realm, String nonce, String opaque, String nc, String cnonce, String qop) { String a1 = user + ":" + realm + ":" + pwd; String a2 = "GET:" + uri; String md5a1 = digest(a1); String md5a2 = digest(a2); String response; if (qop == null) { response = md5a1 + ":" + nonce + ":" + md5a2; } else { response = md5a1 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + md5a2; } String md5response = digest(response); StringBuilder auth = new StringBuilder(); auth.append("Digest username=\""); auth.append(user); auth.append("\", realm=\""); auth.append(realm); auth.append("\", nonce=\""); auth.append(nonce); auth.append("\", uri=\""); auth.append(uri); auth.append("\", opaque=\""); auth.append(opaque); auth.append("\", response=\""); auth.append(md5response); auth.append("\""); if (qop != null) { auth.append(", qop="); auth.append(qop); auth.append(""); } if (nc != null) { auth.append(", nc="); auth.append(nc); } if (cnonce != null) { auth.append(", cnonce=\""); auth.append(cnonce); auth.append("\""); } return auth.toString(); } private static String digest(String input) { return MD5Encoder.encode( ConcurrentMessageDigest.digestMD5(input.getBytes())); } }
54,456
Bug 54456 ChunkedInputFilter returning EOF when client closes connection without sending end chunk
null
resolved fixed
cc2f8db
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-07T11:55:36Z
2013-01-21T20:26:40Z
java/org/apache/coyote/http11/filters/ChunkedInputFilter.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.filters; import java.io.EOFException; import java.io.IOException; import org.apache.coyote.InputBuffer; import org.apache.coyote.Request; import org.apache.coyote.http11.Constants; import org.apache.coyote.http11.InputFilter; import org.apache.tomcat.util.buf.B2CConverter; 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.MimeHeaders; /** * Chunked input filter. Parses chunked data according to * <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1">http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1</a><br> * * @author Remy Maucherat * @author Filip Hanik */ public class ChunkedInputFilter implements InputFilter { // -------------------------------------------------------------- Constants protected static final String ENCODING_NAME = "chunked"; protected static final ByteChunk ENCODING = new ByteChunk(); // ----------------------------------------------------- Static Initializer static { ENCODING.setBytes(ENCODING_NAME.getBytes(B2CConverter.ISO_8859_1), 0, ENCODING_NAME.length()); } // ----------------------------------------------------- Instance Variables /** * Next buffer in the pipeline. */ protected InputBuffer buffer; /** * Number of bytes remaining in the current chunk. */ protected int remaining = 0; /** * Position in the buffer. */ protected int pos = 0; /** * Last valid byte in the buffer. */ protected int lastValid = 0; /** * Read bytes buffer. */ protected byte[] buf = null; /** * Byte chunk used to read bytes. */ protected final ByteChunk readChunk = new ByteChunk(); /** * Flag set to true when the end chunk has been read. */ protected boolean endChunk = false; /** * Byte chunk used to store trailing headers. */ protected final ByteChunk trailingHeaders = new ByteChunk(); /** * Flag set to true if the next call to doRead() must parse a CRLF pair * before doing anything else. */ protected boolean needCRLFParse = false; /** * Request being parsed. */ private Request request; // ----------------------------------------------------------- Constructors public ChunkedInputFilter(int maxTrailerSize) { this.trailingHeaders.setLimit(maxTrailerSize); } // ---------------------------------------------------- InputBuffer Methods /** * Read bytes. * * @return If the filter does request length control, this value is * significant; it should be the number of bytes consumed from the buffer, * up until the end of the current request body, or the buffer length, * whichever is greater. If the filter does not do request body length * control, the returned value should be -1. */ @Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endChunk) return -1; if(needCRLFParse) { needCRLFParse = false; parseCRLF(false); } if (remaining <= 0) { if (!parseChunkHeader()) { throw new IOException("Invalid chunk header"); } if (endChunk) { parseEndChunk(); return -1; } } int result = 0; if (pos >= lastValid) { readBytes(); } if (remaining > (lastValid - pos)) { result = lastValid - pos; remaining = remaining - result; chunk.setBytes(buf, pos, result); pos = lastValid; } else { result = remaining; chunk.setBytes(buf, pos, remaining); pos = pos + remaining; remaining = 0; //we need a CRLF if ((pos+1) >= lastValid) { //if we call parseCRLF we overrun the buffer here //so we defer it to the next call BZ 11117 needCRLFParse = true; } else { parseCRLF(false); //parse the CRLF immediately } } return result; } // ---------------------------------------------------- InputFilter Methods /** * Read the content length from the request. */ @Override public void setRequest(Request request) { this.request = request; } /** * End the current request. */ @Override public long end() throws IOException { // Consume extra bytes : parse the stream until the end chunk is found while (doRead(readChunk, null) >= 0) { // NOOP: Just consume the input } // Return the number of extra bytes which were consumed return (lastValid - pos); } /** * Amount of bytes still available in a buffer. */ @Override public int available() { return (lastValid - pos); } /** * Set the next buffer in the filter pipeline. */ @Override public void setBuffer(InputBuffer buffer) { this.buffer = buffer; } /** * Make the filter ready to process the next request. */ @Override public void recycle() { remaining = 0; pos = 0; lastValid = 0; endChunk = false; needCRLFParse = false; trailingHeaders.recycle(); } /** * Return the name of the associated encoding; Here, the value is * "identity". */ @Override public ByteChunk getEncodingName() { return ENCODING; } // ------------------------------------------------------ Protected Methods /** * Read bytes from the previous buffer. */ protected int readBytes() throws IOException { int nRead = buffer.doRead(readChunk, null); pos = readChunk.getStart(); lastValid = pos + nRead; buf = readChunk.getBytes(); return nRead; } /** * Parse the header of a chunk. * A chunk header can look like one of the following:<br /> * A10CRLF<br /> * F23;chunk-extension to be ignoredCRLF * * <p> * The letters before CRLF or ';' (whatever comes first) must be valid hex * digits. We should not parse F23IAMGONNAMESSTHISUP34CRLF as a valid * header according to the spec. */ protected boolean parseChunkHeader() throws IOException { int result = 0; boolean eol = false; boolean readDigit = false; boolean trailer = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) return false; } if (buf[pos] == Constants.CR || buf[pos] == Constants.LF) { parseCRLF(false); eol = true; } else if (buf[pos] == Constants.SEMI_COLON) { trailer = true; } else if (!trailer) { //don't read data after the trailer int charValue = HexUtils.getDec(buf[pos]); if (charValue != -1) { readDigit = true; result *= 16; result += charValue; } else { //we shouldn't allow invalid, non hex characters //in the chunked header return false; } } // Parsing the CRLF increments pos if (!eol) { pos++; } } if (!readDigit) return false; if (result == 0) endChunk = true; remaining = result; if (remaining < 0) return false; return true; } /** * Parse CRLF at end of chunk. * * @param tolerant Should tolerant parsing (LF and CRLF) be used? This * is recommended (RFC2616, section 19.3) for message * headers. */ protected void parseCRLF(boolean tolerant) throws IOException { boolean eol = false; boolean crfound = false; while (!eol) { if (pos >= lastValid) { if (readBytes() <= 0) throw new IOException("Invalid CRLF"); } if (buf[pos] == Constants.CR) { if (crfound) throw new IOException("Invalid CRLF, two CR characters encountered."); crfound = true; } else if (buf[pos] == Constants.LF) { if (!tolerant && !crfound) { throw new IOException("Invalid CRLF, no CR character encountered."); } eol = true; } else { throw new IOException("Invalid CRLF"); } pos++; } } /** * Parse end chunk data. */ protected void parseEndChunk() throws IOException { // Handle option trailer headers while (parseHeader()) { // Loop until we run out of headers } } private boolean parseHeader() throws IOException { MimeHeaders headers = request.getMimeHeaders(); byte chr = 0; // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; // CRLF terminates the request if (chr == Constants.CR || chr == Constants.LF) { parseCRLF(false); return false; } // Mark the current buffer position int start = trailingHeaders.getEnd(); // // Reading the header name // Header name is always US-ASCII // boolean colon = false; while (!colon) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr >= Constants.A) && (chr <= Constants.Z)) { chr = (byte) (chr - Constants.LC_OFFSET); } if (chr == Constants.COLON) { colon = true; } else { trailingHeaders.append(chr); } pos++; } MessageBytes headerValue = headers.addValue(trailingHeaders.getBytes(), start, trailingHeaders.getEnd() - start); // Mark the current buffer position start = trailingHeaders.getEnd(); // // Reading the header value (which can be spanned over multiple lines) // boolean eol = false; boolean validLine = true; int lastSignificantChar = 0; while (validLine) { boolean space = true; // Skipping spaces while (space) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr == Constants.SP) || (chr == Constants.HT)) { pos++; } else { space = false; } } // Reading bytes until the end of the line while (!eol) { // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if (chr == Constants.CR || chr == Constants.LF) { parseCRLF(true); eol = true; } else if (chr == Constants.SP) { trailingHeaders.append(chr); } else { trailingHeaders.append(chr); lastSignificantChar = trailingHeaders.getEnd(); } if (!eol) { pos++; } } // Checking the first character of the new line. If the character // is a LWS, then it's a multiline header // Read new bytes if needed if (pos >= lastValid) { if (readBytes() <0) throw new EOFException("Unexpected end of stream whilst reading trailer headers for chunked request"); } chr = buf[pos]; if ((chr != Constants.SP) && (chr != Constants.HT)) { validLine = false; } else { eol = false; // Copying one extra space in the buffer (since there must // be at least one space inserted between the lines) trailingHeaders.append(chr); } } // Set the header value headerValue.setBytes(trailingHeaders.getBytes(), start, lastSignificantChar - start); return true; } }
54,239
Bug 54239 Extensible EL Interpreter
null
resolved fixed
f8ac6a0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-12T14:50:39Z
2012-12-04T11:20:00Z
java/org/apache/jasper/compiler/ELInterpreter.java
54,239
Bug 54239 Extensible EL Interpreter
null
resolved fixed
f8ac6a0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-12T14:50:39Z
2012-12-04T11:20:00Z
java/org/apache/jasper/compiler/ELInterpreterFactory.java
54,239
Bug 54239 Extensible EL Interpreter
null
resolved fixed
f8ac6a0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-12T14:50:39Z
2012-12-04T11:20:00Z
java/org/apache/jasper/compiler/Generator.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.beans.BeanInfo; import java.beans.IntrospectionException; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TimeZone; import java.util.Vector; import javax.el.MethodExpression; import javax.el.ValueExpression; import javax.servlet.jsp.tagext.TagAttributeInfo; import javax.servlet.jsp.tagext.TagInfo; import javax.servlet.jsp.tagext.TagVariableInfo; import javax.servlet.jsp.tagext.VariableInfo; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.jasper.JspCompilationContext; import org.apache.jasper.compiler.Node.NamedAttribute; import org.apache.jasper.runtime.JspRuntimeLibrary; import org.xml.sax.Attributes; /** * Generate Java source from Nodes * * @author Anil K. Vijendran * @author Danno Ferrin * @author Mandar Raje * @author Rajiv Mordani * @author Pierre Delisle * * Tomcat 4.1.x and Tomcat 5: * @author Kin-man Chung * @author Jan Luehe * @author Shawn Bayern * @author Mark Roth * @author Denis Benoit * * Tomcat 6.x * @author Jacob Hookom * @author Remy Maucherat */ class Generator { private static final Class<?>[] OBJECT_CLASS = { Object.class }; private static final String VAR_EXPRESSIONFACTORY = System.getProperty("org.apache.jasper.compiler.Generator.VAR_EXPRESSIONFACTORY", "_el_expressionfactory"); private static final String VAR_INSTANCEMANAGER = System.getProperty("org.apache.jasper.compiler.Generator.VAR_INSTANCEMANAGER", "_jsp_instancemanager"); private static final boolean POOL_TAGS_WITH_EXTENDS = Boolean.getBoolean("org.apache.jasper.compiler.Generator.POOL_TAGS_WITH_EXTENDS"); /* System property that controls if the requirement to have the object * used in jsp:getProperty action to be previously "introduced" * to the JSP processor (see JSP.5.3) is enforced. */ private static final boolean STRICT_GET_PROPERTY = Boolean.valueOf( System.getProperty( "org.apache.jasper.compiler.Generator.STRICT_GET_PROPERTY", "true")).booleanValue(); private final ServletWriter out; private final ArrayList<GenBuffer> methodsBuffered; private final FragmentHelperClass fragmentHelperClass; private final ErrorDispatcher err; private final BeanRepository beanInfo; private final Set<String> varInfoNames; private final JspCompilationContext ctxt; private final boolean isPoolingEnabled; private final boolean breakAtLF; private String jspIdPrefix; private int jspId; private final PageInfo pageInfo; private final Vector<String> tagHandlerPoolNames; private GenBuffer charArrayBuffer; private final DateFormat timestampFormat; /** * @param s * the input string * @return quoted and escaped string, per Java rule */ static String quote(String s) { if (s == null) return "null"; return '"' + escape(s) + '"'; } /** * @param s * the input string * @return escaped string, per Java rule */ static String escape(String s) { if (s == null) return ""; StringBuilder b = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '"') b.append('\\').append('"'); else if (c == '\\') b.append('\\').append('\\'); else if (c == '\n') b.append('\\').append('n'); else if (c == '\r') b.append('\\').append('r'); else b.append(c); } return b.toString(); } /** * Single quote and escape a character */ static String quote(char c) { StringBuilder b = new StringBuilder(); b.append('\''); if (c == '\'') b.append('\\').append('\''); else if (c == '\\') b.append('\\').append('\\'); else if (c == '\n') b.append('\\').append('n'); else if (c == '\r') b.append('\\').append('r'); else b.append(c); b.append('\''); return b.toString(); } private String createJspId() { if (this.jspIdPrefix == null) { StringBuilder sb = new StringBuilder(32); String name = ctxt.getServletJavaFileName(); sb.append("jsp_"); // Cast to long to avoid issue with Integer.MIN_VALUE sb.append(Math.abs((long) name.hashCode())); sb.append('_'); this.jspIdPrefix = sb.toString(); } return this.jspIdPrefix + (this.jspId++); } /** * Generates declarations. This includes "info" of the page directive, and * scriptlet declarations. */ private void generateDeclarations(Node.Nodes page) throws JasperException { class DeclarationVisitor extends Node.Visitor { private boolean getServletInfoGenerated = false; /* * Generates getServletInfo() method that returns the value of the * page directive's 'info' attribute, if present. * * The Validator has already ensured that if the translation unit * contains more than one page directive with an 'info' attribute, * their values match. */ @Override public void visit(Node.PageDirective n) throws JasperException { if (getServletInfoGenerated) { return; } String info = n.getAttributeValue("info"); if (info == null) return; getServletInfoGenerated = true; out.printil("public java.lang.String getServletInfo() {"); out.pushIndent(); out.printin("return "); out.print(quote(info)); out.println(";"); out.popIndent(); out.printil("}"); out.println(); } @Override public void visit(Node.Declaration n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); } // Custom Tags may contain declarations from tag plugins. @Override public void visit(Node.CustomTag n) throws JasperException { if (n.useTagPlugin()) { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } else { visitBody(n); } } } out.println(); page.visit(new DeclarationVisitor()); } /** * Compiles list of tag handler pool names. */ private void compileTagHandlerPoolList(Node.Nodes page) throws JasperException { class TagHandlerPoolVisitor extends Node.Visitor { private final Vector<String> names; /* * Constructor * * @param v Vector of tag handler pool names to populate */ TagHandlerPoolVisitor(Vector<String> v) { names = v; } /* * Gets the name of the tag handler pool for the given custom tag * and adds it to the list of tag handler pool names unless it is * already contained in it. */ @Override public void visit(Node.CustomTag n) throws JasperException { if (!n.implementsSimpleTag()) { String name = createTagHandlerPoolName(n.getPrefix(), n .getLocalName(), n.getAttributes(), n.getNamedAttributeNodes(), n.hasEmptyBody()); n.setTagHandlerPoolName(name); if (!names.contains(name)) { names.add(name); } } visitBody(n); } /* * Creates the name of the tag handler pool whose tag handlers may * be (re)used to service this action. * * @return The name of the tag handler pool */ private String createTagHandlerPoolName(String prefix, String shortName, Attributes attrs, Node.Nodes namedAttrs, boolean hasEmptyBody) { StringBuilder poolName = new StringBuilder(64); poolName.append("_jspx_tagPool_").append(prefix).append('_') .append(shortName); if (attrs != null) { String[] attrNames = new String[attrs.getLength() + namedAttrs.size()]; for (int i = 0; i < attrNames.length; i++) { attrNames[i] = attrs.getQName(i); } for (int i = 0; i < namedAttrs.size(); i++) { attrNames[attrs.getLength() + i] = ((NamedAttribute) namedAttrs.getNode(i)).getQName(); } Arrays.sort(attrNames, Collections.reverseOrder()); if (attrNames.length > 0) { poolName.append('&'); } for (int i = 0; i < attrNames.length; i++) { poolName.append('_'); poolName.append(attrNames[i]); } } if (hasEmptyBody) { poolName.append("_nobody"); } return JspUtil.makeJavaIdentifier(poolName.toString()); } } page.visit(new TagHandlerPoolVisitor(tagHandlerPoolNames)); } private void declareTemporaryScriptingVars(Node.Nodes page) throws JasperException { class ScriptingVarVisitor extends Node.Visitor { private final Vector<String> vars; ScriptingVarVisitor() { vars = new Vector<>(); } @Override public void visit(Node.CustomTag n) throws JasperException { // XXX - Actually there is no need to declare those // "_jspx_" + varName + "_" + nestingLevel variables when we are // inside a JspFragment. if (n.getCustomNestingLevel() > 0) { TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(varInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); if (!vars.contains(tmpVarName)) { vars.add(tmpVarName); out.printin(tagVarInfos[i].getClassName()); out.print(" "); out.print(tmpVarName); out.print(" = "); out.print(null); out.println(";"); } } } } visitBody(n); } } page.visit(new ScriptingVarVisitor()); } /** * Generates the _jspInit() method for instantiating the tag handler pools. * For tag file, _jspInit has to be invoked manually, and the ServletConfig * object explicitly passed. * * In JSP 2.1, we also instantiate an ExpressionFactory */ private void generateInit() { if (ctxt.isTagFile()) { out.printil("private void _jspInit(javax.servlet.ServletConfig config) {"); } else { out.printil("public void _jspInit() {"); } out.pushIndent(); if (isPoolingEnabled) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printin(tagHandlerPoolNames.elementAt(i)); out.print(" = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(");"); } } out.printin(VAR_EXPRESSIONFACTORY); out.print(" = _jspxFactory.getJspApplicationContext("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(".getServletContext()).getExpressionFactory();"); out.printin(VAR_INSTANCEMANAGER); out.print(" = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager("); if (ctxt.isTagFile()) { out.print("config"); } else { out.print("getServletConfig()"); } out.println(");"); out.popIndent(); out.printil("}"); out.println(); } /** * Generates the _jspDestroy() method which is responsible for calling the * release() method on every tag handler in any of the tag handler pools. */ private void generateDestroy() { out.printil("public void _jspDestroy() {"); out.pushIndent(); if (isPoolingEnabled) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printin(tagHandlerPoolNames.elementAt(i)); out.println(".release();"); } } out.popIndent(); out.printil("}"); out.println(); } /** * Generate preamble package name (shared by servlet and tag handler * preamble generation) */ private void genPreamblePackage(String packageName) { if (!"".equals(packageName) && packageName != null) { out.printil("package " + packageName + ";"); out.println(); } } /** * Generate preamble imports (shared by servlet and tag handler preamble * generation) */ private void genPreambleImports() { Iterator<String> iter = pageInfo.getImports().iterator(); while (iter.hasNext()) { out.printin("import "); out.print(iter.next()); out.println(";"); } out.println(); } /** * Generation of static initializers in preamble. For example, dependent * list, el function map, prefix map. (shared by servlet and tag handler * preamble generation) */ private void genPreambleStaticInitializers() { out.printil("private static final javax.servlet.jsp.JspFactory _jspxFactory ="); out.printil(" javax.servlet.jsp.JspFactory.getDefaultFactory();"); out.println(); // Static data for getDependants() out.printil("private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;"); out.println(); Map<String,Long> dependants = pageInfo.getDependants(); Iterator<Entry<String,Long>> iter = dependants.entrySet().iterator(); if (!dependants.isEmpty()) { out.printil("static {"); out.pushIndent(); out.printin("_jspx_dependants = new java.util.HashMap<java.lang.String,java.lang.Long>("); out.print("" + dependants.size()); out.println(");"); while (iter.hasNext()) { Entry<String,Long> entry = iter.next(); out.printin("_jspx_dependants.put(\""); out.print(entry.getKey()); out.print("\", Long.valueOf("); out.print(entry.getValue().toString()); out.println("L));"); } out.popIndent(); out.printil("}"); out.println(); } } /** * Declare tag handler pools (tags of the same type and with the same * attribute set share the same tag handler pool) (shared by servlet and tag * handler preamble generation) * * In JSP 2.1, we also scope an instance of ExpressionFactory */ private void genPreambleClassVariableDeclarations() { if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) { for (int i = 0; i < tagHandlerPoolNames.size(); i++) { out.printil("private org.apache.jasper.runtime.TagHandlerPool " + tagHandlerPoolNames.elementAt(i) + ";"); } out.println(); } out.printin("private javax.el.ExpressionFactory "); out.print(VAR_EXPRESSIONFACTORY); out.println(";"); out.printin("private org.apache.tomcat.InstanceManager "); out.print(VAR_INSTANCEMANAGER); out.println(";"); out.println(); } /** * Declare general-purpose methods (shared by servlet and tag handler * preamble generation) */ private void genPreambleMethods() { // Method used to get compile time file dependencies out.printil("public java.util.Map<java.lang.String,java.lang.Long> getDependants() {"); out.pushIndent(); out.printil("return _jspx_dependants;"); out.popIndent(); out.printil("}"); out.println(); generateInit(); generateDestroy(); } /** * Generates the beginning of the static portion of the servlet. */ private void generatePreamble(Node.Nodes page) throws JasperException { String servletPackageName = ctxt.getServletPackageName(); String servletClassName = ctxt.getServletClassName(); String serviceMethodName = Constants.SERVICE_METHOD_NAME; // First the package name: genPreamblePackage(servletPackageName); // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.print(servletClassName); out.print(" extends "); out.println(pageInfo.getExtends()); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (!pageInfo.isThreadSafe()) { out.println(","); out.printin(" javax.servlet.SingleThreadModel"); } out.println(" {"); out.pushIndent(); // Class body begins here generateDeclarations(page); // Static initializations here genPreambleStaticInitializers(); // Class variable declarations genPreambleClassVariableDeclarations(); // Methods here genPreambleMethods(); // Now the service method out.printin("public void "); out.print(serviceMethodName); out.println("(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)"); out.println(" throws java.io.IOException, javax.servlet.ServletException {"); out.pushIndent(); out.println(); // Local variable declarations out.printil("final javax.servlet.jsp.PageContext pageContext;"); if (pageInfo.isSession()) out.printil("javax.servlet.http.HttpSession session = null;"); if (pageInfo.isErrorPage()) { out.printil("java.lang.Throwable exception = org.apache.jasper.runtime.JspRuntimeLibrary.getThrowable(request);"); out.printil("if (exception != null) {"); out.pushIndent(); out.printil("response.setStatus(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR);"); out.popIndent(); out.printil("}"); } out.printil("final javax.servlet.ServletContext application;"); out.printil("final javax.servlet.ServletConfig config;"); out.printil("javax.servlet.jsp.JspWriter out = null;"); out.printil("final java.lang.Object page = this;"); out.printil("javax.servlet.jsp.JspWriter _jspx_out = null;"); out.printil("javax.servlet.jsp.PageContext _jspx_page_context = null;"); out.println(); declareTemporaryScriptingVars(page); out.println(); out.printil("try {"); out.pushIndent(); out.printin("response.setContentType("); out.print(quote(pageInfo.getContentType())); out.println(");"); if (ctxt.getOptions().isXpoweredBy()) { out.printil("response.addHeader(\"X-Powered-By\", \"JSP/2.1\");"); } out.printil("pageContext = _jspxFactory.getPageContext(this, request, response,"); out.printin("\t\t\t"); out.print(quote(pageInfo.getErrorPage())); out.print(", " + pageInfo.isSession()); out.print(", " + pageInfo.getBuffer()); out.print(", " + pageInfo.isAutoFlush()); out.println(");"); out.printil("_jspx_page_context = pageContext;"); out.printil("application = pageContext.getServletContext();"); out.printil("config = pageContext.getServletConfig();"); if (pageInfo.isSession()) out.printil("session = pageContext.getSession();"); out.printil("out = pageContext.getOut();"); out.printil("_jspx_out = out;"); out.println(); } /** * Generates an XML Prolog, which includes an XML declaration and an XML * doctype declaration. */ private void generateXmlProlog(Node.Nodes page) { /* * An XML declaration is generated under the following conditions: - * 'omit-xml-declaration' attribute of <jsp:output> action is set to * "no" or "false" - JSP document without a <jsp:root> */ String omitXmlDecl = pageInfo.getOmitXmlDecl(); if ((omitXmlDecl != null && !JspUtil.booleanValue(omitXmlDecl)) || (omitXmlDecl == null && page.getRoot().isXmlSyntax() && !pageInfo.hasJspRoot() && !ctxt.isTagFile())) { String cType = pageInfo.getContentType(); String charSet = cType.substring(cType.indexOf("charset=") + 8); out.printil("out.write(\"<?xml version=\\\"1.0\\\" encoding=\\\"" + charSet + "\\\"?>\\n\");"); } /* * Output a DOCTYPE declaration if the doctype-root-element appears. If * doctype-public appears: <!DOCTYPE name PUBLIC "doctypePublic" * "doctypeSystem"> else <!DOCTYPE name SYSTEM "doctypeSystem" > */ String doctypeName = pageInfo.getDoctypeName(); if (doctypeName != null) { String doctypePublic = pageInfo.getDoctypePublic(); String doctypeSystem = pageInfo.getDoctypeSystem(); out.printin("out.write(\"<!DOCTYPE "); out.print(doctypeName); if (doctypePublic == null) { out.print(" SYSTEM \\\""); } else { out.print(" PUBLIC \\\""); out.print(doctypePublic); out.print("\\\" \\\""); } out.print(doctypeSystem); out.println("\\\">\\n\");"); } } /** * A visitor that generates codes for the elements in the page. */ class GenerateVisitor extends Node.Visitor { /* * Hashtable containing introspection information on tag handlers: * <key>: tag prefix <value>: hashtable containing introspection on tag * handlers: <key>: tag short name <value>: introspection info of tag * handler for <prefix:shortName> tag */ private final Hashtable<String,Hashtable<String,TagHandlerInfo>> handlerInfos; private final Hashtable<String,Integer> tagVarNumbers; private String parent; private boolean isSimpleTagParent; // Is parent a SimpleTag? private String pushBodyCountVar; private String simpleTagHandlerVar; private boolean isSimpleTagHandler; private boolean isFragment; private final boolean isTagFile; private ServletWriter out; private final ArrayList<GenBuffer> methodsBuffered; private final FragmentHelperClass fragmentHelperClass; private int methodNesting; private int charArrayCount; private HashMap<String,String> textMap; /** * Constructor. */ public GenerateVisitor(boolean isTagFile, ServletWriter out, ArrayList<GenBuffer> methodsBuffered, FragmentHelperClass fragmentHelperClass) { this.isTagFile = isTagFile; this.out = out; this.methodsBuffered = methodsBuffered; this.fragmentHelperClass = fragmentHelperClass; methodNesting = 0; handlerInfos = new Hashtable<>(); tagVarNumbers = new Hashtable<>(); textMap = new HashMap<>(); } /** * Returns an attribute value, optionally URL encoded. If the value is a * runtime expression, the result is the expression itself, as a string. * If the result is an EL expression, we insert a call to the * interpreter. If the result is a Named Attribute we insert the * generated variable name. Otherwise the result is a string literal, * quoted and escaped. * * @param attr * An JspAttribute object * @param encode * true if to be URL encoded * @param expectedType * the expected type for an EL evaluation (ignored for * attributes that aren't EL expressions) */ private String attributeValue(Node.JspAttribute attr, boolean encode, Class<?> expectedType) { String v = attr.getValue(); if (!attr.isNamedAttribute() && (v == null)) return ""; if (attr.isExpression()) { if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(String.valueOf(" + v + "), request.getCharacterEncoding())"; } return v; } else if (attr.isELInterpreterInput()) { v = JspUtil.interpreterCall(this.isTagFile, v, expectedType, attr.getEL().getMapName(), false); if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(" + v + ", request.getCharacterEncoding())"; } return v; } else if (attr.isNamedAttribute()) { return attr.getNamedAttributeNode().getTemporaryVariableName(); } else { if (encode) { return "org.apache.jasper.runtime.JspRuntimeLibrary.URLEncode(" + quote(v) + ", request.getCharacterEncoding())"; } return quote(v); } } /** * Prints the attribute value specified in the param action, in the form * of name=value string. * * @param n * the parent node for the param action nodes. */ private void printParams(Node n, String pageParam, boolean literal) throws JasperException { class ParamVisitor extends Node.Visitor { String separator; ParamVisitor(String separator) { this.separator = separator; } @Override public void visit(Node.ParamAction n) throws JasperException { out.print(" + "); out.print(separator); out.print(" + "); out.print("org.apache.jasper.runtime.JspRuntimeLibrary." + "URLEncode(" + quote(n.getTextAttribute("name")) + ", request.getCharacterEncoding())"); out.print("+ \"=\" + "); out.print(attributeValue(n.getValue(), true, String.class)); // The separator is '&' after the second use separator = "\"&\""; } } String sep; if (literal) { sep = pageParam.indexOf('?') > 0 ? "\"&\"" : "\"?\""; } else { sep = "((" + pageParam + ").indexOf('?')>0? '&': '?')"; } if (n.getBody() != null) { n.getBody().visit(new ParamVisitor(sep)); } } @Override public void visit(Node.Expression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printin("out.print("); out.printMultiLn(n.getText()); out.println(");"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.Scriptlet n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); out.printMultiLn(n.getText()); out.println(); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.ELExpression n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); if (!pageInfo.isELIgnored() && (n.getEL() != null)) { out.printil("out.write(" + JspUtil.interpreterCall(this.isTagFile, n.getType() + "{" + n.getText() + "}", String.class, n.getEL().getMapName(), false) + ");"); } else { out.printil("out.write(" + quote(n.getType() + "{" + n.getText() + "}") + ");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.IncludeAction n) throws JasperException { String flush = n.getTextAttribute("flush"); Node.JspAttribute page = n.getPage(); boolean isFlush = false; // default to false; if ("true".equals(flush)) isFlush = true; n.setBeginJavaLine(out.getJavaLine()); String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:include was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, " + pageParam); printParams(n, pageParam, page.isLiteral()); out.println(", out, " + isFlush + ");"); n.setEndJavaLine(out.getJavaLine()); } /** * Scans through all child nodes of the given parent for &lt;param&gt; * subelements. For each &lt;param&gt; element, if its value is specified via * a Named Attribute (&lt;jsp:attribute&gt;), generate the code to evaluate * those bodies first. * <p> * If parent is null, simply returns. */ private void prepareParams(Node parent) throws JasperException { if (parent == null) return; Node.Nodes subelements = parent.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node n = subelements.getNode(i); if (n instanceof Node.ParamAction) { Node.Nodes paramSubElements = n.getBody(); for (int j = 0; (paramSubElements != null) && (j < paramSubElements.size()); j++) { Node m = paramSubElements.getNode(j); if (m instanceof Node.NamedAttribute) { generateNamedAttributeValue((Node.NamedAttribute) m); } } } } } } /** * Finds the &lt;jsp:body&gt; subelement of the given parent node. If not * found, null is returned. */ private Node.JspBody findJspBody(Node parent) { Node.JspBody result = null; Node.Nodes subelements = parent.getBody(); for (int i = 0; (subelements != null) && (i < subelements.size()); i++) { Node n = subelements.getNode(i); if (n instanceof Node.JspBody) { result = (Node.JspBody) n; break; } } return result; } @Override public void visit(Node.ForwardAction n) throws JasperException { Node.JspAttribute page = n.getPage(); n.setBeginJavaLine(out.getJavaLine()); out.printil("if (true) {"); // So that javac won't complain about out.pushIndent(); // codes after "return" String pageParam; if (page.isNamedAttribute()) { // If the page for jsp:forward was specified via // jsp:attribute, first generate code to evaluate // that body. pageParam = generateNamedAttributeValue(page .getNamedAttributeNode()); } else { pageParam = attributeValue(page, false, String.class); } // If any of the params have their values specified by // jsp:attribute, prepare those values first. Node jspBody = findJspBody(n); if (jspBody != null) { prepareParams(jspBody); } else { prepareParams(n); } out.printin("_jspx_page_context.forward("); out.print(pageParam); printParams(n, pageParam, page.isLiteral()); out.println(");"); if (isTagFile || isFragment) { out.printil("throw new javax.servlet.jsp.SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); n.setEndJavaLine(out.getJavaLine()); // XXX Not sure if we can eliminate dead codes after this. } @Override public void visit(Node.GetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); n.setBeginJavaLine(out.getJavaLine()); if (beanInfo.checkVariable(name)) { // Bean is defined using useBean, introspect at compile time Class<?> bean = beanInfo.getBeanType(name); String beanName = bean.getCanonicalName(); java.lang.reflect.Method meth = JspRuntimeLibrary .getReadMethod(bean, property); String methodName = meth.getName(); out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString(" + "(((" + beanName + ")_jspx_page_context.findAttribute(" + "\"" + name + "\"))." + methodName + "())));"); } else if (!STRICT_GET_PROPERTY || varInfoNames.contains(name)) { // The object is a custom action with an associated // VariableInfo entry for this name. // Get the class name and then introspect at runtime. out.printil("out.write(org.apache.jasper.runtime.JspRuntimeLibrary.toString" + "(org.apache.jasper.runtime.JspRuntimeLibrary.handleGetProperty" + "(_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\")));"); } else { StringBuilder msg = new StringBuilder(); msg.append("file:"); msg.append(n.getStart()); msg.append(" jsp:getProperty for bean with name '"); msg.append(name); msg.append( "'. Name was not previously introduced as per JSP.5.3"); throw new JasperException(msg.toString()); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.SetProperty n) throws JasperException { String name = n.getTextAttribute("name"); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); Node.JspAttribute value = n.getValue(); n.setBeginJavaLine(out.getJavaLine()); if ("*".equals(property)) { out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspect(" + "_jspx_page_context.findAttribute(" + "\"" + name + "\"), request);"); } else if (value == null) { if (param == null) param = property; // default to same as property out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", request.getParameter(\"" + param + "\"), " + "request, \"" + param + "\", false);"); } else if (value.isExpression()) { out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetProperty(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\","); out.print(attributeValue(value, false, null)); out.println(");"); } else if (value.isELInterpreterInput()) { // We've got to resolve the very call to the interpreter // at runtime since we don't know what type to expect // in the general case; we thus can't hard-wire the call // into the generated code. (XXX We could, however, // optimize the case where the bean is exposed with // <jsp:useBean>, much as the code here does for // getProperty.) // The following holds true for the arguments passed to // JspRuntimeLibrary.handleSetPropertyExpression(): // - 'pageContext' is a VariableResolver. // - 'this' (either the generated Servlet or the generated tag // handler for Tag files) is a FunctionMapper. out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.handleSetPropertyExpression(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + quote(value.getValue()) + ", " + "_jspx_page_context, " + value.getEL().getMapName() + ");"); } else if (value.isNamedAttribute()) { // If the value for setProperty was specified via // jsp:attribute, first generate code to evaluate // that body. String valueVarName = generateNamedAttributeValue(value .getNamedAttributeNode()); out.printil("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", " + valueVarName + ", null, null, false);"); } else { out.printin("org.apache.jasper.runtime.JspRuntimeLibrary.introspecthelper(" + "_jspx_page_context.findAttribute(\"" + name + "\"), \"" + property + "\", "); out.print(attributeValue(value, false, null)); out.println(", null, null, false);"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.UseBean n) throws JasperException { String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); String klass = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); Node.JspAttribute beanName = n.getBeanName(); // If "class" is specified, try an instantiation at compile time boolean generateNew = false; String canonicalName = null; // Canonical name for klass if (klass != null) { try { Class<?> bean = ctxt.getClassLoader().loadClass(klass); if (klass.indexOf('$') >= 0) { // Obtain the canonical type name canonicalName = bean.getCanonicalName(); } else { canonicalName = klass; } int modifiers = bean.getModifiers(); if (!Modifier.isPublic(modifiers) || Modifier.isInterface(modifiers) || Modifier.isAbstract(modifiers)) { throw new Exception("Invalid bean class modifier"); } // Check that there is a 0 arg constructor bean.getConstructor(new Class[] {}); // At compile time, we have determined that the bean class // exists, with a public zero constructor, new() can be // used for bean instantiation. generateNew = true; } catch (Exception e) { // Cannot instantiate the specified class, either a // compilation error or a runtime error will be raised, // depending on a compiler flag. if (ctxt.getOptions() .getErrorOnUseBeanInvalidClassAttribute()) { err.jspError(n, "jsp.error.invalid.bean", klass); } if (canonicalName == null) { // Doing our best here to get a canonical name // from the binary name, should work 99.99% of time. canonicalName = klass.replace('$', '.'); } } if (type == null) { // if type is unspecified, use "class" as type of bean type = canonicalName; } } // JSP.5.1, Sematics, para 1 - lock not required for request or // page scope String scopename = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page String lock = null; if ("request".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.SESSION_SCOPE"; lock = "session"; } else if ("application".equals(scope)) { scopename = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE"; lock = "application"; } n.setBeginJavaLine(out.getJavaLine()); // Declare bean out.printin(type); out.print(' '); out.print(name); out.println(" = null;"); // Lock (if required) while getting or creating bean if (lock != null) { out.printin("synchronized ("); out.print(lock); out.println(") {"); out.pushIndent(); } // Locate bean from context out.printin(name); out.print(" = ("); out.print(type); out.print(") _jspx_page_context.getAttribute("); out.print(quote(name)); out.print(", "); out.print(scopename); out.println(");"); // Create bean /* * Check if bean is already there */ out.printin("if ("); out.print(name); out.println(" == null){"); out.pushIndent(); if (klass == null && beanName == null) { /* * If both class name and beanName is not specified, the bean * must be found locally, otherwise it's an error */ out.printin("throw new java.lang.InstantiationException(\"bean "); out.print(name); out.println(" not found within scope\");"); } else { /* * Instantiate the bean if it is not in the specified scope. */ if (!generateNew) { String binaryName; if (beanName != null) { if (beanName.isNamedAttribute()) { // If the value for beanName was specified via // jsp:attribute, first generate code to evaluate // that body. binaryName = generateNamedAttributeValue(beanName .getNamedAttributeNode()); } else { binaryName = attributeValue(beanName, false, String.class); } } else { // Implies klass is not null binaryName = quote(klass); } out.printil("try {"); out.pushIndent(); out.printin(name); out.print(" = ("); out.print(type); out.print(") java.beans.Beans.instantiate("); out.print("this.getClass().getClassLoader(), "); out.print(binaryName); out.println(");"); out.popIndent(); /* * Note: Beans.instantiate throws ClassNotFoundException if * the bean class is abstract. */ out.printil("} catch (java.lang.ClassNotFoundException exc) {"); out.pushIndent(); out.printil("throw new InstantiationException(exc.getMessage());"); out.popIndent(); out.printil("} catch (java.lang.Exception exc) {"); out.pushIndent(); out.printin("throw new javax.servlet.ServletException("); out.print("\"Cannot create bean of class \" + "); out.print(binaryName); out.println(", exc);"); out.popIndent(); out.printil("}"); // close of try } else { // Implies klass is not null // Generate codes to instantiate the bean class out.printin(name); out.print(" = new "); out.print(canonicalName); out.println("();"); } /* * Set attribute for bean in the specified scope */ out.printin("_jspx_page_context.setAttribute("); out.print(quote(name)); out.print(", "); out.print(name); out.print(", "); out.print(scopename); out.println(");"); // Only visit the body when bean is instantiated visitBody(n); } out.popIndent(); out.printil("}"); // End of lock block if (lock != null) { out.popIndent(); out.printil("}"); } n.setEndJavaLine(out.getJavaLine()); } /** * @return a string for the form 'attr = "value"' */ private String makeAttr(String attr, String value) { if (value == null) return ""; return " " + attr + "=\"" + value + '\"'; } @Override public void visit(Node.PlugIn n) throws JasperException { /** * A visitor to handle &lt;jsp:param&gt; in a plugin */ class ParamVisitor extends Node.Visitor { private final boolean ie; ParamVisitor(boolean ie) { this.ie = ie; } @Override public void visit(Node.ParamAction n) throws JasperException { String name = n.getTextAttribute("name"); if (name.equalsIgnoreCase("object")) name = "java_object"; else if (name.equalsIgnoreCase("type")) name = "java_type"; n.setBeginJavaLine(out.getJavaLine()); // XXX - Fixed a bug here - value used to be output // inline, which is only okay if value is not an EL // expression. Also, key/value pairs for the // embed tag were not being generated correctly. // Double check that this is now the correct behavior. if (ie) { // We want something of the form // out.println( "<param name=\"blah\" // value=\"" + ... + "\">" ); out.printil("out.write( \"<param name=\\\"" + escape(name) + "\\\" value=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\">\" );"); out.printil("out.write(\"\\n\");"); } else { // We want something of the form // out.print( " blah=\"" + ... + "\"" ); out.printil("out.write( \" " + escape(name) + "=\\\"\" + " + attributeValue(n.getValue(), false, String.class) + " + \"\\\"\" );"); } n.setEndJavaLine(out.getJavaLine()); } } String type = n.getTextAttribute("type"); String code = n.getTextAttribute("code"); String name = n.getTextAttribute("name"); Node.JspAttribute height = n.getHeight(); Node.JspAttribute width = n.getWidth(); String hspace = n.getTextAttribute("hspace"); String vspace = n.getTextAttribute("vspace"); String align = n.getTextAttribute("align"); String iepluginurl = n.getTextAttribute("iepluginurl"); String nspluginurl = n.getTextAttribute("nspluginurl"); String codebase = n.getTextAttribute("codebase"); String archive = n.getTextAttribute("archive"); String jreversion = n.getTextAttribute("jreversion"); String widthStr = null; if (width != null) { if (width.isNamedAttribute()) { widthStr = generateNamedAttributeValue(width .getNamedAttributeNode()); } else { widthStr = attributeValue(width, false, String.class); } } String heightStr = null; if (height != null) { if (height.isNamedAttribute()) { heightStr = generateNamedAttributeValue(height .getNamedAttributeNode()); } else { heightStr = attributeValue(height, false, String.class); } } if (iepluginurl == null) iepluginurl = Constants.IE_PLUGIN_URL; if (nspluginurl == null) nspluginurl = Constants.NS_PLUGIN_URL; n.setBeginJavaLine(out.getJavaLine()); // If any of the params have their values specified by // jsp:attribute, prepare those values first. // Look for a params node and prepare its param subelements: Node.JspBody jspBody = findJspBody(n); if (jspBody != null) { Node.Nodes subelements = jspBody.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node m = subelements.getNode(i); if (m instanceof Node.ParamsAction) { prepareParams(m); break; } } } } // XXX - Fixed a bug here - width and height can be set // dynamically. Double-check if this generation is correct. // IE style plugin // <object ...> // First compose the runtime output string String s0 = "<object" + makeAttr("classid", ctxt.getOptions().getIeClassId()) + makeAttr("name", name); String s1 = ""; if (width != null) { s1 = " + \" width=\\\"\" + " + widthStr + " + \"\\\"\""; } String s2 = ""; if (height != null) { s2 = " + \" height=\\\"\" + " + heightStr + " + \"\\\"\""; } String s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("codebase", iepluginurl) + '>'; // Then print the output string to the java file out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_code s0 = "<param name=\"java_code\"" + makeAttr("value", code) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); // <param > for java_codebase if (codebase != null) { s0 = "<param name=\"java_codebase\"" + makeAttr("value", codebase) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for java_archive if (archive != null) { s0 = "<param name=\"java_archive\"" + makeAttr("value", archive) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); } // <param > for type s0 = "<param name=\"type\"" + makeAttr("value", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + '>'; out.printil("out.write(" + quote(s0) + ");"); out.printil("out.write(\"\\n\");"); /* * generate a <param> for each <jsp:param> in the plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(true)); /* * Netscape style plugin part */ out.printil("out.write(" + quote("<comment>") + ");"); out.printil("out.write(\"\\n\");"); s0 = "<EMBED" + makeAttr("type", "application/x-java-" + type + ((jreversion == null) ? "" : ";version=" + jreversion)) + makeAttr("name", name); // s1 and s2 are the same as before. s3 = makeAttr("hspace", hspace) + makeAttr("vspace", vspace) + makeAttr("align", align) + makeAttr("pluginspage", nspluginurl) + makeAttr("java_code", code) + makeAttr("java_codebase", codebase) + makeAttr("java_archive", archive); out.printil("out.write(" + quote(s0) + s1 + s2 + " + " + quote(s3) + ");"); /* * Generate a 'attr = "value"' for each <jsp:param> in plugin body */ if (n.getBody() != null) n.getBody().visit(new ParamVisitor(false)); out.printil("out.write(" + quote("/>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("<noembed>") + ");"); out.printil("out.write(\"\\n\");"); /* * Fallback */ if (n.getBody() != null) { visitBody(n); out.printil("out.write(\"\\n\");"); } out.printil("out.write(" + quote("</noembed>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</comment>") + ");"); out.printil("out.write(\"\\n\");"); out.printil("out.write(" + quote("</object>") + ");"); out.printil("out.write(\"\\n\");"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.NamedAttribute n) throws JasperException { // Don't visit body of this tag - we already did earlier. } @Override public void visit(Node.CustomTag n) throws JasperException { // Use plugin to generate more efficient code if there is one. if (n.useTagPlugin()) { generateTagPlugin(n); return; } TagHandlerInfo handlerInfo = getTagHandlerInfo(n); // Create variable names String baseVar = createTagVarName(n.getQName(), n.getPrefix(), n .getLocalName()); String tagEvalVar = "_jspx_eval_" + baseVar; String tagHandlerVar = "_jspx_th_" + baseVar; String tagPushBodyCountVar = "_jspx_push_body_count_" + baseVar; // If the tag contains no scripting element, generate its codes // to a method. ServletWriter outSave = null; Node.ChildInfo ci = n.getChildInfo(); if (ci.isScriptless() && !ci.hasScriptingVars()) { // The tag handler and its body code can reside in a separate // method if it is scriptless and does not have any scripting // variable defined. String tagMethod = "_jspx_meth_" + baseVar; // Generate a call to this method out.printin("if ("); out.print(tagMethod); out.print("("); if (parent != null) { out.print(parent); out.print(", "); } out.print("_jspx_page_context"); if (pushBodyCountVar != null) { out.print(", "); out.print(pushBodyCountVar); } out.println("))"); out.pushIndent(); out.printil((methodNesting > 0) ? "return true;" : "return;"); out.popIndent(); // Set up new buffer for the method outSave = out; /* * For fragments, their bodies will be generated in fragment * helper classes, and the Java line adjustments will be done * there, hence they are set to null here to avoid double * adjustments. */ GenBuffer genBuffer = new GenBuffer(n, n.implementsSimpleTag() ? null : n.getBody()); methodsBuffered.add(genBuffer); out = genBuffer.getOut(); methodNesting++; // Generate code for method declaration out.println(); out.pushIndent(); out.printin("private boolean "); out.print(tagMethod); out.print("("); if (parent != null) { out.print("javax.servlet.jsp.tagext.JspTag "); out.print(parent); out.print(", "); } out.print("javax.servlet.jsp.PageContext _jspx_page_context"); if (pushBodyCountVar != null) { out.print(", int[] "); out.print(pushBodyCountVar); } out.println(")"); out.printil(" throws java.lang.Throwable {"); out.pushIndent(); // Initialize local variables used in this method. if (!isTagFile) { out.printil("javax.servlet.jsp.PageContext pageContext = _jspx_page_context;"); } out.printil("javax.servlet.jsp.JspWriter out = _jspx_page_context.getOut();"); generateLocalVariables(out, n); } // Add the named objects to the list of 'introduced' names to enable // a later test as per JSP.5.3 VariableInfo[] infos = n.getVariableInfos(); if (infos != null && infos.length > 0) { for (int i = 0; i < infos.length; i++) { VariableInfo info = infos[i]; if (info != null && info.getVarName() != null) pageInfo.getVarInfoNames().add(info.getVarName()); } } TagVariableInfo[] tagInfos = n.getTagVariableInfos(); if (tagInfos != null && tagInfos.length > 0) { for (int i = 0; i < tagInfos.length; i++) { TagVariableInfo tagInfo = tagInfos[i]; if (tagInfo != null) { String name = tagInfo.getNameGiven(); if (name == null) { String nameFromAttribute = tagInfo.getNameFromAttribute(); name = n.getAttributeValue(nameFromAttribute); } pageInfo.getVarInfoNames().add(name); } } } if (n.implementsSimpleTag()) { generateCustomDoTag(n, handlerInfo, tagHandlerVar); } else { /* * Classic tag handler: Generate code for start element, body, * and end element */ generateCustomStart(n, handlerInfo, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); // visit body String tmpParent = parent; parent = tagHandlerVar; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = false; String tmpPushBodyCountVar = null; if (n.implementsTryCatchFinally()) { tmpPushBodyCountVar = pushBodyCountVar; pushBodyCountVar = tagPushBodyCountVar; } boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = false; visitBody(n); parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; if (n.implementsTryCatchFinally()) { pushBodyCountVar = tmpPushBodyCountVar; } isSimpleTagHandler = tmpIsSimpleTagHandler; generateCustomEnd(n, tagHandlerVar, tagEvalVar, tagPushBodyCountVar); } if (ci.isScriptless() && !ci.hasScriptingVars()) { // Generate end of method if (methodNesting > 0) { out.printil("return false;"); } out.popIndent(); out.printil("}"); out.popIndent(); methodNesting--; // restore previous writer out = outSave; } } private static final String DOUBLE_QUOTE = "\\\""; @Override public void visit(Node.UninterpretedTag n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); /* * Write begin tag */ out.printin("out.write(\"<"); out.print(n.getQName()); Attributes attrs = n.getNonTaglibXmlnsAttributes(); if (attrs != null) { for (int i = 0; i < attrs.getLength(); i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } attrs = n.getAttributes(); if (attrs != null) { Node.JspAttribute[] jspAttrs = n.getJspAttributes(); for (int i = 0; i < attrs.getLength(); i++) { out.print(" "); out.print(attrs.getQName(i)); out.print("="); if (jspAttrs[i].isELInterpreterInput()) { out.print("\\\"\" + "); out.print(attributeValue(jspAttrs[i], false, String.class)); out.print(" + \"\\\""); } else { out.print(DOUBLE_QUOTE); out.print(attrs.getValue(i).replace("\"", "&quot;")); out.print(DOUBLE_QUOTE); } } } if (n.getBody() != null) { out.println(">\");"); // Visit tag body visitBody(n); /* * Write end tag */ out.printin("out.write(\"</"); out.print(n.getQName()); out.println(">\");"); } else { out.println("/>\");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.JspElement n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Compute attribute value string for XML-style and named // attributes Hashtable<String,String> map = new Hashtable<>(); Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String value = null; String nvp = null; if (attrs[i].isNamedAttribute()) { NamedAttribute attr = attrs[i].getNamedAttributeNode(); Node.JspAttribute omitAttr = attr.getOmit(); String omit; if (omitAttr == null) { omit = "false"; } else { omit = attributeValue(omitAttr, false, boolean.class); if ("true".equals(omit)) { continue; } } value = generateNamedAttributeValue( attrs[i].getNamedAttributeNode()); if ("false".equals(omit)) { nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\""; } else { nvp = " + (java.lang.Boolean.valueOf(" + omit + ")?\"\":\" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\")"; } } else { value = attributeValue(attrs[i], false, Object.class); nvp = " + \" " + attrs[i].getName() + "=\\\"\" + " + value + " + \"\\\"\""; } map.put(attrs[i].getName(), nvp); } // Write begin tag, using XML-style 'name' attribute as the // element name String elemName = attributeValue(n.getNameAttribute(), false, String.class); out.printin("out.write(\"<\""); out.print(" + " + elemName); // Write remaining attributes Enumeration<String> enumeration = map.keys(); while (enumeration.hasMoreElements()) { String attrName = enumeration.nextElement(); out.print(map.get(attrName)); } // Does the <jsp:element> have nested tags other than // <jsp:attribute> boolean hasBody = false; Node.Nodes subelements = n.getBody(); if (subelements != null) { for (int i = 0; i < subelements.size(); i++) { Node subelem = subelements.getNode(i); if (!(subelem instanceof Node.NamedAttribute)) { hasBody = true; break; } } } if (hasBody) { out.println(" + \">\");"); // Smap should not include the body n.setEndJavaLine(out.getJavaLine()); // Visit tag body visitBody(n); // Write end tag out.printin("out.write(\"</\""); out.print(" + " + elemName); out.println(" + \">\");"); } else { out.println(" + \"/>\");"); n.setEndJavaLine(out.getJavaLine()); } } @Override public void visit(Node.TemplateText n) throws JasperException { String text = n.getText(); int textSize = text.length(); if (textSize == 0) { return; } if (textSize <= 3) { // Special case small text strings n.setBeginJavaLine(out.getJavaLine()); int lineInc = 0; for (int i = 0; i < textSize; i++) { char ch = text.charAt(i); out.printil("out.write(" + quote(ch) + ");"); if (i > 0) { n.addSmap(lineInc); } if (ch == '\n') { lineInc++; } } n.setEndJavaLine(out.getJavaLine()); return; } if (ctxt.getOptions().genStringAsCharArray()) { // Generate Strings as char arrays, for performance ServletWriter caOut; if (charArrayBuffer == null) { charArrayBuffer = new GenBuffer(); caOut = charArrayBuffer.getOut(); caOut.pushIndent(); textMap = new HashMap<>(); } else { caOut = charArrayBuffer.getOut(); } // UTF-8 is up to 4 bytes per character // String constants are limited to 64k bytes // Limit string constants here to 16k characters int textIndex = 0; int textLength = text.length(); while (textIndex < textLength) { int len = 0; if (textLength - textIndex > 16384) { len = 16384; } else { len = textLength - textIndex; } String output = text.substring(textIndex, textIndex + len); String charArrayName = textMap.get(output); if (charArrayName == null) { charArrayName = "_jspx_char_array_" + charArrayCount++; textMap.put(output, charArrayName); caOut.printin("static char[] "); caOut.print(charArrayName); caOut.print(" = "); caOut.print(quote(output)); caOut.println(".toCharArray();"); } n.setBeginJavaLine(out.getJavaLine()); out.printil("out.write(" + charArrayName + ");"); n.setEndJavaLine(out.getJavaLine()); textIndex = textIndex + len; } return; } n.setBeginJavaLine(out.getJavaLine()); out.printin(); StringBuilder sb = new StringBuilder("out.write(\""); int initLength = sb.length(); int count = JspUtil.CHUNKSIZE; int srcLine = 0; // relative to starting source line for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); --count; switch (ch) { case '"': sb.append('\\').append('\"'); break; case '\\': sb.append('\\').append('\\'); break; case '\r': sb.append('\\').append('r'); break; case '\n': sb.append('\\').append('n'); srcLine++; if (breakAtLF || count < 0) { // Generate an out.write() when see a '\n' in template sb.append("\");"); out.println(sb.toString()); if (i < text.length() - 1) { out.printin(); } sb.setLength(initLength); count = JspUtil.CHUNKSIZE; } // add a Smap for this line n.addSmap(srcLine); break; case '\t': // Not sure we need this sb.append('\\').append('t'); break; default: sb.append(ch); } } if (sb.length() > initLength) { sb.append("\");"); out.println(sb.toString()); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.JspBody n) throws JasperException { if (n.getBody() != null) { if (isSimpleTagHandler) { out.printin(simpleTagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, simpleTagHandlerVar); out.println(");"); } else { visitBody(n); } } } @Override public void visit(Node.InvokeAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } // Invoke fragment, unless fragment is null out.printin("if ("); out.print(toGetterMethod(n.getTextAttribute("fragment"))); out.println(" != null) {"); out.pushIndent(); out.printin(toGetterMethod(n.getTextAttribute("fragment"))); out.println(".invoke(_jspx_sout);"); out.popIndent(); out.printil("}"); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.DoBodyAction n) throws JasperException { n.setBeginJavaLine(out.getJavaLine()); // Copy virtual page scope of tag file to page scope of invoking // page out.printil("((org.apache.jasper.runtime.JspContextWrapper) this.jspContext).syncBeforeInvoke();"); // Invoke body String varReaderAttr = n.getTextAttribute("varReader"); String varAttr = n.getTextAttribute("var"); if (varReaderAttr != null || varAttr != null) { out.printil("_jspx_sout = new java.io.StringWriter();"); } else { out.printil("_jspx_sout = null;"); } out.printil("if (getJspBody() != null)"); out.pushIndent(); out.printil("getJspBody().invoke(_jspx_sout);"); out.popIndent(); // Store varReader in appropriate scope if (varReaderAttr != null || varAttr != null) { String scopeName = n.getTextAttribute("scope"); out.printin("_jspx_page_context.setAttribute("); if (varReaderAttr != null) { out.print(quote(varReaderAttr)); out.print(", new java.io.StringReader(_jspx_sout.toString())"); } else { out.print(quote(varAttr)); out.print(", _jspx_sout.toString()"); } if (scopeName != null) { out.print(", "); out.print(getScopeConstant(scopeName)); } out.println(");"); } // Restore EL context out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,getJspContext());"); n.setEndJavaLine(out.getJavaLine()); } @Override public void visit(Node.AttributeGenerator n) throws JasperException { Node.CustomTag tag = n.getTag(); Node.JspAttribute[] attrs = tag.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { if (attrs[i].getName().equals(n.getName())) { out.print(evaluateAttribute(getTagHandlerInfo(tag), attrs[i], tag, null)); break; } } } private TagHandlerInfo getTagHandlerInfo(Node.CustomTag n) throws JasperException { Hashtable<String,TagHandlerInfo> handlerInfosByShortName = handlerInfos.get(n.getPrefix()); if (handlerInfosByShortName == null) { handlerInfosByShortName = new Hashtable<>(); handlerInfos.put(n.getPrefix(), handlerInfosByShortName); } TagHandlerInfo handlerInfo = handlerInfosByShortName.get(n.getLocalName()); if (handlerInfo == null) { handlerInfo = new TagHandlerInfo(n, n.getTagHandlerClass(), err); handlerInfosByShortName.put(n.getLocalName(), handlerInfo); } return handlerInfo; } private void generateTagPlugin(Node.CustomTag n) throws JasperException { if (n.getAtSTag() != null) { n.getAtSTag().visit(this); } visitBody(n); if (n.getAtETag() != null) { n.getAtETag().visit(this); } } private void generateCustomStart(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); out.printin("// "); out.println(n.getQName()); n.setBeginJavaLine(out.getJavaLine()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = tagHandlerClass.getCanonicalName(); if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = "); out.print("("); out.print(tagHandlerClassName); out.print(") "); out.print(n.getTagHandlerPoolName()); out.print(".get("); out.print(tagHandlerClassName); out.println(".class);"); } else { writeNewInstance(tagHandlerVar, tagHandlerClassName); } // includes setting the context generateSetters(n, tagHandlerVar, handlerInfo, false); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } if (n.implementsTryCatchFinally()) { out.printin("int[] "); out.print(tagPushBodyCountVar); out.println(" = new int[] { 0 };"); out.printil("try {"); out.pushIndent(); } out.printin("int "); out.print(tagEvalVar); out.print(" = "); out.print(tagHandlerVar); out.println(".doStartTag();"); if (!n.implementsBodyTag()) { // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); } if (!n.hasEmptyBody()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {"); out.pushIndent(); // Declare NESTED scripting variables declareScriptingVars(n, VariableInfo.NESTED); saveScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); // Assume EVAL_BODY_BUFFERED out.pushIndent(); out.printil("out = _jspx_page_context.pushBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]++;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]++;"); } out.printin(tagHandlerVar); out.println(".setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);"); out.printin(tagHandlerVar); out.println(".doInitBody();"); out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); } else { // Synchronize NESTED scripting variables syncScriptingVars(n, VariableInfo.NESTED); } if (n.implementsIterationTag()) { out.printil("do {"); out.pushIndent(); } } // Map the Java lines that handles start of custom tags to the // JSP line for this tag n.setEndJavaLine(out.getJavaLine()); } private void writeNewInstance(String tagHandlerVar, String tagHandlerClassName) { if (Constants.USE_INSTANCE_MANAGER_FOR_TAGS) { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = ("); out.print(tagHandlerClassName); out.print(")"); out.print(VAR_INSTANCEMANAGER); out.print(".newInstance(\""); out.print(tagHandlerClassName); out.println("\", this.getClass().getClassLoader());"); } else { out.printin(tagHandlerClassName); out.print(" "); out.print(tagHandlerVar); out.print(" = ("); out.print("new "); out.print(tagHandlerClassName); out.println("());"); out.printin(VAR_INSTANCEMANAGER); out.print(".newInstance("); out.print(tagHandlerVar); out.println(");"); } } private void writeDestroyInstance(String tagHandlerVar) { out.printin(VAR_INSTANCEMANAGER); out.print(".destroyInstance("); out.print(tagHandlerVar); out.println(");"); } private void generateCustomEnd(Node.CustomTag n, String tagHandlerVar, String tagEvalVar, String tagPushBodyCountVar) { if (!n.hasEmptyBody()) { if (n.implementsIterationTag()) { out.printin("int evalDoAfterBody = "); out.print(tagHandlerVar); out.println(".doAfterBody();"); // Synchronize AT_BEGIN and NESTED scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); syncScriptingVars(n, VariableInfo.NESTED); out.printil("if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)"); out.pushIndent(); out.printil("break;"); out.popIndent(); out.popIndent(); out.printil("} while (true);"); } restoreScriptingVars(n, VariableInfo.NESTED); if (n.implementsBodyTag()) { out.printin("if ("); out.print(tagEvalVar); out.println(" != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {"); out.pushIndent(); out.printil("out = _jspx_page_context.popBody();"); if (n.implementsTryCatchFinally()) { out.printin(tagPushBodyCountVar); out.println("[0]--;"); } else if (pushBodyCountVar != null) { out.printin(pushBodyCountVar); out.println("[0]--;"); } out.popIndent(); out.printil("}"); } out.popIndent(); // EVAL_BODY out.printil("}"); } out.printin("if ("); out.print(tagHandlerVar); out.println(".doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {"); out.pushIndent(); if (!n.implementsTryCatchFinally()) { if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(n.getTagHandlerPoolName()); out.print(".reuse("); out.print(tagHandlerVar); out.println(");"); } else { out.printin(tagHandlerVar); out.println(".release();"); writeDestroyInstance(tagHandlerVar); } } if (isTagFile || isFragment) { out.printil("throw new javax.servlet.jsp.SkipPageException();"); } else { out.printil((methodNesting > 0) ? "return true;" : "return;"); } out.popIndent(); out.printil("}"); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // TryCatchFinally if (n.implementsTryCatchFinally()) { out.popIndent(); // try out.printil("} catch (java.lang.Throwable _jspx_exception) {"); out.pushIndent(); out.printin("while ("); out.print(tagPushBodyCountVar); out.println("[0]-- > 0)"); out.pushIndent(); out.printil("out = _jspx_page_context.popBody();"); out.popIndent(); out.printin(tagHandlerVar); out.println(".doCatch(_jspx_exception);"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); out.printin(tagHandlerVar); out.println(".doFinally();"); } if (isPoolingEnabled && !(n.implementsJspIdConsumer())) { out.printin(n.getTagHandlerPoolName()); out.print(".reuse("); out.print(tagHandlerVar); out.println(");"); } else { out.printin(tagHandlerVar); out.println(".release();"); writeDestroyInstance(tagHandlerVar); } if (n.implementsTryCatchFinally()) { out.popIndent(); out.printil("}"); } // Declare and synchronize AT_END scripting variables (must do this // outside the try/catch/finally block) declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); restoreScriptingVars(n, VariableInfo.AT_BEGIN); } private void generateCustomDoTag(Node.CustomTag n, TagHandlerInfo handlerInfo, String tagHandlerVar) throws JasperException { Class<?> tagHandlerClass = handlerInfo.getTagHandlerClass(); n.setBeginJavaLine(out.getJavaLine()); out.printin("// "); out.println(n.getQName()); // Declare AT_BEGIN scripting variables declareScriptingVars(n, VariableInfo.AT_BEGIN); saveScriptingVars(n, VariableInfo.AT_BEGIN); String tagHandlerClassName = tagHandlerClass.getCanonicalName(); writeNewInstance(tagHandlerVar, tagHandlerClassName); generateSetters(n, tagHandlerVar, handlerInfo, true); // JspIdConsumer (after context has been set) if (n.implementsJspIdConsumer()) { out.printin(tagHandlerVar); out.print(".setJspId(\""); out.print(createJspId()); out.println("\");"); } // Set the body if (findJspBody(n) == null) { /* * Encapsulate body of custom tag invocation in JspFragment and * pass it to tag handler's setJspBody(), unless tag body is * empty */ if (!n.hasEmptyBody()) { out.printin(tagHandlerVar); out.print(".setJspBody("); generateJspFragment(n, tagHandlerVar); out.println(");"); } } else { /* * Body of tag is the body of the <jsp:body> element. The visit * method for that element is going to encapsulate that * element's body in a JspFragment and pass it to the tag * handler's setJspBody() */ String tmpTagHandlerVar = simpleTagHandlerVar; simpleTagHandlerVar = tagHandlerVar; boolean tmpIsSimpleTagHandler = isSimpleTagHandler; isSimpleTagHandler = true; visitBody(n); simpleTagHandlerVar = tmpTagHandlerVar; isSimpleTagHandler = tmpIsSimpleTagHandler; } out.printin(tagHandlerVar); out.println(".doTag();"); restoreScriptingVars(n, VariableInfo.AT_BEGIN); // Synchronize AT_BEGIN scripting variables syncScriptingVars(n, VariableInfo.AT_BEGIN); // Declare and synchronize AT_END scripting variables declareScriptingVars(n, VariableInfo.AT_END); syncScriptingVars(n, VariableInfo.AT_END); // Resource injection writeDestroyInstance(tagHandlerVar); n.setEndJavaLine(out.getJavaLine()); } private void declareScriptingVars(Node.CustomTag n, int scope) { if (isFragment) { // No need to declare Java variables, if we inside a // JspFragment, because a fragment is always scriptless. return; } List<Object> vec = n.getScriptingVars(scope); if (vec != null) { for (int i = 0; i < vec.size(); i++) { Object elem = vec.get(i); if (elem instanceof VariableInfo) { VariableInfo varInfo = (VariableInfo) elem; if (varInfo.getDeclare()) { out.printin(varInfo.getClassName()); out.print(" "); out.print(varInfo.getVarName()); out.println(" = null;"); } } else { TagVariableInfo tagVarInfo = (TagVariableInfo) elem; if (tagVarInfo.getDeclare()) { String varName = tagVarInfo.getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfo.getNameFromAttribute()); } else if (tagVarInfo.getNameFromAttribute() != null) { // alias continue; } out.printin(tagVarInfo.getClassName()); out.print(" "); out.print(varName); out.println(" = null;"); } } } } } /* * This method is called as part of the custom tag's start element. * * If the given custom tag has a custom nesting level greater than 0, * save the current values of its scripting variables to temporary * variables, so those values may be restored in the tag's end element. * This way, the scripting variables may be synchronized by the given * tag without affecting their original values. */ private void saveScriptingVars(Node.CustomTag n, int scope) { if (n.getCustomNestingLevel() == 0) { return; } if (isFragment) { // No need to declare Java variables, if we inside a // JspFragment, because a fragment is always scriptless. // Thus, there is no need to save/ restore/ sync them. // Note, that JspContextWrapper.syncFoo() methods will take // care of saving/ restoring/ sync'ing of JspContext attributes. return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } List<Object> declaredVariables = n.getScriptingVars(scope); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (declaredVariables.contains(varInfos[i])) continue; String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(tmpVarName); out.print(" = "); out.print(varName); out.println(";"); } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (declaredVariables.contains(tagVarInfos[i])) continue; String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(tmpVarName); out.print(" = "); out.print(varName); out.println(";"); } } } /* * This method is called as part of the custom tag's end element. * * If the given custom tag has a custom nesting level greater than 0, * restore its scripting variables to their original values that were * saved in the tag's start element. */ private void restoreScriptingVars(Node.CustomTag n, int scope) { if (n.getCustomNestingLevel() == 0) { return; } if (isFragment) { // No need to declare Java variables, if we inside a // JspFragment, because a fragment is always scriptless. // Thus, there is no need to save/ restore/ sync them. // Note, that JspContextWrapper.syncFoo() methods will take // care of saving/ restoring/ sync'ing of JspContext attributes. return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } List<Object> declaredVariables = n.getScriptingVars(scope); if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (declaredVariables.contains(varInfos[i])) continue; String varName = varInfos[i].getVarName(); String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(varName); out.print(" = "); out.print(tmpVarName); out.println(";"); } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() != scope) continue; // If the scripting variable has been declared, skip codes // for saving and restoring it. if (declaredVariables.contains(tagVarInfos[i])) continue; String varName = tagVarInfos[i].getNameGiven(); if (varName == null) { varName = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } String tmpVarName = "_jspx_" + varName + "_" + n.getCustomNestingLevel(); out.printin(varName); out.print(" = "); out.print(tmpVarName); out.println(";"); } } } /* * Synchronizes the scripting variables of the given custom tag for the * given scope. */ private void syncScriptingVars(Node.CustomTag n, int scope) { if (isFragment) { // No need to declare Java variables, if we inside a // JspFragment, because a fragment is always scriptless. // Thus, there is no need to save/ restore/ sync them. // Note, that JspContextWrapper.syncFoo() methods will take // care of saving/ restoring/ sync'ing of JspContext attributes. return; } TagVariableInfo[] tagVarInfos = n.getTagVariableInfos(); VariableInfo[] varInfos = n.getVariableInfos(); if ((varInfos.length == 0) && (tagVarInfos.length == 0)) { return; } if (varInfos.length > 0) { for (int i = 0; i < varInfos.length; i++) { if (varInfos[i].getScope() == scope) { out.printin(varInfos[i].getVarName()); out.print(" = ("); out.print(varInfos[i].getClassName()); out.print(") _jspx_page_context.findAttribute("); out.print(quote(varInfos[i].getVarName())); out.println(");"); } } } else { for (int i = 0; i < tagVarInfos.length; i++) { if (tagVarInfos[i].getScope() == scope) { String name = tagVarInfos[i].getNameGiven(); if (name == null) { name = n.getTagData().getAttributeString( tagVarInfos[i].getNameFromAttribute()); } else if (tagVarInfos[i].getNameFromAttribute() != null) { // alias continue; } out.printin(name); out.print(" = ("); out.print(tagVarInfos[i].getClassName()); out.print(") _jspx_page_context.findAttribute("); out.print(quote(name)); out.println(");"); } } } } private String getJspContextVar() { if (this.isTagFile) { return "this.getJspContext()"; } return "_jspx_page_context"; } private String getExpressionFactoryVar() { return VAR_EXPRESSIONFACTORY; } /* * Creates a tag variable name by concatenating the given prefix and * shortName and encoded to make the resultant string a valid Java * Identifier. */ private String createTagVarName(String fullName, String prefix, String shortName) { String varName; synchronized (tagVarNumbers) { varName = prefix + "_" + shortName + "_"; if (tagVarNumbers.get(fullName) != null) { Integer i = tagVarNumbers.get(fullName); varName = varName + i.intValue(); tagVarNumbers.put(fullName, Integer.valueOf(i.intValue() + 1)); } else { tagVarNumbers.put(fullName, Integer.valueOf(1)); varName = varName + "0"; } } return JspUtil.makeJavaIdentifier(varName); } @SuppressWarnings("null") private String evaluateAttribute(TagHandlerInfo handlerInfo, Node.JspAttribute attr, Node.CustomTag n, String tagHandlerVar) throws JasperException { String attrValue = attr.getValue(); if (attrValue == null) { if (attr.isNamedAttribute()) { if (n.checkIfAttributeIsJspFragment(attr.getName())) { // XXX - no need to generate temporary variable here attrValue = generateNamedAttributeJspFragment(attr .getNamedAttributeNode(), tagHandlerVar); } else { attrValue = generateNamedAttributeValue(attr .getNamedAttributeNode()); } } else { return null; } } String localName = attr.getLocalName(); Method m = null; Class<?>[] c = null; if (attr.isDynamic()) { c = OBJECT_CLASS; } else { m = handlerInfo.getSetterMethod(localName); if (m == null) { err.jspError(n, "jsp.error.unable.to_find_method", attr .getName()); } c = m.getParameterTypes(); // XXX assert(c.length > 0) } if (attr.isExpression()) { // Do nothing } else if (attr.isNamedAttribute()) { if (!n.checkIfAttributeIsJspFragment(attr.getName()) && !attr.isDynamic()) { attrValue = convertString(c[0], attrValue, localName, handlerInfo.getPropertyEditorClass(localName), true); } } else if (attr.isELInterpreterInput()) { // results buffer StringBuilder sb = new StringBuilder(64); TagAttributeInfo tai = attr.getTagAttributeInfo(); // generate elContext reference sb.append(getJspContextVar()); sb.append(".getELContext()"); String elContext = sb.toString(); if (attr.getEL() != null && attr.getEL().getMapName() != null) { sb.setLength(0); sb.append("new org.apache.jasper.el.ELContextWrapper("); sb.append(elContext); sb.append(','); sb.append(attr.getEL().getMapName()); sb.append(')'); elContext = sb.toString(); } // reset buffer sb.setLength(0); // create our mark sb.append(n.getStart().toString()); sb.append(" '"); sb.append(attrValue); sb.append('\''); String mark = sb.toString(); // reset buffer sb.setLength(0); // depending on type if (attr.isDeferredInput() || ((tai != null) && ValueExpression.class.getName().equals(tai.getTypeName()))) { sb.append("new org.apache.jasper.el.JspValueExpression("); sb.append(quote(mark)); sb.append(','); sb.append(getExpressionFactoryVar()); sb.append(".createValueExpression("); if (attr.getEL() != null) { // optimize sb.append(elContext); sb.append(','); } sb.append(quote(attrValue)); sb.append(','); sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName())); sb.append("))"); // should the expression be evaluated before passing to // the setter? boolean evaluate = false; if (tai != null && tai.canBeRequestTime()) { evaluate = true; // JSP.2.3.2 } if (attr.isDeferredInput()) { evaluate = false; // JSP.2.3.3 } if (attr.isDeferredInput() && tai != null && tai.canBeRequestTime()) { evaluate = !attrValue.contains("#{"); // JSP.2.3.5 } if (evaluate) { sb.append(".getValue("); sb.append(getJspContextVar()); sb.append(".getELContext()"); sb.append(")"); } attrValue = sb.toString(); } else if (attr.isDeferredMethodInput() || ((tai != null) && MethodExpression.class.getName().equals(tai.getTypeName()))) { sb.append("new org.apache.jasper.el.JspMethodExpression("); sb.append(quote(mark)); sb.append(','); sb.append(getExpressionFactoryVar()); sb.append(".createMethodExpression("); sb.append(elContext); sb.append(','); sb.append(quote(attrValue)); sb.append(','); sb.append(JspUtil.toJavaSourceTypeFromTld(attr.getExpectedTypeName())); sb.append(','); sb.append("new java.lang.Class[] {"); String[] p = attr.getParameterTypeNames(); for (int i = 0; i < p.length; i++) { sb.append(JspUtil.toJavaSourceTypeFromTld(p[i])); sb.append(','); } if (p.length > 0) { sb.setLength(sb.length() - 1); } sb.append("}))"); attrValue = sb.toString(); } else { // run attrValue through the expression interpreter String mapName = (attr.getEL() != null) ? attr.getEL() .getMapName() : null; attrValue = JspUtil.interpreterCall(this.isTagFile, attrValue, c[0], mapName, false); } } else { attrValue = convertString(c[0], attrValue, localName, handlerInfo.getPropertyEditorClass(localName), false); } return attrValue; } /** * Generate code to create a map for the alias variables * * @return the name of the map */ private String generateAliasMap(Node.CustomTag n, String tagHandlerVar) { TagVariableInfo[] tagVars = n.getTagVariableInfos(); String aliasMapVar = null; boolean aliasSeen = false; for (int i = 0; i < tagVars.length; i++) { String nameFrom = tagVars[i].getNameFromAttribute(); if (nameFrom != null) { String aliasedName = n.getAttributeValue(nameFrom); if (aliasedName == null) continue; if (!aliasSeen) { out.printin("java.util.HashMap "); aliasMapVar = tagHandlerVar + "_aliasMap"; out.print(aliasMapVar); out.println(" = new java.util.HashMap();"); aliasSeen = true; } out.printin(aliasMapVar); out.print(".put("); out.print(quote(tagVars[i].getNameGiven())); out.print(", "); out.print(quote(aliasedName)); out.println(");"); } } return aliasMapVar; } private void generateSetters(Node.CustomTag n, String tagHandlerVar, TagHandlerInfo handlerInfo, boolean simpleTag) throws JasperException { // Set context if (simpleTag) { // Generate alias map String aliasMapVar = null; if (n.isTagFile()) { aliasMapVar = generateAliasMap(n, tagHandlerVar); } out.printin(tagHandlerVar); if (aliasMapVar == null) { out.println(".setJspContext(_jspx_page_context);"); } else { out.print(".setJspContext(_jspx_page_context, "); out.print(aliasMapVar); out.println(");"); } } else { out.printin(tagHandlerVar); out.println(".setPageContext(_jspx_page_context);"); } // Set parent if (isTagFile && parent == null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) this ));"); } else if (!simpleTag) { out.printin(tagHandlerVar); out.print(".setParent("); if (parent != null) { if (isSimpleTagParent) { out.print("new javax.servlet.jsp.tagext.TagAdapter("); out.print("(javax.servlet.jsp.tagext.SimpleTag) "); out.print(parent); out.println("));"); } else { out.print("(javax.servlet.jsp.tagext.Tag) "); out.print(parent); out.println(");"); } } else { out.println("null);"); } } else { // The setParent() method need not be called if the value being // passed is null, since SimpleTag instances are not reused if (parent != null) { out.printin(tagHandlerVar); out.print(".setParent("); out.print(parent); out.println(");"); } } // need to handle deferred values and methods Node.JspAttribute[] attrs = n.getJspAttributes(); for (int i = 0; attrs != null && i < attrs.length; i++) { String attrValue = evaluateAttribute(handlerInfo, attrs[i], n, tagHandlerVar); Mark m = n.getStart(); out.printil("// "+m.getFile()+"("+m.getLineNumber()+","+m.getColumnNumber()+") "+ attrs[i].getTagAttributeInfo()); if (attrs[i].isDynamic()) { out.printin(tagHandlerVar); out.print("."); out.print("setDynamicAttribute("); String uri = attrs[i].getURI(); if ("".equals(uri) || (uri == null)) { out.print("null"); } else { out.print("\"" + attrs[i].getURI() + "\""); } out.print(", \""); out.print(attrs[i].getLocalName()); out.print("\", "); out.print(attrValue); out.println(");"); } else { out.printin(tagHandlerVar); out.print("."); out.print(handlerInfo.getSetterMethod( attrs[i].getLocalName()).getName()); out.print("("); out.print(attrValue); out.println(");"); } } } /* * @param c The target class to which to coerce the given string @param * s The string value @param attrName The name of the attribute whose * value is being supplied @param propEditorClass The property editor * for the given attribute @param isNamedAttribute true if the given * attribute is a named attribute (that is, specified using the * jsp:attribute standard action), and false otherwise */ private String convertString(Class<?> c, String s, String attrName, Class<?> propEditorClass, boolean isNamedAttribute) { String quoted = s; if (!isNamedAttribute) { quoted = quote(s); } if (propEditorClass != null) { String className = c.getCanonicalName(); return "(" + className + ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromBeanInfoPropertyEditor(" + className + ".class, \"" + attrName + "\", " + quoted + ", " + propEditorClass.getCanonicalName() + ".class)"; } else if (c == String.class) { return quoted; } else if (c == boolean.class) { return JspUtil.coerceToPrimitiveBoolean(s, isNamedAttribute); } else if (c == Boolean.class) { return JspUtil.coerceToBoolean(s, isNamedAttribute); } else if (c == byte.class) { return JspUtil.coerceToPrimitiveByte(s, isNamedAttribute); } else if (c == Byte.class) { return JspUtil.coerceToByte(s, isNamedAttribute); } else if (c == char.class) { return JspUtil.coerceToChar(s, isNamedAttribute); } else if (c == Character.class) { return JspUtil.coerceToCharacter(s, isNamedAttribute); } else if (c == double.class) { return JspUtil.coerceToPrimitiveDouble(s, isNamedAttribute); } else if (c == Double.class) { return JspUtil.coerceToDouble(s, isNamedAttribute); } else if (c == float.class) { return JspUtil.coerceToPrimitiveFloat(s, isNamedAttribute); } else if (c == Float.class) { return JspUtil.coerceToFloat(s, isNamedAttribute); } else if (c == int.class) { return JspUtil.coerceToInt(s, isNamedAttribute); } else if (c == Integer.class) { return JspUtil.coerceToInteger(s, isNamedAttribute); } else if (c == short.class) { return JspUtil.coerceToPrimitiveShort(s, isNamedAttribute); } else if (c == Short.class) { return JspUtil.coerceToShort(s, isNamedAttribute); } else if (c == long.class) { return JspUtil.coerceToPrimitiveLong(s, isNamedAttribute); } else if (c == Long.class) { return JspUtil.coerceToLong(s, isNamedAttribute); } else if (c == Object.class) { return quoted; } else { String className = c.getCanonicalName(); return "(" + className + ")org.apache.jasper.runtime.JspRuntimeLibrary.getValueFromPropertyEditorManager(" + className + ".class, \"" + attrName + "\", " + quoted + ")"; } } /* * Converts the scope string representation, whose possible values are * "page", "request", "session", and "application", to the corresponding * scope constant. */ private String getScopeConstant(String scope) { String scopeName = "javax.servlet.jsp.PageContext.PAGE_SCOPE"; // Default to page if ("request".equals(scope)) { scopeName = "javax.servlet.jsp.PageContext.REQUEST_SCOPE"; } else if ("session".equals(scope)) { scopeName = "javax.servlet.jsp.PageContext.SESSION_SCOPE"; } else if ("application".equals(scope)) { scopeName = "javax.servlet.jsp.PageContext.APPLICATION_SCOPE"; } return scopeName; } /** * Generates anonymous JspFragment inner class which is passed as an * argument to SimpleTag.setJspBody(). */ private void generateJspFragment(Node n, String tagHandlerVar) throws JasperException { // XXX - A possible optimization here would be to check to see // if the only child of the parent node is TemplateText. If so, // we know there won't be any parameters, etc, so we can // generate a low-overhead JspFragment that just echoes its // body. The implementation of this fragment can come from // the org.apache.jasper.runtime package as a support class. FragmentHelperClass.Fragment fragment = fragmentHelperClass .openFragment(n, methodNesting); ServletWriter outSave = out; out = fragment.getGenBuffer().getOut(); String tmpParent = parent; parent = "_jspx_parent"; boolean isSimpleTagParentSave = isSimpleTagParent; isSimpleTagParent = true; boolean tmpIsFragment = isFragment; isFragment = true; String pushBodyCountVarSave = pushBodyCountVar; if (pushBodyCountVar != null) { // Use a fixed name for push body count, to simplify code gen pushBodyCountVar = "_jspx_push_body_count"; } visitBody(n); out = outSave; parent = tmpParent; isSimpleTagParent = isSimpleTagParentSave; isFragment = tmpIsFragment; pushBodyCountVar = pushBodyCountVarSave; fragmentHelperClass.closeFragment(fragment, methodNesting); // XXX - Need to change pageContext to jspContext if // we're not in a place where pageContext is defined (e.g. // in a fragment or in a tag file. out.print("new " + fragmentHelperClass.getClassName() + "( " + fragment.getId() + ", _jspx_page_context, " + tagHandlerVar + ", " + pushBodyCountVar + ")"); } /** * Generate the code required to obtain the runtime value of the given * named attribute. * * @return The name of the temporary variable the result is stored in. */ public String generateNamedAttributeValue(Node.NamedAttribute n) throws JasperException { String varName = n.getTemporaryVariableName(); // If the only body element for this named attribute node is // template text, we need not generate an extra call to // pushBody and popBody. Maybe we can further optimize // here by getting rid of the temporary variable, but in // reality it looks like javac does this for us. Node.Nodes body = n.getBody(); if (body != null) { boolean templateTextOptimization = false; if (body.size() == 1) { Node bodyElement = body.getNode(0); if (bodyElement instanceof Node.TemplateText) { templateTextOptimization = true; out.printil("java.lang.String " + varName + " = " + quote(((Node.TemplateText) bodyElement) .getText()) + ";"); } } // XXX - Another possible optimization would be for // lone EL expressions (no need to pushBody here either). if (!templateTextOptimization) { out.printil("out = _jspx_page_context.pushBody();"); visitBody(n); out.printil("java.lang.String " + varName + " = " + "((javax.servlet.jsp.tagext.BodyContent)" + "out).getString();"); out.printil("out = _jspx_page_context.popBody();"); } } else { // Empty body must be treated as "" out.printil("java.lang.String " + varName + " = \"\";"); } return varName; } /** * Similar to generateNamedAttributeValue, but create a JspFragment * instead. * * @param n * The parent node of the named attribute * @param tagHandlerVar * The variable the tag handler is stored in, so the fragment * knows its parent tag. * @return The name of the temporary variable the fragment is stored in. */ public String generateNamedAttributeJspFragment(Node.NamedAttribute n, String tagHandlerVar) throws JasperException { String varName = n.getTemporaryVariableName(); out.printin("javax.servlet.jsp.tagext.JspFragment " + varName + " = "); generateJspFragment(n, tagHandlerVar); out.println(";"); return varName; } } private static void generateLocalVariables(ServletWriter out, Node n) throws JasperException { Node.ChildInfo ci; if (n instanceof Node.CustomTag) { ci = ((Node.CustomTag) n).getChildInfo(); } else if (n instanceof Node.JspBody) { ci = ((Node.JspBody) n).getChildInfo(); } else if (n instanceof Node.NamedAttribute) { ci = ((Node.NamedAttribute) n).getChildInfo(); } else { // Cannot access err since this method is static, but at // least flag an error. throw new JasperException("Unexpected Node Type"); // err.getString( // "jsp.error.internal.unexpected_node_type" ) ); } if (ci.hasUseBean()) { out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); } if (ci.hasUseBean() || ci.hasIncludeAction() || ci.hasSetProperty() || ci.hasParamAction()) { out.printil("javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest)_jspx_page_context.getRequest();"); } if (ci.hasIncludeAction()) { out.printil("javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse)_jspx_page_context.getResponse();"); } } /** * Common part of postamble, shared by both servlets and tag files. */ private void genCommonPostamble() { // Append any methods that were generated in the buffer. for (int i = 0; i < methodsBuffered.size(); i++) { GenBuffer methodBuffer = methodsBuffered.get(i); methodBuffer.adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(methodBuffer.toString()); } // Append the helper class if (fragmentHelperClass.isUsed()) { fragmentHelperClass.generatePostamble(); fragmentHelperClass.adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(fragmentHelperClass.toString()); } // Append char array declarations if (charArrayBuffer != null) { out.printMultiLn(charArrayBuffer.toString()); } // Close the class definition out.popIndent(); out.printil("}"); } /** * Generates the ending part of the static portion of the servlet. */ private void generatePostamble() { out.popIndent(); out.printil("} catch (java.lang.Throwable t) {"); out.pushIndent(); out.printil("if (!(t instanceof javax.servlet.jsp.SkipPageException)){"); out.pushIndent(); out.printil("out = _jspx_out;"); out.printil("if (out != null && out.getBufferSize() != 0)"); out.pushIndent(); out.printil("try { out.clearBuffer(); } catch (java.io.IOException e) {}"); out.popIndent(); out.printil("if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);"); out.printil("else throw new ServletException(t);"); out.popIndent(); out.printil("}"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); out.printil("_jspxFactory.releasePageContext(_jspx_page_context);"); out.popIndent(); out.printil("}"); // Close the service method out.popIndent(); out.printil("}"); // Generated methods, helper classes, etc. genCommonPostamble(); } /** * Constructor. */ Generator(ServletWriter out, Compiler compiler) { this.out = out; methodsBuffered = new ArrayList<>(); charArrayBuffer = null; err = compiler.getErrorDispatcher(); ctxt = compiler.getCompilationContext(); fragmentHelperClass = new FragmentHelperClass("Helper"); pageInfo = compiler.getPageInfo(); /* * Temporary hack. If a JSP page uses the "extends" attribute of the * page directive, the _jspInit() method of the generated servlet class * will not be called (it is only called for those generated servlets * that extend HttpJspBase, the default), causing the tag handler pools * not to be initialized and resulting in a NPE. The JSP spec needs to * clarify whether containers can override init() and destroy(). For * now, we just disable tag pooling for pages that use "extends". */ if (pageInfo.getExtends(false) == null || POOL_TAGS_WITH_EXTENDS) { isPoolingEnabled = ctxt.getOptions().isPoolingEnabled(); } else { isPoolingEnabled = false; } beanInfo = pageInfo.getBeanRepository(); varInfoNames = pageInfo.getVarInfoNames(); breakAtLF = ctxt.getOptions().getMappedFile(); if (isPoolingEnabled) { tagHandlerPoolNames = new Vector<>(); } else { tagHandlerPoolNames = null; } timestampFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); timestampFormat.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * The main entry for Generator. * * @param out * The servlet output writer * @param compiler * The compiler * @param page * The input page */ public static void generate(ServletWriter out, Compiler compiler, Node.Nodes page) throws JasperException { Generator gen = new Generator(out, compiler); if (gen.isPoolingEnabled) { gen.compileTagHandlerPoolList(page); } gen.generateCommentHeader(); if (gen.ctxt.isTagFile()) { JasperTagInfo tagInfo = (JasperTagInfo) gen.ctxt.getTagInfo(); gen.generateTagHandlerPreamble(tagInfo, page); if (gen.ctxt.isPrototypeMode()) { return; } gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generateTagHandlerPostamble(tagInfo); } else { gen.generatePreamble(page); gen.generateXmlProlog(page); gen.fragmentHelperClass.generatePreamble(); page.visit(gen.new GenerateVisitor(gen.ctxt.isTagFile(), out, gen.methodsBuffered, gen.fragmentHelperClass)); gen.generatePostamble(); } } private void generateCommentHeader() { out.println("/*"); out.println(" * Generated by the Jasper component of Apache Tomcat"); out.println(" * Version: " + ctxt.getServletContext().getServerInfo()); out.println(" * Generated at: " + timestampFormat.format(new Date()) + " UTC"); out.println(" * Note: The last modified time of this file was set to"); out.println(" * the last modified time of the source file after"); out.println(" * generation to assist with modification tracking."); out.println(" */"); } /* * Generates tag handler preamble. */ private void generateTagHandlerPreamble(JasperTagInfo tagInfo, Node.Nodes tag) throws JasperException { // Generate package declaration String className = tagInfo.getTagClassName(); int lastIndex = className.lastIndexOf('.'); if (lastIndex != -1) { String pkgName = className.substring(0, lastIndex); genPreamblePackage(pkgName); className = className.substring(lastIndex + 1); } // Generate imports genPreambleImports(); // Generate class declaration out.printin("public final class "); out.println(className); out.printil(" extends javax.servlet.jsp.tagext.SimpleTagSupport"); out.printin(" implements org.apache.jasper.runtime.JspSourceDependent"); if (tagInfo.hasDynamicAttributes()) { out.println(","); out.printin(" javax.servlet.jsp.tagext.DynamicAttributes"); } out.println(" {"); out.println(); out.pushIndent(); /* * Class body begins here */ generateDeclarations(tag); // Static initializations here genPreambleStaticInitializers(); out.printil("private javax.servlet.jsp.JspContext jspContext;"); // Declare writer used for storing result of fragment/body invocation // if 'varReader' or 'var' attribute is specified out.printil("private java.io.Writer _jspx_sout;"); // Class variable declarations genPreambleClassVariableDeclarations(); generateSetJspContext(tagInfo); // Tag-handler specific declarations generateTagHandlerAttributes(tagInfo); if (tagInfo.hasDynamicAttributes()) generateSetDynamicAttribute(); // Methods here genPreambleMethods(); // Now the doTag() method out.printil("public void doTag() throws javax.servlet.jsp.JspException, java.io.IOException {"); if (ctxt.isPrototypeMode()) { out.printil("}"); out.popIndent(); out.printil("}"); return; } out.pushIndent(); /* * According to the spec, 'pageContext' must not be made available as an * implicit object in tag files. Declare _jspx_page_context, so we can * share the code generator with JSPs. */ out.printil("javax.servlet.jsp.PageContext _jspx_page_context = (javax.servlet.jsp.PageContext)jspContext;"); // Declare implicit objects. out.printil("javax.servlet.http.HttpServletRequest request = " + "(javax.servlet.http.HttpServletRequest) _jspx_page_context.getRequest();"); out.printil("javax.servlet.http.HttpServletResponse response = " + "(javax.servlet.http.HttpServletResponse) _jspx_page_context.getResponse();"); out.printil("javax.servlet.http.HttpSession session = _jspx_page_context.getSession();"); out.printil("javax.servlet.ServletContext application = _jspx_page_context.getServletContext();"); out.printil("javax.servlet.ServletConfig config = _jspx_page_context.getServletConfig();"); out.printil("javax.servlet.jsp.JspWriter out = jspContext.getOut();"); out.printil("_jspInit(config);"); // set current JspContext on ELContext out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,jspContext);"); generatePageScopedVariables(tagInfo); declareTemporaryScriptingVars(tag); out.println(); out.printil("try {"); out.pushIndent(); } private void generateTagHandlerPostamble(TagInfo tagInfo) { out.popIndent(); // Have to catch Throwable because a classic tag handler // helper method is declared to throw Throwable. out.printil("} catch( java.lang.Throwable t ) {"); out.pushIndent(); out.printil("if( t instanceof javax.servlet.jsp.SkipPageException )"); out.printil(" throw (javax.servlet.jsp.SkipPageException) t;"); out.printil("if( t instanceof java.io.IOException )"); out.printil(" throw (java.io.IOException) t;"); out.printil("if( t instanceof java.lang.IllegalStateException )"); out.printil(" throw (java.lang.IllegalStateException) t;"); out.printil("if( t instanceof javax.servlet.jsp.JspException )"); out.printil(" throw (javax.servlet.jsp.JspException) t;"); out.printil("throw new javax.servlet.jsp.JspException(t);"); out.popIndent(); out.printil("} finally {"); out.pushIndent(); // handle restoring VariableMapper TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); for (int i = 0; i < attrInfos.length; i++) { if (attrInfos[i].isDeferredMethod() || attrInfos[i].isDeferredValue()) { out.printin("_el_variablemapper.setVariable("); out.print(quote(attrInfos[i].getName())); out.print(",_el_ve"); out.print(i); out.println(");"); } } // restore nested JspContext on ELContext out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,super.getJspContext());"); out.printil("((org.apache.jasper.runtime.JspContextWrapper) jspContext).syncEndTagFile();"); if (isPoolingEnabled && !tagHandlerPoolNames.isEmpty()) { out.printil("_jspDestroy();"); } out.popIndent(); out.printil("}"); // Close the doTag method out.popIndent(); out.printil("}"); // Generated methods, helper classes, etc. genCommonPostamble(); } /** * Generates declarations for tag handler attributes, and defines the getter * and setter methods for each. */ private void generateTagHandlerAttributes(TagInfo tagInfo) { if (tagInfo.hasDynamicAttributes()) { out.printil("private java.util.HashMap _jspx_dynamic_attrs = new java.util.HashMap();"); } // Declare attributes TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); for (int i = 0; i < attrInfos.length; i++) { out.printin("private "); if (attrInfos[i].isFragment()) { out.print("javax.servlet.jsp.tagext.JspFragment "); } else { out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName())); out.print(" "); } out.print(JspUtil.makeJavaIdentifierForAttribute( attrInfos[i].getName())); out.println(";"); } out.println(); // Define attribute getter and setter methods for (int i = 0; i < attrInfos.length; i++) { String javaName = JspUtil.makeJavaIdentifierForAttribute(attrInfos[i].getName()); // getter method out.printin("public "); if (attrInfos[i].isFragment()) { out.print("javax.servlet.jsp.tagext.JspFragment "); } else { out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName())); out.print(" "); } out.print(toGetterMethod(attrInfos[i].getName())); out.println(" {"); out.pushIndent(); out.printin("return this."); out.print(javaName); out.println(";"); out.popIndent(); out.printil("}"); out.println(); // setter method out.printin("public void "); out.print(toSetterMethodName(attrInfos[i].getName())); if (attrInfos[i].isFragment()) { out.print("(javax.servlet.jsp.tagext.JspFragment "); } else { out.print("("); out.print(JspUtil.toJavaSourceType(attrInfos[i].getTypeName())); out.print(" "); } out.print(javaName); out.println(") {"); out.pushIndent(); out.printin("this."); out.print(javaName); out.print(" = "); out.print(javaName); out.println(";"); if (ctxt.isTagFile()) { // Tag files should also set jspContext attributes out.printin("jspContext.setAttribute(\""); out.print(attrInfos[i].getName()); out.print("\", "); out.print(javaName); out.println(");"); } out.popIndent(); out.printil("}"); out.println(); } } /* * Generate setter for JspContext so we can create a wrapper and store both * the original and the wrapper. We need the wrapper to mask the page * context from the tag file and simulate a fresh page context. We need the * original to do things like sync AT_BEGIN and AT_END scripting variables. */ private void generateSetJspContext(TagInfo tagInfo) { boolean nestedSeen = false; boolean atBeginSeen = false; boolean atEndSeen = false; // Determine if there are any aliases boolean aliasSeen = false; TagVariableInfo[] tagVars = tagInfo.getTagVariableInfos(); for (int i = 0; i < tagVars.length; i++) { if (tagVars[i].getNameFromAttribute() != null && tagVars[i].getNameGiven() != null) { aliasSeen = true; break; } } if (aliasSeen) { out.printil("public void setJspContext(javax.servlet.jsp.JspContext ctx, java.util.Map aliasMap) {"); } else { out.printil("public void setJspContext(javax.servlet.jsp.JspContext ctx) {"); } out.pushIndent(); out.printil("super.setJspContext(ctx);"); out.printil("java.util.ArrayList _jspx_nested = null;"); out.printil("java.util.ArrayList _jspx_at_begin = null;"); out.printil("java.util.ArrayList _jspx_at_end = null;"); for (int i = 0; i < tagVars.length; i++) { switch (tagVars[i].getScope()) { case VariableInfo.NESTED: if (!nestedSeen) { out.printil("_jspx_nested = new java.util.ArrayList();"); nestedSeen = true; } out.printin("_jspx_nested.add("); break; case VariableInfo.AT_BEGIN: if (!atBeginSeen) { out.printil("_jspx_at_begin = new java.util.ArrayList();"); atBeginSeen = true; } out.printin("_jspx_at_begin.add("); break; case VariableInfo.AT_END: if (!atEndSeen) { out.printil("_jspx_at_end = new java.util.ArrayList();"); atEndSeen = true; } out.printin("_jspx_at_end.add("); break; } // switch out.print(quote(tagVars[i].getNameGiven())); out.println(");"); } if (aliasSeen) { out.printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, aliasMap);"); } else { out.printil("this.jspContext = new org.apache.jasper.runtime.JspContextWrapper(ctx, _jspx_nested, _jspx_at_begin, _jspx_at_end, null);"); } out.popIndent(); out.printil("}"); out.println(); out.printil("public javax.servlet.jsp.JspContext getJspContext() {"); out.pushIndent(); out.printil("return this.jspContext;"); out.popIndent(); out.printil("}"); } /* * Generates implementation of * javax.servlet.jsp.tagext.DynamicAttributes.setDynamicAttribute() method, * which saves each dynamic attribute that is passed in so that a scoped * variable can later be created for it. */ public void generateSetDynamicAttribute() { out.printil("public void setDynamicAttribute(java.lang.String uri, java.lang.String localName, java.lang.Object value) throws javax.servlet.jsp.JspException {"); out.pushIndent(); /* * According to the spec, only dynamic attributes with no uri are to be * present in the Map; all other dynamic attributes are ignored. */ out.printil("if (uri == null)"); out.pushIndent(); out.printil("_jspx_dynamic_attrs.put(localName, value);"); out.popIndent(); out.popIndent(); out.printil("}"); } /* * Creates a page-scoped variable for each declared tag attribute. Also, if * the tag accepts dynamic attributes, a page-scoped variable is made * available for each dynamic attribute that was passed in. */ private void generatePageScopedVariables(JasperTagInfo tagInfo) { // "normal" attributes TagAttributeInfo[] attrInfos = tagInfo.getAttributes(); boolean variableMapperVar = false; for (int i = 0; i < attrInfos.length; i++) { String attrName = attrInfos[i].getName(); // handle assigning deferred vars to VariableMapper, storing // previous values under '_el_ve[i]' for later re-assignment if (attrInfos[i].isDeferredValue() || attrInfos[i].isDeferredMethod()) { // we need to scope the modified VariableMapper for consistency and performance if (!variableMapperVar) { out.printil("javax.el.VariableMapper _el_variablemapper = jspContext.getELContext().getVariableMapper();"); variableMapperVar = true; } out.printin("javax.el.ValueExpression _el_ve"); out.print(i); out.print(" = _el_variablemapper.setVariable("); out.print(quote(attrName)); out.print(','); if (attrInfos[i].isDeferredMethod()) { out.print(VAR_EXPRESSIONFACTORY); out.print(".createValueExpression("); out.print(toGetterMethod(attrName)); out.print(",javax.el.MethodExpression.class)"); } else { out.print(toGetterMethod(attrName)); } out.println(");"); } else { out.printil("if( " + toGetterMethod(attrName) + " != null ) "); out.pushIndent(); out.printin("_jspx_page_context.setAttribute("); out.print(quote(attrName)); out.print(", "); out.print(toGetterMethod(attrName)); out.println(");"); out.popIndent(); } } // Expose the Map containing dynamic attributes as a page-scoped var if (tagInfo.hasDynamicAttributes()) { out.printin("_jspx_page_context.setAttribute(\""); out.print(tagInfo.getDynamicAttributesMapName()); out.print("\", _jspx_dynamic_attrs);"); } } /* * Generates the getter method for the given attribute name. */ private String toGetterMethod(String attrName) { char[] attrChars = attrName.toCharArray(); attrChars[0] = Character.toUpperCase(attrChars[0]); return "get" + new String(attrChars) + "()"; } /* * Generates the setter method name for the given attribute name. */ private String toSetterMethodName(String attrName) { char[] attrChars = attrName.toCharArray(); attrChars[0] = Character.toUpperCase(attrChars[0]); return "set" + new String(attrChars); } /** * Class storing the result of introspecting a custom tag handler. */ private static class TagHandlerInfo { private Hashtable<String, Method> methodMaps; private Hashtable<String, Class<?>> propertyEditorMaps; private Class<?> tagHandlerClass; /** * Constructor. * * @param n * The custom tag whose tag handler class is to be * introspected * @param tagHandlerClass * Tag handler class * @param err * Error dispatcher */ TagHandlerInfo(Node n, Class<?> tagHandlerClass, ErrorDispatcher err) throws JasperException { this.tagHandlerClass = tagHandlerClass; this.methodMaps = new Hashtable<>(); this.propertyEditorMaps = new Hashtable<>(); try { BeanInfo tagClassInfo = Introspector .getBeanInfo(tagHandlerClass); PropertyDescriptor[] pd = tagClassInfo.getPropertyDescriptors(); for (int i = 0; i < pd.length; i++) { /* * FIXME: should probably be checking for things like * pageContext, bodyContent, and parent here -akv */ if (pd[i].getWriteMethod() != null) { methodMaps.put(pd[i].getName(), pd[i].getWriteMethod()); } if (pd[i].getPropertyEditorClass() != null) propertyEditorMaps.put(pd[i].getName(), pd[i] .getPropertyEditorClass()); } } catch (IntrospectionException ie) { err.jspError(n, "jsp.error.introspect.taghandler", tagHandlerClass.getName(), ie); } } /** * XXX */ public Method getSetterMethod(String attrName) { return methodMaps.get(attrName); } /** * XXX */ public Class<?> getPropertyEditorClass(String attrName) { return propertyEditorMaps.get(attrName); } /** * XXX */ public Class<?> getTagHandlerClass() { return tagHandlerClass; } } /** * A class for generating codes to a buffer. Included here are some support * for tracking source to Java lines mapping. */ private static class GenBuffer { /* * For a CustomTag, the codes that are generated at the beginning of the * tag may not be in the same buffer as those for the body of the tag. * Two fields are used here to keep this straight. For codes that do not * corresponds to any JSP lines, they should be null. */ private Node node; private Node.Nodes body; private java.io.CharArrayWriter charWriter; protected ServletWriter out; GenBuffer() { this(null, null); } GenBuffer(Node n, Node.Nodes b) { node = n; body = b; if (body != null) { body.setGeneratedInBuffer(true); } charWriter = new java.io.CharArrayWriter(); out = new ServletWriter(new java.io.PrintWriter(charWriter)); } public ServletWriter getOut() { return out; } @Override public String toString() { return charWriter.toString(); } /** * Adjust the Java Lines. This is necessary because the Java lines * stored with the nodes are relative the beginning of this buffer and * need to be adjusted when this buffer is inserted into the source. */ public void adjustJavaLines(final int offset) { if (node != null) { adjustJavaLine(node, offset); } if (body != null) { try { body.visit(new Node.Visitor() { @Override public void doVisit(Node n) { adjustJavaLine(n, offset); } @Override public void visit(Node.CustomTag n) throws JasperException { Node.Nodes b = n.getBody(); if (b != null && !b.isGeneratedInBuffer()) { // Don't adjust lines for the nested tags that // are also generated in buffers, because the // adjustments will be done elsewhere. b.visit(this); } } }); } catch (JasperException ex) { // Ignore } } } private static void adjustJavaLine(Node n, int offset) { if (n.getBeginJavaLine() > 0) { n.setBeginJavaLine(n.getBeginJavaLine() + offset); n.setEndJavaLine(n.getEndJavaLine() + offset); } } } /** * Keeps track of the generated Fragment Helper Class */ private static class FragmentHelperClass { private static class Fragment { private GenBuffer genBuffer; private int id; public Fragment(int id, Node node) { this.id = id; genBuffer = new GenBuffer(null, node.getBody()); } public GenBuffer getGenBuffer() { return this.genBuffer; } public int getId() { return this.id; } } // True if the helper class should be generated. private boolean used = false; private ArrayList<Fragment> fragments = new ArrayList<>(); private String className; // Buffer for entire helper class private GenBuffer classBuffer = new GenBuffer(); public FragmentHelperClass(String className) { this.className = className; } public String getClassName() { return this.className; } public boolean isUsed() { return this.used; } public void generatePreamble() { ServletWriter out = this.classBuffer.getOut(); out.println(); out.pushIndent(); // Note: cannot be static, as we need to reference things like // _jspx_meth_* out.printil("private class " + className); out.printil(" extends " + "org.apache.jasper.runtime.JspFragmentHelper"); out.printil("{"); out.pushIndent(); out.printil("private javax.servlet.jsp.tagext.JspTag _jspx_parent;"); out.printil("private int[] _jspx_push_body_count;"); out.println(); out.printil("public " + className + "( int discriminator, javax.servlet.jsp.JspContext jspContext, " + "javax.servlet.jsp.tagext.JspTag _jspx_parent, " + "int[] _jspx_push_body_count ) {"); out.pushIndent(); out.printil("super( discriminator, jspContext, _jspx_parent );"); out.printil("this._jspx_parent = _jspx_parent;"); out.printil("this._jspx_push_body_count = _jspx_push_body_count;"); out.popIndent(); out.printil("}"); } public Fragment openFragment(Node parent, int methodNesting) throws JasperException { Fragment result = new Fragment(fragments.size(), parent); fragments.add(result); this.used = true; parent.setInnerClassName(className); ServletWriter out = result.getGenBuffer().getOut(); out.pushIndent(); out.pushIndent(); // XXX - Returns boolean because if a tag is invoked from // within this fragment, the Generator sometimes might // generate code like "return true". This is ignored for now, // meaning only the fragment is skipped. The JSR-152 // expert group is currently discussing what to do in this case. // See comment in closeFragment() if (methodNesting > 0) { out.printin("public boolean invoke"); } else { out.printin("public void invoke"); } out.println(result.getId() + "( " + "javax.servlet.jsp.JspWriter out ) "); out.pushIndent(); // Note: Throwable required because methods like _jspx_meth_* // throw Throwable. out.printil("throws java.lang.Throwable"); out.popIndent(); out.printil("{"); out.pushIndent(); generateLocalVariables(out, parent); return result; } public void closeFragment(Fragment fragment, int methodNesting) { ServletWriter out = fragment.getGenBuffer().getOut(); // XXX - See comment in openFragment() if (methodNesting > 0) { out.printil("return false;"); } else { out.printil("return;"); } out.popIndent(); out.printil("}"); } public void generatePostamble() { ServletWriter out = this.classBuffer.getOut(); // Generate all fragment methods: for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); fragment.getGenBuffer().adjustJavaLines(out.getJavaLine() - 1); out.printMultiLn(fragment.getGenBuffer().toString()); } // Generate postamble: out.printil("public void invoke( java.io.Writer writer )"); out.pushIndent(); out.printil("throws javax.servlet.jsp.JspException"); out.popIndent(); out.printil("{"); out.pushIndent(); out.printil("javax.servlet.jsp.JspWriter out = null;"); out.printil("if( writer != null ) {"); out.pushIndent(); out.printil("out = this.jspContext.pushBody(writer);"); out.popIndent(); out.printil("} else {"); out.pushIndent(); out.printil("out = this.jspContext.getOut();"); out.popIndent(); out.printil("}"); out.printil("try {"); out.pushIndent(); out.printil("Object _jspx_saved_JspContext = this.jspContext.getELContext().getContext(javax.servlet.jsp.JspContext.class);"); out.printil("this.jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,this.jspContext);"); out.printil("switch( this.discriminator ) {"); out.pushIndent(); for (int i = 0; i < fragments.size(); i++) { out.printil("case " + i + ":"); out.pushIndent(); out.printil("invoke" + i + "( out );"); out.printil("break;"); out.popIndent(); } out.popIndent(); out.printil("}"); // switch // restore nested JspContext on ELContext out.printil("jspContext.getELContext().putContext(javax.servlet.jsp.JspContext.class,_jspx_saved_JspContext);"); out.popIndent(); out.printil("}"); // try out.printil("catch( java.lang.Throwable e ) {"); out.pushIndent(); out.printil("if (e instanceof javax.servlet.jsp.SkipPageException)"); out.printil(" throw (javax.servlet.jsp.SkipPageException) e;"); out.printil("throw new javax.servlet.jsp.JspException( e );"); out.popIndent(); out.printil("}"); // catch out.printil("finally {"); out.pushIndent(); out.printil("if( writer != null ) {"); out.pushIndent(); out.printil("this.jspContext.popBody();"); out.popIndent(); out.printil("}"); out.popIndent(); out.printil("}"); // finally out.popIndent(); out.printil("}"); // invoke method out.popIndent(); out.printil("}"); // helper class out.popIndent(); } @Override public String toString() { return classBuffer.toString(); } public void adjustJavaLines(int offset) { for (int i = 0; i < fragments.size(); i++) { Fragment fragment = fragments.get(i); fragment.getGenBuffer().adjustJavaLines(offset); } } } }
54,239
Bug 54239 Extensible EL Interpreter
null
resolved fixed
f8ac6a0
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-12T14:50:39Z
2012-12-04T11:20:00Z
test/org/apache/jasper/compiler/TestELInterpreterFactory.java
54,536
Bug 54536 ErrorReportValve doesn't respect HttpServletResponse.sendError(int sc, String msg)
null
resolved fixed
ef9ed07
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-12T20:06:11Z
2013-02-07T18:00:00Z
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 String report = null; try { report = sm.getString("http." + statusCode); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } if (report == null) { return; } 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(); } }
54,536
Bug 54536 ErrorReportValve doesn't respect HttpServletResponse.sendError(int sc, String msg)
null
resolved fixed
ef9ed07
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-12T20:06:11Z
2013-02-07T18:00:00Z
test/org/apache/catalina/valves/TestErrorReportValve.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 javax.servlet.RequestDispatcher; 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 TestErrorReportValve extends TomcatBaseTest { @Test public void testBug53071() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "errorServlet", new ErrorServlet()); ctx.addServletMapping("/", "errorServlet"); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort()); Assert.assertTrue(res.toString().contains("<p><b>message</b> <u>" + ErrorServlet.ERROR_TEXT + "</u></p>")); } private static final class ErrorServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String ERROR_TEXT = "The wheels fell off."; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setAttribute(RequestDispatcher.ERROR_EXCEPTION, new Throwable(ERROR_TEXT)); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } @Test public void testBug54220DoNotSetNotFound() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "bug54220", new Bug54220Servlet(false)); ctx.addServletMapping("/", "bug54220"); tomcat.start(); ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort(), res, null); Assert.assertNull(res.toString()); Assert.assertEquals(HttpServletResponse.SC_OK, rc); } @Test public void testBug54220SetNotFound() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctx, "bug54220", new Bug54220Servlet(true)); ctx.addServletMapping("/", "bug54220"); tomcat.start(); ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort(), res, null); Assert.assertNull(res.toString()); Assert.assertEquals(HttpServletResponse.SC_NOT_FOUND, rc); } private static final class Bug54220Servlet extends HttpServlet { private static final long serialVersionUID = 1L; private boolean setNotFound; private Bug54220Servlet(boolean setNotFound) { this.setNotFound = setNotFound; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (setNotFound) { resp.setStatus(HttpServletResponse.SC_NOT_FOUND); } } } }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/javax/servlet/http/HttpServletRequest.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 javax.servlet.http; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.ServletRequest; /** * Extends the {@link javax.servlet.ServletRequest} interface to provide request * information for HTTP servlets. * <p> * The servlet container creates an <code>HttpServletRequest</code> object and * passes it as an argument to the servlet's service methods * (<code>doGet</code>, <code>doPost</code>, etc). */ public interface HttpServletRequest extends ServletRequest { /** * String identifier for Basic authentication. Value "BASIC" */ public static final String BASIC_AUTH = "BASIC"; /** * String identifier for Form authentication. Value "FORM" */ public static final String FORM_AUTH = "FORM"; /** * String identifier for Client Certificate authentication. Value * "CLIENT_CERT" */ public static final String CLIENT_CERT_AUTH = "CLIENT_CERT"; /** * String identifier for Digest authentication. Value "DIGEST" */ public static final String DIGEST_AUTH = "DIGEST"; /** * Returns the name of the authentication scheme used to protect the * servlet. All servlet containers support basic, form and client * certificate authentication, and may additionally support digest * authentication. If the servlet is not authenticated <code>null</code> is * returned. * <p> * Same as the value of the CGI variable AUTH_TYPE. * * @return one of the static members BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, * DIGEST_AUTH (suitable for == comparison) or the * container-specific string indicating the authentication scheme, * or <code>null</code> if the request was not authenticated. */ public String getAuthType(); /** * Returns an array containing all of the <code>Cookie</code> objects the * client sent with this request. This method returns <code>null</code> if * no cookies were sent. * * @return an array of all the <code>Cookies</code> included with this * request, or <code>null</code> if the request has no cookies */ public Cookie[] getCookies(); /** * Returns the value of the specified request header as a <code>long</code> * value that represents a <code>Date</code> object. Use this method with * headers that contain dates, such as <code>If-Modified-Since</code>. * <p> * The date is returned as the number of milliseconds since January 1, 1970 * GMT. The header name is case insensitive. * <p> * If the request did not have a header of the specified name, this method * returns -1. If the header can't be converted to a date, the method throws * an <code>IllegalArgumentException</code>. * * @param name * a <code>String</code> specifying the name of the header * @return a <code>long</code> value representing the date specified in the * header expressed as the number of milliseconds since January 1, * 1970 GMT, or -1 if the named header was not included with the * request * @exception IllegalArgumentException * If the header value can't be converted to a date */ public long getDateHeader(String name); /** * Returns the value of the specified request header as a * <code>String</code>. If the request did not include a header of the * specified name, this method returns <code>null</code>. If there are * multiple headers with the same name, this method returns the first head * in the request. The header name is case insensitive. You can use this * method with any request header. * * @param name * a <code>String</code> specifying the header name * @return a <code>String</code> containing the value of the requested * header, or <code>null</code> if the request does not have a * header of that name */ public String getHeader(String name); /** * Returns all the values of the specified request header as an * <code>Enumeration</code> of <code>String</code> objects. * <p> * Some headers, such as <code>Accept-Language</code> can be sent by clients * as several headers each with a different value rather than sending the * header as a comma separated list. * <p> * If the request did not include any headers of the specified name, this * method returns an empty <code>Enumeration</code>. The header name is case * insensitive. You can use this method with any request header. * * @param name * a <code>String</code> specifying the header name * @return an <code>Enumeration</code> containing the values of the requested * header. If the request does not have any headers of that name * return an empty enumeration. If the container does not allow * access to header information, return null */ public Enumeration<String> getHeaders(String name); /** * Returns an enumeration of all the header names this request contains. If * the request has no headers, this method returns an empty enumeration. * <p> * Some servlet containers do not allow servlets to access headers using * this method, in which case this method returns <code>null</code> * * @return an enumeration of all the header names sent with this request; if * the request has no headers, an empty enumeration; if the servlet * container does not allow servlets to use this method, * <code>null</code> */ public Enumeration<String> getHeaderNames(); /** * Returns the value of the specified request header as an <code>int</code>. * If the request does not have a header of the specified name, this method * returns -1. If the header cannot be converted to an integer, this method * throws a <code>NumberFormatException</code>. * <p> * The header name is case insensitive. * * @param name * a <code>String</code> specifying the name of a request header * @return an integer expressing the value of the request header or -1 if the * request doesn't have a header of this name * @exception NumberFormatException * If the header value can't be converted to an * <code>int</code> */ public int getIntHeader(String name); /** * Returns the name of the HTTP method with which this request was made, for * example, GET, POST, or PUT. Same as the value of the CGI variable * REQUEST_METHOD. * * @return a <code>String</code> specifying the name of the method with * which this request was made */ public String getMethod(); /** * Returns any extra path information associated with the URL the client * sent when it made this request. The extra path information follows the * servlet path but precedes the query string and will start with a "/" * character. * <p> * This method returns <code>null</code> if there was no extra path * information. * <p> * Same as the value of the CGI variable PATH_INFO. * * @return a <code>String</code>, decoded by the web container, specifying * extra path information that comes after the servlet path but * before the query string in the request URL; or <code>null</code> * if the URL does not have any extra path information */ public String getPathInfo(); /** * Returns any extra path information after the servlet name but before the * query string, and translates it to a real path. Same as the value of the * CGI variable PATH_TRANSLATED. * <p> * If the URL does not have any extra path information, this method returns * <code>null</code> or the servlet container cannot translate the virtual * path to a real path for any reason (such as when the web application is * executed from an archive). The web container does not decode this string. * * @return a <code>String</code> specifying the real path, or * <code>null</code> if the URL does not have any extra path * information */ public String getPathTranslated(); /** * Returns the portion of the request URI that indicates the context of the * request. The context path always comes first in a request URI. The path * starts with a "/" character but does not end with a "/" character. For * servlets in the default (root) context, this method returns "". The * container does not decode this string. * * @return a <code>String</code> specifying the portion of the request URI * that indicates the context of the request */ public String getContextPath(); /** * Returns the query string that is contained in the request URL after the * path. This method returns <code>null</code> if the URL does not have a * query string. Same as the value of the CGI variable QUERY_STRING. * * @return a <code>String</code> containing the query string or * <code>null</code> if the URL contains no query string. The value * is not decoded by the container. */ public String getQueryString(); /** * Returns the login of the user making this request, if the user has been * authenticated, or <code>null</code> if the user has not been * authenticated. Whether the user name is sent with each subsequent request * depends on the browser and type of authentication. Same as the value of * the CGI variable REMOTE_USER. * * @return a <code>String</code> specifying the login of the user making * this request, or <code>null</code> if the user login is not known */ public String getRemoteUser(); /** * Returns a boolean indicating whether the authenticated user is included * in the specified logical "role". Roles and role membership can be defined * using deployment descriptors. If the user has not been authenticated, the * method returns <code>false</code>. * * @param role * a <code>String</code> specifying the name of the role * @return a <code>boolean</code> indicating whether the user making this * request belongs to a given role; <code>false</code> if the user * has not been authenticated */ public boolean isUserInRole(String role); /** * Returns a <code>java.security.Principal</code> object containing the name * of the current authenticated user. If the user has not been * authenticated, the method returns <code>null</code>. * * @return a <code>java.security.Principal</code> containing the name of the * user making this request; <code>null</code> if the user has not * been authenticated */ public java.security.Principal getUserPrincipal(); /** * Returns the session ID specified by the client. This may not be the same * as the ID of the current valid session for this request. If the client * did not specify a session ID, this method returns <code>null</code>. * * @return a <code>String</code> specifying the session ID, or * <code>null</code> if the request did not specify a session ID * @see #isRequestedSessionIdValid */ public String getRequestedSessionId(); /** * Returns the part of this request's URL from the protocol name up to the * query string in the first line of the HTTP request. The web container * does not decode this String. For example: * <table summary="Examples of Returned Values"> * <tr align=left> * <th>First line of HTTP request</th> * <th>Returned Value</th> * <tr> * <td>POST /some/path.html HTTP/1.1 * <td> * <td>/some/path.html * <tr> * <td>GET http://foo.bar/a.html HTTP/1.0 * <td> * <td>/a.html * <tr> * <td>HEAD /xyz?a=b HTTP/1.1 * <td> * <td>/xyz * </table> * <p> * To reconstruct an URL with a scheme and host, use * {@link #getRequestURL}. * * @return a <code>String</code> containing the part of the URL from the * protocol name up to the query string * @see #getRequestURL */ public String getRequestURI(); /** * 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 string, * 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 */ public StringBuffer getRequestURL(); /** * Returns the part of this request's URL that calls the servlet. This path * starts with a "/" character and includes either the servlet name or a * path to the servlet, but does not include any extra path information or a * query string. Same as the value of the CGI variable SCRIPT_NAME. * <p> * This method will return an empty string ("") if the servlet used to * process this request was matched using the "/*" pattern. * * @return a <code>String</code> containing the name or path of the servlet * being called, as specified in the request URL, decoded, or an * empty string if the servlet used to process the request is * matched using the "/*" pattern. */ public String getServletPath(); /** * Returns the current <code>HttpSession</code> associated with this request * or, if there is no current session and <code>create</code> is true, * returns a new session. * <p> * If <code>create</code> is <code>false</code> and the request has no valid * <code>HttpSession</code>, this method returns <code>null</code>. * <p> * To make sure the session is properly maintained, you must call this * method before the response is committed. If the container is using * cookies to maintain session integrity and is asked to create a new * session when the response is committed, an IllegalStateException is * thrown. * * @param create * <code>true</code> to create a new session for this request if * necessary; <code>false</code> to return <code>null</code> if * there's no current session * @return the <code>HttpSession</code> associated with this request or * <code>null</code> if <code>create</code> is <code>false</code> * and the request has no valid session * @see #getSession() */ public HttpSession getSession(boolean create); /** * Returns the current session associated with this request, or if the * request does not have a session, creates one. * * @return the <code>HttpSession</code> associated with this request * @see #getSession(boolean) */ public HttpSession getSession(); /** * Checks whether the requested session ID is still valid. * * @return <code>true</code> if this request has an id for a valid session * in the current session context; <code>false</code> otherwise * @see #getRequestedSessionId * @see #getSession */ public boolean isRequestedSessionIdValid(); /** * Checks whether the requested session ID came in as a cookie. * * @return <code>true</code> if the session ID came in as a cookie; * otherwise, <code>false</code> * @see #getSession */ public boolean isRequestedSessionIdFromCookie(); /** * Checks whether the requested session ID came in as part of the request * URL. * * @return <code>true</code> if the session ID came in as part of a URL; * otherwise, <code>false</code> * @see #getSession */ public boolean isRequestedSessionIdFromURL(); /** * @deprecated As of Version 2.1 of the Java Servlet API, use * {@link #isRequestedSessionIdFromURL} instead. */ @SuppressWarnings("dep-ann") // Spec API does not use @Deprecated public boolean isRequestedSessionIdFromUrl(); /** * Triggers the same authentication process as would be triggered if the * request is for a resource that is protected by a security constraint. * * @param response The response to use to return any authentication * challenge * @return <code>true</code> if the user is successfully authenticated and * <code>false</code> if not * * @since Servlet 3.0 */ public boolean authenticate(HttpServletResponse response) throws IOException, ServletException; /** * Authenticate the provided user name and password and then associated the * authenticated user with the request. * * @param username The user name to authenticate * @param password The password to use to authenticate the user * * @throws ServletException * If any of {@link #getRemoteUser()}, * {@link #getUserPrincipal()} or {@link #getAuthType()} are * non-null, if the configured authenticator does not support * user name and password authentication or if the * authentication fails * @since Servlet 3.0 */ public void login(String username, String password) throws ServletException; /** * Removes any authenticated user from the request. * * @throws ServletException * If the logout fails * @since Servlet 3.0 */ public void logout() throws ServletException; /** * Return a collection of all uploaded Parts. * * @return A collection of all uploaded Parts. * @throws IOException * if an I/O error occurs * @throws IllegalStateException * if size limits are exceeded * @throws ServletException * if the request is not multipart/form-data * @since Servlet 3.0 */ public Collection<Part> getParts() throws IOException, ServletException; /** * Gets the named Part or null if the Part does not exist. Triggers upload * of all Parts. * * @param name * @return The named Part or null if the Part does not exist * @throws IOException * if an I/O error occurs * @throws IllegalStateException * if size limits are exceeded * @throws ServletException * if the request is not multipart/form-data * @since Servlet 3.0 */ public Part getPart(String name) throws IOException, ServletException; /** * Start the HTTP upgrade process and pass the connection to the provided * protocol handler once the current request/response pair has completed * processing. Calling this method sets the response status to {@link * HttpServletResponse#SC_SWITCHING_PROTOCOLS} and flushes the response. * Protocol specific headers must have already been set before this method * is called. * * @since Servlet 3.1 */ public void upgrade(HttpUpgradeHandler handler) throws java.io.IOException; }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/javax/servlet/http/HttpServletRequestWrapper.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 javax.servlet.http; import java.io.IOException; import java.util.Collection; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.ServletRequestWrapper; /** * Provides a convenient implementation of the HttpServletRequest interface that * can be subclassed by developers wishing to adapt the request to a Servlet. * This class implements the Wrapper or Decorator pattern. Methods default to * calling through to the wrapped request object. * * @see javax.servlet.http.HttpServletRequest * @since v 2.3 */ public class HttpServletRequestWrapper extends ServletRequestWrapper implements HttpServletRequest { /** * Constructs a request object wrapping the given request. * * @throws java.lang.IllegalArgumentException * if the request is null */ public HttpServletRequestWrapper(HttpServletRequest request) { super(request); } private HttpServletRequest _getHttpServletRequest() { return (HttpServletRequest) super.getRequest(); } /** * The default behavior of this method is to return getAuthType() on the * wrapped request object. */ @Override public String getAuthType() { return this._getHttpServletRequest().getAuthType(); } /** * The default behavior of this method is to return getCookies() on the * wrapped request object. */ @Override public Cookie[] getCookies() { return this._getHttpServletRequest().getCookies(); } /** * The default behavior of this method is to return getDateHeader(String * name) on the wrapped request object. */ @Override public long getDateHeader(String name) { return this._getHttpServletRequest().getDateHeader(name); } /** * The default behavior of this method is to return getHeader(String name) * on the wrapped request object. */ @Override public String getHeader(String name) { return this._getHttpServletRequest().getHeader(name); } /** * The default behavior of this method is to return getHeaders(String name) * on the wrapped request object. */ @Override public Enumeration<String> getHeaders(String name) { return this._getHttpServletRequest().getHeaders(name); } /** * The default behavior of this method is to return getHeaderNames() on the * wrapped request object. */ @Override public Enumeration<String> getHeaderNames() { return this._getHttpServletRequest().getHeaderNames(); } /** * The default behavior of this method is to return getIntHeader(String * name) on the wrapped request object. */ @Override public int getIntHeader(String name) { return this._getHttpServletRequest().getIntHeader(name); } /** * The default behavior of this method is to return getMethod() on the * wrapped request object. */ @Override public String getMethod() { return this._getHttpServletRequest().getMethod(); } /** * The default behavior of this method is to return getPathInfo() on the * wrapped request object. */ @Override public String getPathInfo() { return this._getHttpServletRequest().getPathInfo(); } /** * The default behavior of this method is to return getPathTranslated() on * the wrapped request object. */ @Override public String getPathTranslated() { return this._getHttpServletRequest().getPathTranslated(); } /** * The default behavior of this method is to return getContextPath() on the * wrapped request object. */ @Override public String getContextPath() { return this._getHttpServletRequest().getContextPath(); } /** * The default behavior of this method is to return getQueryString() on the * wrapped request object. */ @Override public String getQueryString() { return this._getHttpServletRequest().getQueryString(); } /** * The default behavior of this method is to return getRemoteUser() on the * wrapped request object. */ @Override public String getRemoteUser() { return this._getHttpServletRequest().getRemoteUser(); } /** * The default behavior of this method is to return isUserInRole(String * role) on the wrapped request object. */ @Override public boolean isUserInRole(String role) { return this._getHttpServletRequest().isUserInRole(role); } /** * The default behavior of this method is to return getUserPrincipal() on * the wrapped request object. */ @Override public java.security.Principal getUserPrincipal() { return this._getHttpServletRequest().getUserPrincipal(); } /** * The default behavior of this method is to return getRequestedSessionId() * on the wrapped request object. */ @Override public String getRequestedSessionId() { return this._getHttpServletRequest().getRequestedSessionId(); } /** * The default behavior of this method is to return getRequestURI() on the * wrapped request object. */ @Override public String getRequestURI() { return this._getHttpServletRequest().getRequestURI(); } /** * The default behavior of this method is to return getRequestURL() on the * wrapped request object. */ @Override public StringBuffer getRequestURL() { return this._getHttpServletRequest().getRequestURL(); } /** * The default behavior of this method is to return getServletPath() on the * wrapped request object. */ @Override public String getServletPath() { return this._getHttpServletRequest().getServletPath(); } /** * The default behavior of this method is to return getSession(boolean * create) on the wrapped request object. */ @Override public HttpSession getSession(boolean create) { return this._getHttpServletRequest().getSession(create); } /** * The default behavior of this method is to return getSession() on the * wrapped request object. */ @Override public HttpSession getSession() { return this._getHttpServletRequest().getSession(); } /** * The default behavior of this method is to return * isRequestedSessionIdValid() on the wrapped request object. */ @Override public boolean isRequestedSessionIdValid() { return this._getHttpServletRequest().isRequestedSessionIdValid(); } /** * The default behavior of this method is to return * isRequestedSessionIdFromCookie() on the wrapped request object. */ @Override public boolean isRequestedSessionIdFromCookie() { return this._getHttpServletRequest().isRequestedSessionIdFromCookie(); } /** * The default behavior of this method is to return * isRequestedSessionIdFromURL() on the wrapped request object. */ @Override public boolean isRequestedSessionIdFromURL() { return this._getHttpServletRequest().isRequestedSessionIdFromURL(); } /** * The default behavior of this method is to return * isRequestedSessionIdFromUrl() on the wrapped request object. * * @deprecated As of Version 3.0 of the Java Servlet API */ @Override @SuppressWarnings("dep-ann") // Spec API does not use @Deprecated public boolean isRequestedSessionIdFromUrl() { return this._getHttpServletRequest().isRequestedSessionIdFromUrl(); } /** * {@inheritDoc} * <p> * The default behavior of this method is to return * {@link HttpServletRequest#authenticate(HttpServletResponse)} * on the wrapped request object. * * @since Servlet 3.0 */ @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return this._getHttpServletRequest().authenticate(response); } /** * {@inheritDoc} * <p> * The default behavior of this method is to return * {@link HttpServletRequest#login(String, String)} * on the wrapped request object. * * @since Servlet 3.0 */ @Override public void login(String username, String password) throws ServletException { this._getHttpServletRequest().login(username, password); } /** * {@inheritDoc} * <p> * The default behavior of this method is to return * {@link HttpServletRequest#logout()} * on the wrapped request object. * * @since Servlet 3.0 */ @Override public void logout() throws ServletException { this._getHttpServletRequest().logout(); } /** * {@inheritDoc} * <p> * The default behavior of this method is to return * {@link HttpServletRequest#getParts()} * on the wrapped request object. * * @since Servlet 3.0 */ @Override public Collection<Part> getParts() throws IOException, ServletException { return this._getHttpServletRequest().getParts(); } /** * {@inheritDoc} * <p> * The default behavior of this method is to return * {@link HttpServletRequest#getPart(String)} * on the wrapped request object. * * @since Servlet 3.0 */ @Override public Part getPart(String name) throws IOException, ServletException { return this._getHttpServletRequest().getPart(name); } /** * {@inheritDoc} * <p> * The default behavior of this method is to return * {@link HttpServletRequest#upgrade(HttpUpgradeHandler)} * on the wrapped request object. * * @since Servlet 3.1 */ @Override public void upgrade(HttpUpgradeHandler handler) throws java.io.IOException { this._getHttpServletRequest().upgrade(handler); } }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/javax/servlet/http/HttpSessionIdListener.java
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
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.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.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.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 (not recycled). */ 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(); } public boolean isAsyncOperation() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC_OPERATION, 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 void upgrade(HttpUpgradeHandler handler) throws IOException { 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 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); } } /** * 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); } /** * 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(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.getFilename() == 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,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/org/apache/catalina/connector/RequestFacade.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.IOException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.Collection; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; 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.Globals; import org.apache.catalina.security.SecurityUtil; import org.apache.tomcat.util.res.StringManager; /** * Facade class that wraps a Coyote request object. * All methods are delegated to the wrapped request. * * @author Craig R. McClanahan * @author Remy Maucherat * @author Jean-Francois Arcand * @version $Id$ */ @SuppressWarnings("deprecation") public class RequestFacade implements HttpServletRequest { // ----------------------------------------------------------- DoPrivileged private final class GetAttributePrivilegedAction implements PrivilegedAction<Enumeration<String>> { @Override public Enumeration<String> run() { return request.getAttributeNames(); } } private final class GetParameterMapPrivilegedAction implements PrivilegedAction<Map<String,String[]>> { @Override public Map<String,String[]> run() { return request.getParameterMap(); } } private final class GetRequestDispatcherPrivilegedAction implements PrivilegedAction<RequestDispatcher> { private final String path; public GetRequestDispatcherPrivilegedAction(String path){ this.path = path; } @Override public RequestDispatcher run() { return request.getRequestDispatcher(path); } } private final class GetParameterPrivilegedAction implements PrivilegedAction<String> { public String name; public GetParameterPrivilegedAction(String name){ this.name = name; } @Override public String run() { return request.getParameter(name); } } private final class GetParameterNamesPrivilegedAction implements PrivilegedAction<Enumeration<String>> { @Override public Enumeration<String> run() { return request.getParameterNames(); } } private final class GetParameterValuePrivilegedAction implements PrivilegedAction<String[]> { public String name; public GetParameterValuePrivilegedAction(String name){ this.name = name; } @Override public String[] run() { return request.getParameterValues(name); } } private final class GetCookiesPrivilegedAction implements PrivilegedAction<Cookie[]> { @Override public Cookie[] run() { return request.getCookies(); } } private final class GetCharacterEncodingPrivilegedAction implements PrivilegedAction<String> { @Override public String run() { return request.getCharacterEncoding(); } } private final class GetHeadersPrivilegedAction implements PrivilegedAction<Enumeration<String>> { private final String name; public GetHeadersPrivilegedAction(String name){ this.name = name; } @Override public Enumeration<String> run() { return request.getHeaders(name); } } private final class GetHeaderNamesPrivilegedAction implements PrivilegedAction<Enumeration<String>> { @Override public Enumeration<String> run() { return request.getHeaderNames(); } } private final class GetLocalePrivilegedAction implements PrivilegedAction<Locale> { @Override public Locale run() { return request.getLocale(); } } private final class GetLocalesPrivilegedAction implements PrivilegedAction<Enumeration<Locale>> { @Override public Enumeration<Locale> run() { return request.getLocales(); } } private final class GetSessionPrivilegedAction implements PrivilegedAction<HttpSession> { private final boolean create; public GetSessionPrivilegedAction(boolean create){ this.create = create; } @Override public HttpSession run() { return request.getSession(create); } } // ----------------------------------------------------------- Constructors /** * Construct a wrapper for the specified request. * * @param request The request to be wrapped */ public RequestFacade(Request request) { this.request = request; } // ----------------------------------------------------- Instance Variables /** * The wrapped request. */ protected Request request = null; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); // --------------------------------------------------------- Public Methods /** * Clear facade. */ public void clear() { request = null; } /** * Prevent cloning the facade. */ @Override protected Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException(); } // ------------------------------------------------- ServletRequest Methods @Override public Object getAttribute(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetAttributePrivilegedAction()); } else { return request.getAttributeNames(); } } @Override public String getCharacterEncoding() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetCharacterEncodingPrivilegedAction()); } else { return request.getCharacterEncoding(); } } @Override public void setCharacterEncoding(String env) throws java.io.UnsupportedEncodingException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setCharacterEncoding(env); } @Override public int getContentLength() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContentLength(); } @Override public String getContentType() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContentType(); } @Override public ServletInputStream getInputStream() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getInputStream(); } @Override public String getParameter(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterPrivilegedAction(name)); } else { return request.getParameter(name); } } @Override public Enumeration<String> getParameterNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterNamesPrivilegedAction()); } else { return request.getParameterNames(); } } @Override public String[] getParameterValues(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } String[] ret = null; /* * Clone the returned array only if there is a security manager * in place, so that performance won't suffer in the non-secure case */ if (SecurityUtil.isPackageProtectionEnabled()){ ret = AccessController.doPrivileged( new GetParameterValuePrivilegedAction(name)); if (ret != null) { ret = ret.clone(); } } else { ret = request.getParameterValues(name); } return ret; } @Override public Map<String,String[]> getParameterMap() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetParameterMapPrivilegedAction()); } else { return request.getParameterMap(); } } @Override public String getProtocol() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getProtocol(); } @Override public String getScheme() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getScheme(); } @Override public String getServerName() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServerName(); } @Override public int getServerPort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServerPort(); } @Override public BufferedReader getReader() throws IOException { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getReader(); } @Override public String getRemoteAddr() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteAddr(); } @Override public String getRemoteHost() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteHost(); } @Override public void setAttribute(String name, Object o) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.setAttribute(name, o); } @Override public void removeAttribute(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } request.removeAttribute(name); } @Override public Locale getLocale() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetLocalePrivilegedAction()); } else { return request.getLocale(); } } @Override public Enumeration<Locale> getLocales() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetLocalesPrivilegedAction()); } else { return request.getLocales(); } } @Override public boolean isSecure() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isSecure(); } @Override public RequestDispatcher getRequestDispatcher(String path) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetRequestDispatcherPrivilegedAction(path)); } else { return request.getRequestDispatcher(path); } } @Override public String getRealPath(String path) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRealPath(path); } @Override public String getAuthType() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getAuthType(); } @Override public Cookie[] getCookies() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } Cookie[] ret = null; /* * Clone the returned array only if there is a security manager * in place, so that performance won't suffer in the non-secure case */ if (SecurityUtil.isPackageProtectionEnabled()){ ret = AccessController.doPrivileged( new GetCookiesPrivilegedAction()); if (ret != null) { ret = ret.clone(); } } else { ret = request.getCookies(); } return ret; } @Override public long getDateHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getDateHeader(name); } @Override public String getHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getHeader(name); } @Override public Enumeration<String> getHeaders(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetHeadersPrivilegedAction(name)); } else { return request.getHeaders(name); } } @Override public Enumeration<String> getHeaderNames() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (Globals.IS_SECURITY_ENABLED){ return AccessController.doPrivileged( new GetHeaderNamesPrivilegedAction()); } else { return request.getHeaderNames(); } } @Override public int getIntHeader(String name) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getIntHeader(name); } @Override public String getMethod() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getMethod(); } @Override public String getPathInfo() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getPathInfo(); } @Override public String getPathTranslated() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getPathTranslated(); } @Override public String getContextPath() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getContextPath(); } @Override public String getQueryString() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getQueryString(); } @Override public String getRemoteUser() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemoteUser(); } @Override public boolean isUserInRole(String role) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isUserInRole(role); } @Override public java.security.Principal getUserPrincipal() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getUserPrincipal(); } @Override public String getRequestedSessionId() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestedSessionId(); } @Override public String getRequestURI() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestURI(); } @Override public StringBuffer getRequestURL() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRequestURL(); } @Override public String getServletPath() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServletPath(); } @Override public HttpSession getSession(boolean create) { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } if (SecurityUtil.isPackageProtectionEnabled()){ return AccessController. doPrivileged(new GetSessionPrivilegedAction(create)); } else { return request.getSession(create); } } @Override public HttpSession getSession() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return getSession(true); } @Override public boolean isRequestedSessionIdValid() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdValid(); } @Override public boolean isRequestedSessionIdFromCookie() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromCookie(); } @Override public boolean isRequestedSessionIdFromURL() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromURL(); } @Override public boolean isRequestedSessionIdFromUrl() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.isRequestedSessionIdFromURL(); } @Override public String getLocalAddr() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalAddr(); } @Override public String getLocalName() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalName(); } @Override public int getLocalPort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getLocalPort(); } @Override public int getRemotePort() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getRemotePort(); } @Override public ServletContext getServletContext() { if (request == null) { throw new IllegalStateException( sm.getString("requestFacade.nullRequest")); } return request.getServletContext(); } @Override public AsyncContext startAsync() throws IllegalStateException { return request.startAsync(); } @Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) throws IllegalStateException { return this.request.startAsync(request, response); } @Override public boolean isAsyncStarted() { return request.isAsyncStarted(); } @Override public boolean isAsyncSupported() { return request.isAsyncSupported(); } @Override public AsyncContext getAsyncContext() { return request.getAsyncContext(); } @Override public DispatcherType getDispatcherType() { return request.getDispatcherType(); } @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return request.authenticate(response); } @Override public void login(String username, String password) throws ServletException { request.login(username, password); } @Override public void logout() throws ServletException { request.logout(); } @Override public Collection<Part> getParts() throws IllegalStateException, IOException, ServletException { return request.getParts(); } @Override public Part getPart(String name) throws IllegalStateException, IOException, ServletException { return request.getPart(name); } public boolean getAllowTrace() { return request.getConnector().getAllowTrace(); } /** * {@inheritDoc} * * @since Servlet 3.1 */ @Override public long getContentLengthLong() { return request.getContentLengthLong(); } /** * {@inheritDoc} * * @since Servlet 3.1 */ @Override public void upgrade(HttpUpgradeHandler handler) throws IOException { request.upgrade(handler); } }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20: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.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 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.getName()); if (listener instanceof ServletContextListener || listener instanceof ServletContextAttributeListener || listener instanceof ServletRequestListener || listener instanceof ServletRequestAttributeListener || listener instanceof HttpSessionListener || 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); } catch (ClassNotFoundException 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; } // -------------------------------------------------------- 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,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
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.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; 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.FilterConfig; 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.ServletRequest; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.ServletSecurityElement; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.http.HttpSessionAttributeListener; 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.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; /** * Associated host name. */ private String hostName; /** * 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 web.xml file. */ private String applicationListeners[] = new String[0]; private final Object applicationListenersLock = new Object(); /** * The set of instantiated application event listener objects</code>. */ private Object applicationEventListenersObjects[] = new Object[0]; /** * The set of instantiated application lifecycle listener objects</code>. */ 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; /** * 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; } public InstanceManager getInstanceManager() { return instanceManager; } 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; } /** * 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(String listener) { synchronized (applicationListenersLock) { String results[] =new String[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 String[] 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].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[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; } /** * 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 String listeners[] = findApplicationListeners(); Object results[] = new Object[listeners.length]; boolean ok = true; for (int i = 0; i < results.length; i++) { if (getLogger().isDebugEnabled()) getLogger().debug(" Configuring event listener class '" + listeners[i] + "'"); try { results[i] = instanceManager.newInstance(listeners[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 HttpSessionAttributeListener)) { eventListeners.add(results[i]); } if ((results[i] instanceof ServletContextListener) || (results[i] instanceof HttpSessionListener)) { lifecycleListeners.add(results[i]); } } //Listeners may have been added by ServletContextInitializers. Put them after the ones we know about. for (Object eventListener: getApplicationEventListeners()) { eventListeners.add(eventListener); } setApplicationEventListeners(eventListeners.toArray()); for (Object lifecycleListener: getApplicationLifecycleListeners()) { lifecycleListeners.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()); 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); 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()); 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) { // TODO: Log error 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 String[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().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); } public String getHostname() { Container parentHost = getParent(); if (parentHost != null) { hostName = parentHost.getName(); } if ((hostName == null) || (hostName.length() < 1)) hostName = "_"; return hostName; } @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 = getName(); if (temp.startsWith("/")) temp = temp.substring(1); temp = temp.replace('/', '_'); temp = temp.replace('\\', '_'); if (temp.length() < 1) temp = "_"; 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; } }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/org/apache/catalina/ha/session/DeltaManager.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.ha.session; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import org.apache.catalina.Cluster; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Host; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Session; import org.apache.catalina.Valve; import org.apache.catalina.core.StandardContext; import org.apache.catalina.ha.CatalinaCluster; import org.apache.catalina.ha.ClusterManager; import org.apache.catalina.ha.ClusterMessage; import org.apache.catalina.ha.tcp.ReplicationValve; import org.apache.catalina.session.ManagerBase; import org.apache.catalina.tribes.Member; import org.apache.catalina.tribes.io.ReplicationStream; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * The DeltaManager manages replicated sessions by only replicating the deltas * in data. For applications written to handle this, the DeltaManager is the * optimal way of replicating data. * * This code is almost identical to StandardManager with a difference in how it * persists sessions and some modifications to it. * * <b>IMPLEMENTATION NOTE </b>: Correct behavior of session storing and * reloading depends upon external calls to the <code>start()</code> and * <code>stop()</code> methods of this class at the correct times. * * @author Filip Hanik * @author Craig R. McClanahan * @author Jean-Francois Arcand * @author Peter Rossbach * @version $Id$ */ public class DeltaManager extends ClusterManagerBase{ // ---------------------------------------------------- Security Classes public static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(DeltaManager.class); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------- Instance Variables /** * The descriptive name of this Manager implementation (for logging). */ protected static final String managerName = "DeltaManager"; protected String name = null; /** * cached replication valve cluster container! */ private volatile ReplicationValve replicationValve = null ; private boolean expireSessionsOnShutdown = false; private boolean notifySessionListenersOnReplication = true; private boolean notifyContainerListenersOnReplication = true; private volatile boolean stateTransfered = false ; private volatile boolean noContextManagerReceived = false ; private int stateTransferTimeout = 60; private boolean sendAllSessions = true; private int sendAllSessionsSize = 1000 ; /** * wait time between send session block (default 2 sec) */ private int sendAllSessionsWaitTime = 2 * 1000 ; private final ArrayList<SessionMessage> receivedMessageQueue = new ArrayList<>(); private boolean receiverQueue = false ; private boolean stateTimestampDrop = true ; private long stateTransferCreateSendTime; // ------------------------------------------------------------------ stats attributes private long sessionReplaceCounter = 0 ; private long counterReceive_EVT_GET_ALL_SESSIONS = 0 ; private long counterReceive_EVT_ALL_SESSION_DATA = 0 ; private long counterReceive_EVT_SESSION_CREATED = 0 ; private long counterReceive_EVT_SESSION_EXPIRED = 0; private long counterReceive_EVT_SESSION_ACCESSED = 0 ; private long counterReceive_EVT_SESSION_DELTA = 0; private int counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE = 0 ; private long counterReceive_EVT_CHANGE_SESSION_ID = 0 ; private long counterReceive_EVT_ALL_SESSION_NOCONTEXTMANAGER = 0 ; private long counterSend_EVT_GET_ALL_SESSIONS = 0 ; private long counterSend_EVT_ALL_SESSION_DATA = 0 ; private long counterSend_EVT_SESSION_CREATED = 0; private long counterSend_EVT_SESSION_DELTA = 0 ; private long counterSend_EVT_SESSION_ACCESSED = 0; private long counterSend_EVT_SESSION_EXPIRED = 0; private int counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE = 0 ; private long counterSend_EVT_CHANGE_SESSION_ID = 0; private int counterNoStateTransfered = 0 ; // ------------------------------------------------------------- Constructor public DeltaManager() { super(); } // ------------------------------------------------------------- Properties @Override public void setName(String name) { this.name = name; } /** * Return the descriptive short name of this Manager implementation. */ @Override public String getName() { return name; } /** * @return Returns the counterSend_EVT_GET_ALL_SESSIONS. */ public long getCounterSend_EVT_GET_ALL_SESSIONS() { return counterSend_EVT_GET_ALL_SESSIONS; } /** * @return Returns the counterSend_EVT_SESSION_ACCESSED. */ public long getCounterSend_EVT_SESSION_ACCESSED() { return counterSend_EVT_SESSION_ACCESSED; } /** * @return Returns the counterSend_EVT_SESSION_CREATED. */ public long getCounterSend_EVT_SESSION_CREATED() { return counterSend_EVT_SESSION_CREATED; } /** * @return Returns the counterSend_EVT_SESSION_DELTA. */ public long getCounterSend_EVT_SESSION_DELTA() { return counterSend_EVT_SESSION_DELTA; } /** * @return Returns the counterSend_EVT_SESSION_EXPIRED. */ public long getCounterSend_EVT_SESSION_EXPIRED() { return counterSend_EVT_SESSION_EXPIRED; } /** * @return Returns the counterSend_EVT_ALL_SESSION_DATA. */ public long getCounterSend_EVT_ALL_SESSION_DATA() { return counterSend_EVT_ALL_SESSION_DATA; } /** * @return Returns the counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE. */ public int getCounterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE() { return counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE; } /** * @return Returns the counterSend_EVT_CHANGE_SESSION_ID. */ public long getCounterSend_EVT_CHANGE_SESSION_ID() { return counterSend_EVT_CHANGE_SESSION_ID; } /** * @return Returns the counterReceive_EVT_ALL_SESSION_DATA. */ public long getCounterReceive_EVT_ALL_SESSION_DATA() { return counterReceive_EVT_ALL_SESSION_DATA; } /** * @return Returns the counterReceive_EVT_GET_ALL_SESSIONS. */ public long getCounterReceive_EVT_GET_ALL_SESSIONS() { return counterReceive_EVT_GET_ALL_SESSIONS; } /** * @return Returns the counterReceive_EVT_SESSION_ACCESSED. */ public long getCounterReceive_EVT_SESSION_ACCESSED() { return counterReceive_EVT_SESSION_ACCESSED; } /** * @return Returns the counterReceive_EVT_SESSION_CREATED. */ public long getCounterReceive_EVT_SESSION_CREATED() { return counterReceive_EVT_SESSION_CREATED; } /** * @return Returns the counterReceive_EVT_SESSION_DELTA. */ public long getCounterReceive_EVT_SESSION_DELTA() { return counterReceive_EVT_SESSION_DELTA; } /** * @return Returns the counterReceive_EVT_SESSION_EXPIRED. */ public long getCounterReceive_EVT_SESSION_EXPIRED() { return counterReceive_EVT_SESSION_EXPIRED; } /** * @return Returns the counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE. */ public int getCounterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE() { return counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE; } /** * @return Returns the counterReceive_EVT_CHANGE_SESSION_ID. */ public long getCounterReceive_EVT_CHANGE_SESSION_ID() { return counterReceive_EVT_CHANGE_SESSION_ID; } /** * @return Returns the counterReceive_EVT_ALL_SESSION_NOCONTEXTMANAGER. */ public long getCounterReceive_EVT_ALL_SESSION_NOCONTEXTMANAGER() { return counterReceive_EVT_ALL_SESSION_NOCONTEXTMANAGER; } /** * @return Returns the processingTime. */ @Override public long getProcessingTime() { return processingTime; } /** * @return Returns the sessionReplaceCounter. */ public long getSessionReplaceCounter() { return sessionReplaceCounter; } /** * @return Returns the counterNoStateTransfered. */ public int getCounterNoStateTransfered() { return counterNoStateTransfered; } public int getReceivedQueueSize() { return receivedMessageQueue.size() ; } /** * @return Returns the stateTransferTimeout. */ public int getStateTransferTimeout() { return stateTransferTimeout; } /** * @param timeoutAllSession The timeout */ public void setStateTransferTimeout(int timeoutAllSession) { this.stateTransferTimeout = timeoutAllSession; } /** * is session state transfered complete? * */ public boolean getStateTransfered() { return stateTransfered; } /** * set that state ist complete transfered * @param stateTransfered */ public void setStateTransfered(boolean stateTransfered) { this.stateTransfered = stateTransfered; } public boolean isNoContextManagerReceived() { return noContextManagerReceived; } public void setNoContextManagerReceived(boolean noContextManagerReceived) { this.noContextManagerReceived = noContextManagerReceived; } /** * @return Returns the sendAllSessionsWaitTime in msec */ public int getSendAllSessionsWaitTime() { return sendAllSessionsWaitTime; } /** * @param sendAllSessionsWaitTime The sendAllSessionsWaitTime to set at msec. */ public void setSendAllSessionsWaitTime(int sendAllSessionsWaitTime) { this.sendAllSessionsWaitTime = sendAllSessionsWaitTime; } /** * @return Returns the stateTimestampDrop. */ public boolean isStateTimestampDrop() { return stateTimestampDrop; } /** * @param isTimestampDrop The new flag value */ public void setStateTimestampDrop(boolean isTimestampDrop) { this.stateTimestampDrop = isTimestampDrop; } /** * * @return Returns the sendAllSessions. */ public boolean isSendAllSessions() { return sendAllSessions; } /** * @param sendAllSessions The sendAllSessions to set. */ public void setSendAllSessions(boolean sendAllSessions) { this.sendAllSessions = sendAllSessions; } /** * @return Returns the sendAllSessionsSize. */ public int getSendAllSessionsSize() { return sendAllSessionsSize; } /** * @param sendAllSessionsSize The sendAllSessionsSize to set. */ public void setSendAllSessionsSize(int sendAllSessionsSize) { this.sendAllSessionsSize = sendAllSessionsSize; } /** * @return Returns the notifySessionListenersOnReplication. */ public boolean isNotifySessionListenersOnReplication() { return notifySessionListenersOnReplication; } /** * @param notifyListenersCreateSessionOnReplication The notifySessionListenersOnReplication to set. */ public void setNotifySessionListenersOnReplication(boolean notifyListenersCreateSessionOnReplication) { this.notifySessionListenersOnReplication = notifyListenersCreateSessionOnReplication; } public boolean isExpireSessionsOnShutdown() { return expireSessionsOnShutdown; } public void setExpireSessionsOnShutdown(boolean expireSessionsOnShutdown) { this.expireSessionsOnShutdown = expireSessionsOnShutdown; } public boolean isNotifyContainerListenersOnReplication() { return notifyContainerListenersOnReplication; } public void setNotifyContainerListenersOnReplication( boolean notifyContainerListenersOnReplication) { this.notifyContainerListenersOnReplication = notifyContainerListenersOnReplication; } // --------------------------------------------------------- Public Methods /** * Construct and return a new session object, based on the default settings * specified by this Manager's properties. The session id will be assigned * by this method, and available via the getId() method of the returned * session. If a new session cannot be created for any reason, return * <code>null</code>. * * @exception IllegalStateException * if a new session cannot be instantiated for any reason * * Construct and return a new session object, based on the default settings * specified by this Manager's properties. The session id will be assigned * by this method, and available via the getId() method of the returned * session. If a new session cannot be created for any reason, return * <code>null</code>. * * @exception IllegalStateException * if a new session cannot be instantiated for any reason */ @Override public Session createSession(String sessionId) { return createSession(sessionId, true); } /** * create new session with check maxActiveSessions and send session creation * to other cluster nodes. * * @param distribute * @return The session */ public Session createSession(String sessionId, boolean distribute) { DeltaSession session = (DeltaSession) super.createSession(sessionId) ; if (distribute) { sendCreateSession(session.getId(), session); } if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createSession.newSession", session.getId(), Integer.valueOf(sessions.size()))); return (session); } /** * Send create session evt to all backup node * @param sessionId * @param session */ protected void sendCreateSession(String sessionId, DeltaSession session) { if(cluster.getMembers().length > 0 ) { SessionMessage msg = new SessionMessageImpl(getName(), SessionMessage.EVT_SESSION_CREATED, null, sessionId, sessionId + "-" + System.currentTimeMillis()); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.sendMessage.newSession",name, sessionId)); msg.setTimestamp(session.getCreationTime()); counterSend_EVT_SESSION_CREATED++; send(msg); } } /** * Send messages to other backup member (domain or all) * @param msg Session message */ protected void send(SessionMessage msg) { if(cluster != null) { cluster.send(msg); } } /** * Create DeltaSession * @see org.apache.catalina.Manager#createEmptySession() */ @Override public Session createEmptySession() { return getNewDeltaSession() ; } /** * Get new session class to be used in the doLoad() method. */ protected DeltaSession getNewDeltaSession() { return new DeltaSession(this); } /** * Change the session ID of the current session to a new randomly generated * session ID. * * @param session The session to change the session ID for */ @Override public void changeSessionId(Session session) { changeSessionId(session, true); } public void changeSessionId(Session session, boolean notify) { // original sessionID String orgSessionID = session.getId(); super.changeSessionId(session); if (notify && cluster.getMembers().length > 0) { // changed sessionID String newSessionID = session.getId(); try { // serialize sessionID byte[] data = serializeSessionId(newSessionID); // notify change sessionID SessionMessage msg = new SessionMessageImpl(getName(), SessionMessage.EVT_CHANGE_SESSION_ID, data, orgSessionID, orgSessionID + "-" + System.currentTimeMillis()); msg.setTimestamp(System.currentTimeMillis()); counterSend_EVT_CHANGE_SESSION_ID++; send(msg); } catch (IOException e) { log.error(sm.getString("deltaManager.unableSerializeSessionID", newSessionID), e); } } } /** * serialize sessionID * @throws IOException if an input/output error occurs */ protected byte[] serializeSessionId(String sessionId) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeUTF(sessionId); oos.flush(); oos.close(); return bos.toByteArray(); } /** * Load sessionID * @throws IOException if an input/output error occurs */ protected String deserializeSessionId(byte[] data) throws IOException { ReplicationStream ois = getReplicationStream(data); String sessionId = ois.readUTF(); ois.close(); return sessionId; } /** * Load Deltarequest from external node * Load the Class at container classloader * @see DeltaRequest#readExternal(java.io.ObjectInput) * @param session * @param data message data * @return The request * @throws ClassNotFoundException * @throws IOException */ protected DeltaRequest deserializeDeltaRequest(DeltaSession session, byte[] data) throws ClassNotFoundException, IOException { try { session.lock(); ReplicationStream ois = getReplicationStream(data); session.getDeltaRequest().readExternal(ois); ois.close(); return session.getDeltaRequest(); }finally { session.unlock(); } } /** * serialize DeltaRequest * @see DeltaRequest#writeExternal(java.io.ObjectOutput) * * @param deltaRequest * @return serialized delta request * @throws IOException */ protected byte[] serializeDeltaRequest(DeltaSession session, DeltaRequest deltaRequest) throws IOException { try { session.lock(); return deltaRequest.serialize(); }finally { session.unlock(); } } /** * Load sessions from other cluster node. * FIXME replace currently sessions with same id without notification. * FIXME SSO handling is not really correct with the session replacement! * @exception ClassNotFoundException * if a serialized class cannot be found during the reload * @exception IOException * if an input/output error occurs */ protected void deserializeSessions(byte[] data) throws ClassNotFoundException,IOException { // Initialize our internal data structures //sessions.clear(); //should not do this // Open an input stream to the specified pathname, if any ClassLoader originalLoader = Thread.currentThread().getContextClassLoader(); ObjectInputStream ois = null; // Load the previously unloaded active sessions try { ois = getReplicationStream(data); Integer count = (Integer) ois.readObject(); int n = count.intValue(); for (int i = 0; i < n; i++) { DeltaSession session = (DeltaSession) createEmptySession(); session.readObjectData(ois); session.setManager(this); session.setValid(true); session.setPrimarySession(false); //in case the nodes in the cluster are out of //time synch, this will make sure that we have the //correct timestamp, isValid returns true, cause // accessCount=1 session.access(); //make sure that the session gets ready to expire if // needed session.setAccessCount(0); session.resetDeltaRequest(); // FIXME How inform other session id cache like SingleSignOn // increment sessionCounter to correct stats report if (findSession(session.getIdInternal()) == null ) { sessionCounter++; } else { sessionReplaceCounter++; // FIXME better is to grap this sessions again ! if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.loading.existing.session",session.getIdInternal())); } add(session); if (notifySessionListenersOnReplication) { session.tellNew(); } } } catch (ClassNotFoundException e) { log.error(sm.getString("deltaManager.loading.cnfe", e), e); throw e; } catch (IOException e) { log.error(sm.getString("deltaManager.loading.ioe", e), e); throw e; } finally { // Close the input stream try { if (ois != null) ois.close(); } catch (IOException f) { // ignored } ois = null; if (originalLoader != null) Thread.currentThread().setContextClassLoader(originalLoader); } } /** * Save any currently active sessions in the appropriate persistence * mechanism, if any. If persistence is not supported, this method returns * without doing anything. * * @exception IOException * if an input/output error occurs */ protected byte[] serializeSessions(Session[] currentSessions) throws IOException { // Open an output stream to the specified pathname, if any ByteArrayOutputStream fos = null; ObjectOutputStream oos = null; try { fos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(new BufferedOutputStream(fos)); oos.writeObject(Integer.valueOf(currentSessions.length)); for(int i=0 ; i < currentSessions.length;i++) { ((DeltaSession)currentSessions[i]).writeObjectData(oos); } // Flush and close the output stream oos.flush(); } catch (IOException e) { log.error(sm.getString("deltaManager.unloading.ioe", e), e); throw e; } finally { if (oos != null) { try { oos.close(); } catch (IOException f) { // Ignore } oos = null; } } // send object data as byte[] return fos.toByteArray(); } /** * 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 { super.startInternal(); // Load unloaded sessions, if any try { //the channel is already running Cluster cluster = getCluster() ; // stop remove cluster binding //wow, how many nested levels of if statements can we have ;) if(cluster == null) { Context context = getContext() ; if (context != null) { Container host = context.getParent() ; if(host != null && host instanceof Host) { cluster = host.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster) ; } else { Container engine = host.getParent() ; if(engine != null && engine instanceof Engine) { cluster = engine.getCluster(); if(cluster != null && cluster instanceof CatalinaCluster) { setCluster((CatalinaCluster) cluster) ; } } else { cluster = null ; } } } } } if (cluster == null) { log.error(sm.getString("deltaManager.noCluster", getName())); return; } else { if (log.isInfoEnabled()) { String type = "unknown" ; if( cluster.getContainer() instanceof Host){ type = "Host" ; } else if( cluster.getContainer() instanceof Engine){ type = "Engine" ; } log.info(sm.getString("deltaManager.registerCluster", getName(), type, cluster.getClusterName())); } } if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.startClustering", getName())); //to survice context reloads, as only a stop/start is called, not // createManager cluster.registerManager(this); getAllClusterSessions(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("deltaManager.managerLoad"), t); } setState(LifecycleState.STARTING); } /** * get from first session master the backup from all clustered sessions * @see #findSessionMasterMember() */ public synchronized void getAllClusterSessions() { if (cluster != null && cluster.getMembers().length > 0) { long beforeSendTime = System.currentTimeMillis(); Member mbr = findSessionMasterMember(); if(mbr == null) { // No domain member found return; } SessionMessage msg = new SessionMessageImpl(this.getName(),SessionMessage.EVT_GET_ALL_SESSIONS, null, "GET-ALL","GET-ALL-" + getName()); // set reference time stateTransferCreateSendTime = beforeSendTime ; // request session state counterSend_EVT_GET_ALL_SESSIONS++; stateTransfered = false ; // FIXME This send call block the deploy thread, when sender waitForAck is enabled try { synchronized(receivedMessageQueue) { receiverQueue = true ; } cluster.send(msg, mbr); if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.waitForSessionState",getName(), mbr, Integer.valueOf(getStateTransferTimeout()))); // FIXME At sender ack mode this method check only the state transfer and resend is a problem! waitForSendAllSessions(beforeSendTime); } finally { synchronized(receivedMessageQueue) { for (Iterator<SessionMessage> iter = receivedMessageQueue.iterator(); iter.hasNext();) { SessionMessage smsg = iter.next(); if (!stateTimestampDrop) { messageReceived(smsg, smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (smsg.getEventType() != SessionMessage.EVT_GET_ALL_SESSIONS && smsg.getTimestamp() >= stateTransferCreateSendTime) { // FIXME handle EVT_GET_ALL_SESSIONS later messageReceived(smsg,smsg.getAddress() != null ? (Member) smsg.getAddress() : null); } else { if (log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.dropMessage",getName(), smsg.getEventTypeString(),new Date(stateTransferCreateSendTime), new Date(smsg.getTimestamp()))); } } } } receivedMessageQueue.clear(); receiverQueue = false ; } } } else { if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.noMembers", getName())); } } /** * Register cross context session at replication valve thread local * @param session cross context session */ protected void registerSessionAtReplicationValve(DeltaSession session) { if(replicationValve == null) { Context context = getContext(); if(context instanceof StandardContext && ((StandardContext)context).getCrossContext()) { CatalinaCluster cluster = getCluster() ; if(cluster != null) { Valve[] valves = cluster.getValves(); if(valves != null && valves.length > 0) { for(int i=0; replicationValve == null && i < valves.length ; i++ ){ if(valves[i] instanceof ReplicationValve) replicationValve = (ReplicationValve)valves[i] ; }//for if(replicationValve == null && log.isDebugEnabled()) { log.debug("no ReplicationValve found for CrossContext Support"); }//endif }//end if }//endif }//end if }//end if if(replicationValve != null) { replicationValve.registerReplicationSession(session); } } /** * Find the master of the session state * @return master member of sessions */ protected Member findSessionMasterMember() { Member mbr = null; Member mbrs[] = cluster.getMembers(); if(mbrs.length != 0 ) mbr = mbrs[0]; if(mbr == null && log.isWarnEnabled()) log.warn(sm.getString("deltaManager.noMasterMember",getName(), "")); if(mbr != null && log.isDebugEnabled()) log.warn(sm.getString("deltaManager.foundMasterMember",getName(), mbr)); return mbr; } /** * Wait that cluster session state is transfer or timeout after 60 Sec * With stateTransferTimeout == -1 wait that backup is transfered (forever mode) */ protected void waitForSendAllSessions(long beforeSendTime) { long reqStart = System.currentTimeMillis(); long reqNow = reqStart ; boolean isTimeout = false; if(getStateTransferTimeout() > 0) { // wait that state is transfered with timeout check do { try { Thread.sleep(100); } catch (Exception sleep) { // } reqNow = System.currentTimeMillis(); isTimeout = ((reqNow - reqStart) > (1000 * getStateTransferTimeout())); } while ((!getStateTransfered()) && (!isTimeout) && (!isNoContextManagerReceived())); } else { if(getStateTransferTimeout() == -1) { // wait that state is transfered do { try { Thread.sleep(100); } catch (Exception sleep) { } } while ((!getStateTransfered())&& (!isNoContextManagerReceived())); reqNow = System.currentTimeMillis(); } } if (isTimeout) { counterNoStateTransfered++ ; log.error(sm.getString("deltaManager.noSessionState",getName(),new Date(beforeSendTime),Long.valueOf(reqNow - beforeSendTime))); }else if (isNoContextManagerReceived()) { if (log.isWarnEnabled()) log.warn(sm.getString("deltaManager.noContextManager",getName(),new Date(beforeSendTime),Long.valueOf(reqNow - beforeSendTime))); } else { if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.sessionReceived",getName(), new Date(beforeSendTime), Long.valueOf(reqNow - beforeSendTime))); } } /** * 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 { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.stopped", getName())); setState(LifecycleState.STOPPING); // Expire all active sessions if (log.isInfoEnabled()) log.info(sm.getString("deltaManager.expireSessions", getName())); Session sessions[] = findSessions(); for (int i = 0; i < sessions.length; i++) { DeltaSession session = (DeltaSession) sessions[i]; if (!session.isValid()) continue; try { session.expire(true, isExpireSessionsOnShutdown()); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } // Require a new random number generator if we are restarted getCluster().removeManager(this); super.stopInternal(); replicationValve = null; } // -------------------------------------------------------- Replication // Methods /** * A message was received from another node, this is the callback method to * implement if you are interested in receiving replication messages. * * @param cmsg - * the message received. */ @Override public void messageDataReceived(ClusterMessage cmsg) { if (cmsg != null && cmsg instanceof SessionMessage) { SessionMessage msg = (SessionMessage) cmsg; switch (msg.getEventType()) { case SessionMessage.EVT_GET_ALL_SESSIONS: case SessionMessage.EVT_SESSION_CREATED: case SessionMessage.EVT_SESSION_EXPIRED: case SessionMessage.EVT_SESSION_ACCESSED: case SessionMessage.EVT_SESSION_DELTA: case SessionMessage.EVT_CHANGE_SESSION_ID: { synchronized(receivedMessageQueue) { if(receiverQueue) { receivedMessageQueue.add(msg); return ; } } break; } default: { //we didn't queue, do nothing break; } } //switch messageReceived(msg, msg.getAddress() != null ? (Member) msg.getAddress() : null); } } /** * When the request has been completed, the replication valve will notify * the manager, and the manager will decide whether any replication is * needed or not. If there is a need for replication, the manager will * create a session message and that will be replicated. The cluster * determines where it gets sent. * * @param sessionId - * the sessionId that just completed. * @return a SessionMessage to be sent, */ @Override public ClusterMessage requestCompleted(String sessionId) { return requestCompleted(sessionId, false); } /** * When the request has been completed, the replication valve will notify * the manager, and the manager will decide whether any replication is * needed or not. If there is a need for replication, the manager will * create a session message and that will be replicated. The cluster * determines where it gets sent. * * Session expiration also calls this method, but with expires == true. * * @param sessionId - * the sessionId that just completed. * @param expires - * whether this method has been called during session expiration * @return a SessionMessage to be sent, */ public ClusterMessage requestCompleted(String sessionId, boolean expires) { DeltaSession session = null; try { session = (DeltaSession) findSession(sessionId); if (session == null) { // A parallel request has called session.invalidate() which has // removed the session from the Manager. return null; } DeltaRequest deltaRequest = session.getDeltaRequest(); session.lock(); SessionMessage msg = null; boolean isDeltaRequest = false ; synchronized(deltaRequest) { isDeltaRequest = deltaRequest.getSize() > 0 ; if (isDeltaRequest) { counterSend_EVT_SESSION_DELTA++; byte[] data = serializeDeltaRequest(session,deltaRequest); msg = new SessionMessageImpl(getName(), SessionMessage.EVT_SESSION_DELTA, data, sessionId, sessionId + "-" + System.currentTimeMillis()); session.resetDeltaRequest(); } } if(!isDeltaRequest) { if(!expires && !session.isPrimarySession()) { counterSend_EVT_SESSION_ACCESSED++; msg = new SessionMessageImpl(getName(), SessionMessage.EVT_SESSION_ACCESSED, null, sessionId, sessionId + "-" + System.currentTimeMillis()); if (log.isDebugEnabled()) { log.debug(sm.getString("deltaManager.createMessage.accessChangePrimary",getName(), sessionId)); } } } else { // log only outside synch block! if (log.isDebugEnabled()) { log.debug(sm.getString("deltaManager.createMessage.delta",getName(), sessionId)); } } if (!expires) session.setPrimarySession(true); //check to see if we need to send out an access message if (!expires && (msg == null)) { long replDelta = System.currentTimeMillis() - session.getLastTimeReplicated(); if (session.getMaxInactiveInterval() >=0 && replDelta > (session.getMaxInactiveInterval() * 1000)) { counterSend_EVT_SESSION_ACCESSED++; msg = new SessionMessageImpl(getName(), SessionMessage.EVT_SESSION_ACCESSED, null, sessionId, sessionId + "-" + System.currentTimeMillis()); if (log.isDebugEnabled()) { log.debug(sm.getString("deltaManager.createMessage.access", getName(),sessionId)); } } } //update last replicated time if (msg != null){ session.setLastTimeReplicated(System.currentTimeMillis()); msg.setTimestamp(session.getLastTimeReplicated()); } return msg; } catch (IOException x) { log.error(sm.getString("deltaManager.createMessage.unableCreateDeltaRequest",sessionId), x); return null; }finally { if (session!=null) session.unlock(); } } /** * Reset manager statistics */ public synchronized void resetStatistics() { processingTime = 0 ; expiredSessions.set(0); synchronized (sessionCreationTiming) { sessionCreationTiming.clear(); while (sessionCreationTiming.size() < ManagerBase.TIMING_STATS_CACHE_SIZE) { sessionCreationTiming.add(null); } } synchronized (sessionExpirationTiming) { sessionExpirationTiming.clear(); while (sessionExpirationTiming.size() < ManagerBase.TIMING_STATS_CACHE_SIZE) { sessionExpirationTiming.add(null); } } rejectedSessions = 0 ; sessionReplaceCounter = 0 ; counterNoStateTransfered = 0 ; setMaxActive(getActiveSessions()); sessionCounter = getActiveSessions() ; counterReceive_EVT_ALL_SESSION_DATA = 0; counterReceive_EVT_GET_ALL_SESSIONS = 0; counterReceive_EVT_SESSION_ACCESSED = 0 ; counterReceive_EVT_SESSION_CREATED = 0 ; counterReceive_EVT_SESSION_DELTA = 0 ; counterReceive_EVT_SESSION_EXPIRED = 0 ; counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE = 0; counterReceive_EVT_CHANGE_SESSION_ID = 0; counterSend_EVT_ALL_SESSION_DATA = 0; counterSend_EVT_GET_ALL_SESSIONS = 0; counterSend_EVT_SESSION_ACCESSED = 0 ; counterSend_EVT_SESSION_CREATED = 0 ; counterSend_EVT_SESSION_DELTA = 0 ; counterSend_EVT_SESSION_EXPIRED = 0 ; counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE = 0; counterSend_EVT_CHANGE_SESSION_ID = 0; } // -------------------------------------------------------- expire /** * send session expired to other cluster nodes * * @param id * session id */ protected void sessionExpired(String id) { if(cluster.getMembers().length > 0 ) { counterSend_EVT_SESSION_EXPIRED++ ; SessionMessage msg = new SessionMessageImpl(getName(), SessionMessage.EVT_SESSION_EXPIRED, null, id, id+ "-EXPIRED-MSG"); msg.setTimestamp(System.currentTimeMillis()); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.expire",getName(), id)); send(msg); } } /** * Expire all find sessions. */ public void expireAllLocalSessions() { long timeNow = System.currentTimeMillis(); Session sessions[] = findSessions(); int expireDirect = 0 ; int expireIndirect = 0 ; if(log.isDebugEnabled()) log.debug("Start expire all sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length); for (int i = 0; i < sessions.length; i++) { if (sessions[i] instanceof DeltaSession) { DeltaSession session = (DeltaSession) sessions[i]; if (session.isPrimarySession()) { if (session.isValid()) { session.expire(); expireDirect++; } else { expireIndirect++; }//end if }//end if }//end if }//for long timeEnd = System.currentTimeMillis(); if(log.isDebugEnabled()) log.debug("End expire sessions " + getName() + " expire processingTime " + (timeEnd - timeNow) + " expired direct sessions: " + expireDirect + " expired direct sessions: " + expireIndirect); } /** * When the manager expires session not tied to a request. The cluster will * periodically ask for a list of sessions that should expire and that * should be sent across the wire. * * @return The invalidated sessions array */ @Override public String[] getInvalidatedSessions() { return new String[0]; } // -------------------------------------------------------- message receive /** * Test that sender and local domain is the same */ protected boolean checkSenderDomain(SessionMessage msg,Member sender) { boolean sameDomain= true; if (!sameDomain && log.isWarnEnabled()) { log.warn(sm.getString("deltaManager.receiveMessage.fromWrongDomain", new Object[] {getName(), msg.getEventTypeString(), sender, "", "" })); } return sameDomain ; } /** * This method is called by the received thread when a SessionMessage has * been received from one of the other nodes in the cluster. * * @param msg - * the message received * @param sender - * the sender of the message, this is used if we receive a * EVT_GET_ALL_SESSION message, so that we only reply to the * requesting node */ protected void messageReceived(SessionMessage msg, Member sender) { if(!checkSenderDomain(msg,sender)) { return; } ClassLoader contextLoader = Thread.currentThread().getContextClassLoader(); try { ClassLoader[] loaders = getClassLoaders(); if ( loaders != null && loaders.length > 0) Thread.currentThread().setContextClassLoader(loaders[0]); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.eventType",getName(), msg.getEventTypeString(), sender)); switch (msg.getEventType()) { case SessionMessage.EVT_GET_ALL_SESSIONS: { handleGET_ALL_SESSIONS(msg,sender); break; } case SessionMessage.EVT_ALL_SESSION_DATA: { handleALL_SESSION_DATA(msg,sender); break; } case SessionMessage.EVT_ALL_SESSION_TRANSFERCOMPLETE: { handleALL_SESSION_TRANSFERCOMPLETE(msg,sender); break; } case SessionMessage.EVT_SESSION_CREATED: { handleSESSION_CREATED(msg,sender); break; } case SessionMessage.EVT_SESSION_EXPIRED: { handleSESSION_EXPIRED(msg,sender); break; } case SessionMessage.EVT_SESSION_ACCESSED: { handleSESSION_ACCESSED(msg,sender); break; } case SessionMessage.EVT_SESSION_DELTA: { handleSESSION_DELTA(msg,sender); break; } case SessionMessage.EVT_CHANGE_SESSION_ID: { handleCHANGE_SESSION_ID(msg,sender); break; } case SessionMessage.EVT_ALL_SESSION_NOCONTEXTMANAGER: { handleALL_SESSION_NOCONTEXTMANAGER(msg,sender); break; } default: { //we didn't recognize the message type, do nothing break; } } //switch } catch (Exception x) { log.error(sm.getString("deltaManager.receiveMessage.error",getName()), x); } finally { Thread.currentThread().setContextClassLoader(contextLoader); } } // -------------------------------------------------------- message receiver handler /** * handle receive session state is complete transfered * @param msg * @param sender */ protected void handleALL_SESSION_TRANSFERCOMPLETE(SessionMessage msg, Member sender) { counterReceive_EVT_ALL_SESSION_TRANSFERCOMPLETE++ ; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.transfercomplete",getName(), sender.getHost(), Integer.valueOf(sender.getPort()))); stateTransferCreateSendTime = msg.getTimestamp() ; stateTransfered = true ; } /** * handle receive session delta * @param msg * @param sender * @throws IOException * @throws ClassNotFoundException */ protected void handleSESSION_DELTA(SessionMessage msg, Member sender) throws IOException, ClassNotFoundException { counterReceive_EVT_SESSION_DELTA++; byte[] delta = msg.getSession(); DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.delta",getName(), msg.getSessionID())); try { session.lock(); DeltaRequest dreq = deserializeDeltaRequest(session, delta); dreq.execute(session, isNotifyListenersOnReplication()); session.setPrimarySession(false); }finally { session.unlock(); } } } /** * handle receive session is access at other node ( primary session is now false) * @param msg * @param sender * @throws IOException */ protected void handleSESSION_ACCESSED(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_SESSION_ACCESSED++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.accessed",getName(), msg.getSessionID())); session.access(); session.setPrimarySession(false); session.endAccess(); } } /** * handle receive session is expire at other node ( expire session also here) * @param msg * @param sender * @throws IOException */ protected void handleSESSION_EXPIRED(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_SESSION_EXPIRED++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.expired",getName(), msg.getSessionID())); session.expire(notifySessionListenersOnReplication, false); } } /** * handle receive new session is created at other node (create backup - primary false) * @param msg * @param sender */ protected void handleSESSION_CREATED(SessionMessage msg,Member sender) { counterReceive_EVT_SESSION_CREATED++; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.createNewSession",getName(), msg.getSessionID())); DeltaSession session = (DeltaSession) createEmptySession(); session.setManager(this); session.setValid(true); session.setPrimarySession(false); session.setCreationTime(msg.getTimestamp()); // use container maxInactiveInterval so that session will expire correctly in case of primary transfer session.setMaxInactiveInterval(getMaxInactiveInterval(), false); session.access(); session.setId(msg.getSessionID(), notifySessionListenersOnReplication); session.resetDeltaRequest(); session.endAccess(); } /** * handle receive sessions from other not ( restart ) * @param msg * @param sender * @throws ClassNotFoundException * @throws IOException */ protected void handleALL_SESSION_DATA(SessionMessage msg,Member sender) throws ClassNotFoundException, IOException { counterReceive_EVT_ALL_SESSION_DATA++; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataBegin",getName())); byte[] data = msg.getSession(); deserializeSessions(data); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.allSessionDataAfter",getName())); //stateTransferred = true; } /** * handle receive that other node want all sessions ( restart ) * a) send all sessions with one message * b) send session at blocks * After sending send state is complete transfered * @param msg * @param sender * @throws IOException */ protected void handleGET_ALL_SESSIONS(SessionMessage msg, Member sender) throws IOException { counterReceive_EVT_GET_ALL_SESSIONS++; //get a list of all the session from this manager if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingBegin", getName())); // Write the number of active sessions, followed by the details // get all sessions and serialize without sync Session[] currentSessions = findSessions(); long findSessionTimestamp = System.currentTimeMillis() ; if (isSendAllSessions()) { sendSessions(sender, currentSessions, findSessionTimestamp); } else { // send session at blocks for (int i = 0; i < currentSessions.length; i += getSendAllSessionsSize()) { int len = i + getSendAllSessionsSize() > currentSessions.length ? currentSessions.length - i : getSendAllSessionsSize(); Session[] sendSessions = new Session[len]; System.arraycopy(currentSessions, i, sendSessions, 0, len); sendSessions(sender, sendSessions,findSessionTimestamp); if (getSendAllSessionsWaitTime() > 0) { try { Thread.sleep(getSendAllSessionsWaitTime()); } catch (Exception sleep) { } }//end if }//for }//end if SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_TRANSFERCOMPLETE, null,"SESSION-STATE-TRANSFERED", "SESSION-STATE-TRANSFERED"+ getName()); newmsg.setTimestamp(findSessionTimestamp); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionTransfered",getName())); counterSend_EVT_ALL_SESSION_TRANSFERCOMPLETE++; cluster.send(newmsg, sender); } /** * handle receive change sessionID at other node * @param msg * @param sender * @throws IOException */ protected void handleCHANGE_SESSION_ID(SessionMessage msg,Member sender) throws IOException { counterReceive_EVT_CHANGE_SESSION_ID++; DeltaSession session = (DeltaSession) findSession(msg.getSessionID()); if (session != null) { String newSessionID = deserializeSessionId(msg.getSession()); session.setPrimarySession(false); session.setId(newSessionID, false); if (notifyContainerListenersOnReplication) { getContext().fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT, new String[] {msg.getSessionID(), newSessionID}); } } } /** * handle receive no context manager. * @param msg * @param sender */ protected void handleALL_SESSION_NOCONTEXTMANAGER(SessionMessage msg, Member sender) { counterReceive_EVT_ALL_SESSION_NOCONTEXTMANAGER++ ; if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.noContextManager",getName(), sender.getHost(), Integer.valueOf(sender.getPort()))); noContextManagerReceived = true ; } /** * send a block of session to sender * @param sender * @param currentSessions * @param sendTimestamp * @throws IOException */ protected void sendSessions(Member sender, Session[] currentSessions,long sendTimestamp) throws IOException { byte[] data = serializeSessions(currentSessions); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.receiveMessage.unloadingAfter",getName())); SessionMessage newmsg = new SessionMessageImpl(name,SessionMessage.EVT_ALL_SESSION_DATA, data,"SESSION-STATE", "SESSION-STATE-" + getName()); newmsg.setTimestamp(sendTimestamp); if (log.isDebugEnabled()) log.debug(sm.getString("deltaManager.createMessage.allSessionData",getName())); counterSend_EVT_ALL_SESSION_DATA++; cluster.send(newmsg, sender); } @Override public ClusterManager cloneFromTemplate() { DeltaManager result = new DeltaManager(); clone(result); result.replicationValve = replicationValve; result.expireSessionsOnShutdown = expireSessionsOnShutdown; result.notifySessionListenersOnReplication = notifySessionListenersOnReplication; result.notifyContainerListenersOnReplication = notifyContainerListenersOnReplication; result.stateTransferTimeout = stateTransferTimeout; result.sendAllSessions = sendAllSessions; result.sendAllSessionsSize = sendAllSessionsSize; result.sendAllSessionsWaitTime = sendAllSessionsWaitTime ; result.receiverQueue = receiverQueue ; result.stateTimestampDrop = stateTimestampDrop ; result.stateTransferCreateSendTime = stateTransferCreateSendTime; return result; } }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/org/apache/catalina/session/ManagerBase.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.session; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.Deque; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicLong; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.LifecycleException; import org.apache.catalina.Manager; import org.apache.catalina.Session; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.catalina.util.SessionIdGenerator; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * Minimal implementation of the <b>Manager</b> interface that supports * no session persistence or distributable capabilities. This class may * be subclassed to create more sophisticated Manager implementations. * * @author Craig R. McClanahan * @version $Id$ */ public abstract class ManagerBase extends LifecycleMBeanBase implements Manager, PropertyChangeListener { private final Log log = LogFactory.getLog(ManagerBase.class); // must not be static // ----------------------------------------------------- Instance Variables /** * The Context with which this Manager is associated. */ private Context context; /** * The distributable flag for Sessions created by this Manager. If this * flag is set to <code>true</code>, any user attributes added to a * session controlled by this Manager must be Serializable. */ protected boolean distributable; /** * The descriptive name of this Manager implementation (for logging). */ private static final String name = "ManagerBase"; /** * The default maximum inactive interval for Sessions created by * this Manager. */ protected int maxInactiveInterval = 30 * 60; /** * The session id length of Sessions created by this Manager. */ protected int sessionIdLength = 16; /** * The Java class name of the secure random number generator class to be * used when generating 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 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 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 longest time (in seconds) that an expired session had been alive. */ protected volatile int sessionMaxAliveTime; private final Object sessionMaxAliveTimeUpdateLock = new Object(); protected static final int TIMING_STATS_CACHE_SIZE = 100; protected final Deque<SessionTiming> sessionCreationTiming = new LinkedList<>(); protected final Deque<SessionTiming> sessionExpirationTiming = new LinkedList<>(); /** * Number of sessions that have expired. */ protected final AtomicLong expiredSessions = new AtomicLong(0); /** * The set of currently active Sessions for this Manager, keyed by * session identifier. */ protected Map<String, Session> sessions = new ConcurrentHashMap<>(); // Number of sessions created by this manager protected long sessionCounter=0; protected volatile int maxActive=0; private final Object maxActiveUpdateLock = new Object(); /** * The maximum number of active Sessions allowed, or -1 for no limit. */ protected int maxActiveSessions = -1; /** * Number of session creations that failed due to maxActiveSessions. */ protected int rejectedSessions = 0; // number of duplicated session ids - anything >0 means we have problems protected volatile int duplicates=0; /** * Processing time during session expiration. */ protected long processingTime = 0; /** * Iteration count for background processing. */ private int count = 0; /** * Frequency of the session expiration, and related manager operations. * Manager operations will be done once for the specified amount of * backgrondProcess calls (ie, the lower the amount, the most often the * checks will occur). */ protected int processExpiresFrequency = 6; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The property change support for this component. */ protected final PropertyChangeSupport support = new PropertyChangeSupport(this); // ------------------------------------------------------------- Properties @Override @Deprecated public Container getContainer() { return getContext(); } @Override @Deprecated public void setContainer(Container container) { if (container instanceof Context || container == null) { setContext((Context) container); } else { log.warn(sm.getString("managerBase.container.noop")); } } @Override public Context getContext() { return context; } @Override public void setContext(Context context) { // De-register from the old Context (if any) if (this.context != null) { this.context.removePropertyChangeListener(this); } Context oldContext = this.context; this.context = context; support.firePropertyChange("context", oldContext, this.context); // TODO - delete the line below in Tomcat 9 onwards support.firePropertyChange("container", oldContext, this.context); // Register with the new Context (if any) if (this.context != null) { setMaxInactiveInterval(this.context.getSessionTimeout() * 60); this.context.addPropertyChangeListener(this); } } /** Returns the name of the implementation class. */ public String getClassName() { return this.getClass().getName(); } /** * Return the distributable flag for the sessions supported by * this Manager. */ @Override public boolean getDistributable() { return (this.distributable); } /** * Set the distributable flag for the sessions supported by this * Manager. If this flag is set, all user data objects added to * sessions associated with this manager must implement Serializable. * * @param distributable The new distributable flag */ @Override public void setDistributable(boolean distributable) { boolean oldDistributable = this.distributable; this.distributable = distributable; support.firePropertyChange("distributable", Boolean.valueOf(oldDistributable), Boolean.valueOf(this.distributable)); } /** * Return the default maximum inactive interval (in seconds) * for Sessions created by this Manager. */ @Override public int getMaxInactiveInterval() { return (this.maxInactiveInterval); } /** * Set the default maximum inactive interval (in seconds) * for Sessions created by this Manager. * * @param interval The new default value */ @Override public void setMaxInactiveInterval(int interval) { int oldMaxInactiveInterval = this.maxInactiveInterval; this.maxInactiveInterval = interval; support.firePropertyChange("maxInactiveInterval", Integer.valueOf(oldMaxInactiveInterval), Integer.valueOf(this.maxInactiveInterval)); } /** * Gets the session id length (in bytes) of Sessions created by * this Manager. * * @return The session id length */ @Override public int getSessionIdLength() { return (this.sessionIdLength); } /** * Sets the session id length (in bytes) for Sessions created by this * Manager. * * @param idLength The session id length */ @Override public void setSessionIdLength(int idLength) { int oldSessionIdLength = this.sessionIdLength; this.sessionIdLength = idLength; support.firePropertyChange("sessionIdLength", Integer.valueOf(oldSessionIdLength), Integer.valueOf(this.sessionIdLength)); } /** * Return the descriptive short name of this Manager implementation. */ public String getName() { return (name); } /** * 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) { String oldSecureRandomClass = this.secureRandomClass; this.secureRandomClass = secureRandomClass; support.firePropertyChange("secureRandomClass", oldSecureRandomClass, this.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; } /** * Number of session creations that failed due to maxActiveSessions * * @return The count */ @Override public int getRejectedSessions() { return rejectedSessions; } /** * Gets the number of sessions that have expired. * * @return Number of sessions that have expired */ @Override public long getExpiredSessions() { return expiredSessions.get(); } /** * Sets the number of sessions that have expired. * * @param expiredSessions Number of sessions that have expired */ @Override public void setExpiredSessions(long expiredSessions) { this.expiredSessions.set(expiredSessions); } public long getProcessingTime() { return processingTime; } public void setProcessingTime(long processingTime) { this.processingTime = processingTime; } /** * Return the frequency of manager checks. */ public int getProcessExpiresFrequency() { return (this.processExpiresFrequency); } /** * Set the manager checks frequency. * * @param processExpiresFrequency the new manager checks frequency */ public void setProcessExpiresFrequency(int processExpiresFrequency) { if (processExpiresFrequency <= 0) { return; } int oldProcessExpiresFrequency = this.processExpiresFrequency; this.processExpiresFrequency = processExpiresFrequency; support.firePropertyChange("processExpiresFrequency", Integer.valueOf(oldProcessExpiresFrequency), Integer.valueOf(this.processExpiresFrequency)); } // --------------------------------------------------------- Public Methods /** * Implements the Manager interface, direct call to processExpires */ @Override public void backgroundProcess() { count = (count + 1) % processExpiresFrequency; if (count == 0) processExpires(); } /** * Invalidate all sessions that have expired. */ public void processExpires() { long timeNow = System.currentTimeMillis(); Session sessions[] = findSessions(); int expireHere = 0 ; if(log.isDebugEnabled()) log.debug("Start expire sessions " + getName() + " at " + timeNow + " sessioncount " + sessions.length); for (int i = 0; i < sessions.length; i++) { if (sessions[i]!=null && !sessions[i].isValid()) { expireHere++; } } long timeEnd = System.currentTimeMillis(); if(log.isDebugEnabled()) log.debug("End expire sessions " + getName() + " processingTime " + (timeEnd - timeNow) + " expired sessions: " + expireHere); processingTime += ( timeEnd - timeNow ); } @Override protected void initInternal() throws LifecycleException { super.initInternal(); setDistributable(getContext().getDistributable()); } @Override protected void startInternal() throws LifecycleException { // Ensure caches for timing stats are the right size by filling with // nulls. while (sessionCreationTiming.size() < TIMING_STATS_CACHE_SIZE) { sessionCreationTiming.add(null); } while (sessionExpirationTiming.size() < TIMING_STATS_CACHE_SIZE) { sessionExpirationTiming.add(null); } sessionIdGenerator = new SessionIdGenerator(); sessionIdGenerator.setJvmRoute(getJvmRoute()); sessionIdGenerator.setSecureRandomAlgorithm(getSecureRandomAlgorithm()); sessionIdGenerator.setSecureRandomClass(getSecureRandomClass()); sessionIdGenerator.setSecureRandomProvider(getSecureRandomProvider()); sessionIdGenerator.setSessionIdLength(getSessionIdLength()); // Force initialization of the random number generator if (log.isDebugEnabled()) log.debug("Force random number initialization starting"); sessionIdGenerator.generateSessionId(); if (log.isDebugEnabled()) log.debug("Force random number initialization completed"); } @Override protected void stopInternal() throws LifecycleException { this.sessionIdGenerator = null; } /** * Add this Session to the set of active Sessions for this Manager. * * @param session Session to be added */ @Override public void add(Session session) { sessions.put(session.getIdInternal(), session); int size = getActiveSessions(); if( size > maxActive ) { synchronized(maxActiveUpdateLock) { if( size > maxActive ) { maxActive = size; } } } } /** * Add a property change listener to this component. * * @param listener The listener to add */ @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } /** * Construct and return a new session object, based on the default * settings specified by this Manager's properties. The session * id specified will be used as the session id. * If a new session cannot be created for any reason, return * <code>null</code>. * * @param sessionId The session id which should be used to create the * new session; if <code>null</code>, a new session id will be * generated * @exception IllegalStateException if a new session cannot be * instantiated for any reason */ @Override public Session createSession(String sessionId) { if ((maxActiveSessions >= 0) && (getActiveSessions() >= maxActiveSessions)) { rejectedSessions++; throw new TooManyActiveSessionsException( sm.getString("managerBase.createSession.ise"), maxActiveSessions); } // Recycle or create a Session instance Session session = createEmptySession(); // Initialize the properties of the new session and return it session.setNew(true); session.setValid(true); session.setCreationTime(System.currentTimeMillis()); session.setMaxInactiveInterval(this.maxInactiveInterval); String id = sessionId; if (id == null) { id = generateSessionId(); } session.setId(id); sessionCounter++; SessionTiming timing = new SessionTiming(session.getCreationTime(), 0); synchronized (sessionCreationTiming) { sessionCreationTiming.add(timing); sessionCreationTiming.poll(); } return (session); } /** * Get a session from the recycled ones or create a new empty one. * The PersistentManager manager does not need to create session data * because it reads it from the Store. */ @Override public Session createEmptySession() { return (getNewSession()); } /** * Return the active Session, associated with this Manager, with the * specified session id (if any); otherwise return <code>null</code>. * * @param id The session id for the session to be returned * * @exception IllegalStateException if a new session cannot be * instantiated for any reason * @exception IOException if an input/output error occurs while * processing this request */ @Override public Session findSession(String id) throws IOException { if (id == null) return (null); return sessions.get(id); } /** * Return the set of active Sessions associated with this Manager. * If this Manager has no active Sessions, a zero-length array is returned. */ @Override public Session[] findSessions() { return sessions.values().toArray(new Session[0]); } /** * Remove this Session from the active Sessions for this Manager. * * @param session Session to be removed */ @Override public void remove(Session session) { remove(session, false); } /** * Remove this Session from the active Sessions for this Manager. * * @param session Session to be removed * @param update Should the expiration statistics be updated */ @Override public void remove(Session session, boolean update) { // If the session has expired - as opposed to just being removed from // the manager because it is being persisted - update the expired stats if (update) { long timeNow = System.currentTimeMillis(); int timeAlive = (int) (timeNow - session.getCreationTimeInternal())/1000; updateSessionMaxAliveTime(timeAlive); expiredSessions.incrementAndGet(); SessionTiming timing = new SessionTiming(timeNow, timeAlive); synchronized (sessionExpirationTiming) { sessionExpirationTiming.add(timing); sessionExpirationTiming.poll(); } } if (session.getIdInternal() != null) { sessions.remove(session.getIdInternal()); } } /** * Remove a property change listener from this component. * * @param listener The listener to remove */ @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } /** * Change the session ID of the current session to a new randomly generated * session ID. * * @param session The session to change the session ID for */ @Override public void changeSessionId(Session session) { String oldId = session.getIdInternal(); session.setId(generateSessionId(), false); String newId = session.getIdInternal(); context.fireContainerEvent(Context.CHANGE_SESSION_ID_EVENT, new String[] {oldId, newId}); } // ------------------------------------------------------ Protected Methods /** * Get new session class to be used in the doLoad() method. */ protected StandardSession getNewSession() { return new StandardSession(this); } /** * Generate and return a new session identifier. */ protected String generateSessionId() { String result = null; do { if (result != null) { // Not thread-safe but if one of multiple increments is lost // that is not a big deal since the fact that there was any // duplicate is a much bigger issue. duplicates++; } result = sessionIdGenerator.generateSessionId(); } while (sessions.containsKey(result)); return result; } // ------------------------------------------------------ Protected Methods /** * Retrieve the enclosing Engine for this Manager. * * @return an Engine object (or null). */ public Engine getEngine() { Engine e = null; for (Container c = getContext(); e == null && c != null ; c = c.getParent()) { if (c instanceof Engine) { e = (Engine)c; } } return e; } /** * Retrieve the JvmRoute for the enclosing Engine. * @return the JvmRoute or null. */ public String getJvmRoute() { Engine e = getEngine(); return e == null ? null : e.getJvmRoute(); } // -------------------------------------------------------- Package Methods @Override public void setSessionCounter(long sessionCounter) { this.sessionCounter = sessionCounter; } /** * Total sessions created by this manager. * * @return sessions created */ @Override public long getSessionCounter() { return sessionCounter; } /** * Number of duplicated session IDs generated by the random source. * Anything bigger than 0 means problems. * * @return The count of duplicates */ public int getDuplicates() { return duplicates; } public void setDuplicates(int duplicates) { this.duplicates = duplicates; } /** * Returns the number of active sessions * * @return number of sessions active */ @Override public int getActiveSessions() { return sessions.size(); } /** * Max number of concurrent active sessions * * @return The highest number of concurrent active sessions */ @Override public int getMaxActive() { return maxActive; } @Override public void setMaxActive(int maxActive) { synchronized (maxActiveUpdateLock) { this.maxActive = maxActive; } } /** * Return the maximum number of active Sessions allowed, or -1 for * no limit. */ public int getMaxActiveSessions() { return (this.maxActiveSessions); } /** * Set the maximum number of active Sessions allowed, or -1 for * no limit. * * @param max The new maximum number of sessions */ public void setMaxActiveSessions(int max) { int oldMaxActiveSessions = this.maxActiveSessions; this.maxActiveSessions = max; support.firePropertyChange("maxActiveSessions", Integer.valueOf(oldMaxActiveSessions), Integer.valueOf(this.maxActiveSessions)); } /** * Gets the longest time (in seconds) that an expired session had been * alive. * * @return Longest time (in seconds) that an expired session had been * alive. */ @Override public int getSessionMaxAliveTime() { return sessionMaxAliveTime; } /** * Sets the longest time (in seconds) that an expired session had been * alive. Typically used for resetting the current value. * * @param sessionMaxAliveTime Longest time (in seconds) that an expired * session had been alive. */ @Override public void setSessionMaxAliveTime(int sessionMaxAliveTime) { synchronized (sessionMaxAliveTimeUpdateLock) { this.sessionMaxAliveTime = sessionMaxAliveTime; } } /** * Updates the sessionMaxAliveTime attribute if the candidate value is * larger than the current value. * * @param sessionAliveTime The candidate value (in seconds) for the new * sessionMaxAliveTime value. */ public void updateSessionMaxAliveTime(int sessionAliveTime) { if (sessionAliveTime > this.sessionMaxAliveTime) { synchronized (sessionMaxAliveTimeUpdateLock) { if (sessionAliveTime > this.sessionMaxAliveTime) { this.sessionMaxAliveTime = sessionAliveTime; } } } } /** * Gets the average time (in seconds) that expired sessions had been * alive based on the last 100 sessions to expire. If less than * 100 sessions have expired then all available data is used. * * @return Average time (in seconds) that expired sessions had been * alive. */ @Override public int getSessionAverageAliveTime() { // Copy current stats List<SessionTiming> copy = new ArrayList<>(); synchronized (sessionExpirationTiming) { copy.addAll(sessionExpirationTiming); } // Init int counter = 0; int result = 0; Iterator<SessionTiming> iter = copy.iterator(); // Calculate average while (iter.hasNext()) { SessionTiming timing = iter.next(); if (timing != null) { int timeAlive = timing.getDuration(); counter++; // Very careful not to overflow - probably not necessary result = (result * ((counter - 1)/counter)) + (timeAlive/counter); } } return result; } /** * Gets the current rate of session creation (in session per minute) based * on the creation time of the previous 100 sessions created. If less than * 100 sessions have been created then all available data is used. * * @return The current rate (in sessions per minute) of session creation */ @Override public int getSessionCreateRate() { long now = System.currentTimeMillis(); // Copy current stats List<SessionTiming> copy = new ArrayList<>(); synchronized (sessionCreationTiming) { copy.addAll(sessionCreationTiming); } // Init long oldest = now; int counter = 0; int result = 0; Iterator<SessionTiming> iter = copy.iterator(); // Calculate rate while (iter.hasNext()) { SessionTiming timing = iter.next(); if (timing != null) { counter++; if (timing.getTimestamp() < oldest) { oldest = timing.getTimestamp(); } } } if (counter > 0) { if (oldest < now) { result = (1000*60*counter)/(int) (now - oldest); } else { result = Integer.MAX_VALUE; } } return result; } /** * Gets the current rate of session expiration (in session per minute) based * on the expiry time of the previous 100 sessions expired. If less than * 100 sessions have expired then all available data is used. * * @return The current rate (in sessions per minute) of session expiration */ @Override public int getSessionExpireRate() { long now = System.currentTimeMillis(); // Copy current stats List<SessionTiming> copy = new ArrayList<>(); synchronized (sessionExpirationTiming) { copy.addAll(sessionExpirationTiming); } // Init long oldest = now; int counter = 0; int result = 0; Iterator<SessionTiming> iter = copy.iterator(); // Calculate rate while (iter.hasNext()) { SessionTiming timing = iter.next(); if (timing != null) { counter++; if (timing.getTimestamp() < oldest) { oldest = timing.getTimestamp(); } } } if (counter > 0) { if (oldest < now) { result = (1000*60*counter)/(int) (now - oldest); } else { // Better than reporting zero result = Integer.MAX_VALUE; } } return result; } /** * For debugging: return a list of all session ids currently active * */ public String listSessionIds() { StringBuilder sb=new StringBuilder(); Iterator<String> keys = sessions.keySet().iterator(); while (keys.hasNext()) { sb.append(keys.next()).append(" "); } return sb.toString(); } /** * For debugging: get a session attribute * * @param sessionId * @param key * @return The attribute value, if found, null otherwise */ public String getSessionAttribute( String sessionId, String key ) { Session s = sessions.get(sessionId); if( s==null ) { if(log.isInfoEnabled()) log.info("Session not found " + sessionId); return null; } Object o=s.getSession().getAttribute(key); if( o==null ) return null; return o.toString(); } /** * Returns information about the session with the given session id. * * <p>The session information is organized as a HashMap, mapping * session attribute names to the String representation of their values. * * @param sessionId Session id * * @return HashMap mapping session attribute names to the String * representation of their values, or null if no session with the * specified id exists, or if the session does not have any attributes */ public HashMap<String, String> getSession(String sessionId) { Session s = sessions.get(sessionId); if (s == null) { if (log.isInfoEnabled()) { log.info("Session not found " + sessionId); } return null; } Enumeration<String> ee = s.getSession().getAttributeNames(); if (ee == null || !ee.hasMoreElements()) { return null; } HashMap<String, String> map = new HashMap<>(); while (ee.hasMoreElements()) { String attrName = ee.nextElement(); map.put(attrName, getSessionAttribute(sessionId, attrName)); } return map; } public void expireSession( String sessionId ) { Session s=sessions.get(sessionId); if( s==null ) { if(log.isInfoEnabled()) log.info("Session not found " + sessionId); return; } s.expire(); } public long getThisAccessedTimestamp( String sessionId ) { Session s=sessions.get(sessionId); if(s== null) return -1 ; return s.getThisAccessedTime(); } public String getThisAccessedTime( String sessionId ) { Session s=sessions.get(sessionId); if( s==null ) { if(log.isInfoEnabled()) log.info("Session not found " + sessionId); return ""; } return new Date(s.getThisAccessedTime()).toString(); } public long getLastAccessedTimestamp( String sessionId ) { Session s=sessions.get(sessionId); if(s== null) return -1 ; return s.getLastAccessedTime(); } public String getLastAccessedTime( String sessionId ) { Session s=sessions.get(sessionId); if( s==null ) { if(log.isInfoEnabled()) log.info("Session not found " + sessionId); return ""; } return new Date(s.getLastAccessedTime()).toString(); } public String getCreationTime( String sessionId ) { Session s=sessions.get(sessionId); if( s==null ) { if(log.isInfoEnabled()) log.info("Session not found " + sessionId); return ""; } return new Date(s.getCreationTime()).toString(); } public long getCreationTimestamp( String sessionId ) { Session s=sessions.get(sessionId); if(s== null) return -1 ; return s.getCreationTime(); } /** * Return a String rendering of this object. */ @Override public String toString() { StringBuilder sb = new StringBuilder(this.getClass().getName()); sb.append('['); if (context == null) { sb.append("Context is null"); } else { sb.append(context.getName()); } sb.append(']'); return sb.toString(); } // -------------------- JMX and Registration -------------------- @Override public String getObjectNameKeyProperties() { StringBuilder name = new StringBuilder("type=Manager"); name.append(",context="); String contextName = context.getName(); if (!contextName.startsWith("/")) { name.append('/'); } name.append(contextName); name.append(",host="); name.append(context.getParent().getName()); return name.toString(); } @Override public String getDomainInternal() { return context.getDomain(); } // ----------------------------------------- PropertyChangeListener Methods /** * Process property change events from our associated Context. * * @param event * The property change event that has occurred */ @Override public void propertyChange(PropertyChangeEvent event) { // Validate the source of this event if (!(event.getSource() instanceof Context)) return; // Process a relevant property change if (event.getPropertyName().equals("sessionTimeout")) { try { setMaxInactiveInterval( ((Integer) event.getNewValue()).intValue() * 60); } catch (NumberFormatException e) { log.error(sm.getString("managerBase.sessionTimeout", event.getNewValue())); } } } // ----------------------------------------------------------- Inner classes protected static final class SessionTiming { private final long timestamp; private final int duration; public SessionTiming(long timestamp, int duration) { this.timestamp = timestamp; this.duration = duration; } /** * Time stamp associated with this piece of timing information in * milliseconds. */ public long getTimestamp() { return timestamp; } /** * Duration associated with this piece of timing information in seconds. */ public int getDuration() { return duration; } } }
54,552
Bug 54552 Completed Servlet 3.1 spec for changeSessionId, HttpSessionIdListener
null
resolved fixed
c11952d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:28:58Z
2013-02-12T20:13:20Z
java/org/apache/catalina/websocket/WsHttpServletRequestWrapper.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.websocket; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.Collection; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; 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.tomcat.util.res.StringManager; /** * Wrapper for the HttpServletRequest object that allows the underlying request * object to be invalidated. */ public class WsHttpServletRequestWrapper implements HttpServletRequest { private static final StringManager sm = StringManager.getManager(Constants.Package); private HttpServletRequest request; public WsHttpServletRequestWrapper(HttpServletRequest request) { this.request = request; } private HttpServletRequest getRequest() { if (request == null) { throw new IllegalStateException(sm.getString("wrapper.invalid")); } return request; } protected void invalidate() { request = null; } @Override public Object getAttribute(String name) { return getRequest().getAttribute(name); } @Override public Enumeration<String> getAttributeNames() { return getRequest().getAttributeNames(); } @Override public String getCharacterEncoding() { return getRequest().getCharacterEncoding(); } @Override public void setCharacterEncoding(String env) throws UnsupportedEncodingException { getRequest().setCharacterEncoding(env); } @Override public int getContentLength() { return getRequest().getContentLength(); } @Override public long getContentLengthLong() { return getRequest().getContentLengthLong(); } @Override public String getContentType() { return getRequest().getContentType(); } @Override public ServletInputStream getInputStream() throws IOException { return getRequest().getInputStream(); } @Override public String getParameter(String name) { return getRequest().getParameter(name); } @Override public Enumeration<String> getParameterNames() { return getRequest().getParameterNames(); } @Override public String[] getParameterValues(String name) { return getRequest().getParameterValues(name); } @Override public Map<String, String[]> getParameterMap() { return getRequest().getParameterMap(); } @Override public String getProtocol() { return getRequest().getProtocol(); } @Override public String getScheme() { return getRequest().getScheme(); } @Override public String getServerName() { return getRequest().getServerName(); } @Override public int getServerPort() { return getRequest().getServerPort(); } @Override public BufferedReader getReader() throws IOException { return getRequest().getReader(); } @Override public String getRemoteAddr() { return getRequest().getRemoteAddr(); } @Override public String getRemoteHost() { return getRequest().getRemoteHost(); } @Override public void setAttribute(String name, Object o) { getRequest().setAttribute(name, o); } @Override public void removeAttribute(String name) { getRequest().removeAttribute(name); } @Override public Locale getLocale() { return getRequest().getLocale(); } @Override public Enumeration<Locale> getLocales() { return getRequest().getLocales(); } @Override public boolean isSecure() { return getRequest().isSecure(); } @Override public RequestDispatcher getRequestDispatcher(String path) { return getRequest().getRequestDispatcher(path); } @Override @Deprecated public String getRealPath(String path) { return getRequest().getRealPath(path); } @Override public int getRemotePort() { return getRequest().getRemotePort(); } @Override public String getLocalName() { return getRequest().getLocalName(); } @Override public String getLocalAddr() { return getRequest().getLocalAddr(); } @Override public int getLocalPort() { return getRequest().getLocalPort(); } @Override public ServletContext getServletContext() { return getRequest().getServletContext(); } @Override public AsyncContext startAsync() throws IllegalStateException { return getRequest().startAsync(); } @Override public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException { return getRequest().startAsync(servletRequest, servletResponse); } @Override public boolean isAsyncStarted() { return getRequest().isAsyncStarted(); } @Override public boolean isAsyncSupported() { return getRequest().isAsyncSupported(); } @Override public AsyncContext getAsyncContext() { return getRequest().getAsyncContext(); } @Override public DispatcherType getDispatcherType() { return getRequest().getDispatcherType(); } @Override public String getAuthType() { return getRequest().getAuthType(); } @Override public Cookie[] getCookies() { return getRequest().getCookies(); } @Override public long getDateHeader(String name) { return getRequest().getDateHeader(name); } @Override public String getHeader(String name) { return getRequest().getHeader(name); } @Override public Enumeration<String> getHeaders(String name) { return getRequest().getHeaders(name); } @Override public Enumeration<String> getHeaderNames() { return getRequest().getHeaderNames(); } @Override public int getIntHeader(String name) { return getRequest().getIntHeader(name); } @Override public String getMethod() { return getRequest().getMethod(); } @Override public String getPathInfo() { return getRequest().getPathInfo(); } @Override public String getPathTranslated() { return getRequest().getPathTranslated(); } @Override public String getContextPath() { return getRequest().getContextPath(); } @Override public String getQueryString() { return getRequest().getQueryString(); } @Override public String getRemoteUser() { return getRequest().getRemoteUser(); } @Override public boolean isUserInRole(String role) { return getRequest().isUserInRole(role); } @Override public Principal getUserPrincipal() { return getRequest().getUserPrincipal(); } @Override public String getRequestedSessionId() { return getRequest().getRequestedSessionId(); } @Override public String getRequestURI() { return getRequest().getRequestURI(); } @Override public StringBuffer getRequestURL() { return getRequest().getRequestURL(); } @Override public String getServletPath() { return getRequest().getServletPath(); } @Override public HttpSession getSession(boolean create) { return getRequest().getSession(create); } @Override public HttpSession getSession() { return getRequest().getSession(); } @Override public boolean isRequestedSessionIdValid() { return getRequest().isRequestedSessionIdValid(); } @Override public boolean isRequestedSessionIdFromCookie() { return getRequest().isRequestedSessionIdFromCookie(); } @Override public boolean isRequestedSessionIdFromURL() { return getRequest().isRequestedSessionIdFromURL(); } @Override @Deprecated public boolean isRequestedSessionIdFromUrl() { return getRequest().isRequestedSessionIdFromUrl(); } @Override public boolean authenticate(HttpServletResponse response) throws IOException, ServletException { return getRequest().authenticate(response); } @Override public void login(String username, String password) throws ServletException { getRequest().login(username, password); } @Override public void logout() throws ServletException { getRequest().logout(); } @Override public Collection<Part> getParts() throws IOException, ServletException { return getRequest().getParts(); } @Override public Part getPart(String name) throws IOException, ServletException { return getRequest().getPart(name); } @Override public void upgrade(HttpUpgradeHandler handler) throws IOException { getRequest().upgrade(handler); } }
54,203
Bug 54203 Part class missing documentation
null
resolved fixed
81eaf63
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-13T09:50:21Z
2012-11-25T13:26:40Z
java/javax/servlet/http/Part.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 javax.servlet.http; import java.io.IOException; import java.io.InputStream; import java.util.Collection; /** * @since Servlet 3.0 * TODO SERVLET3 - Add comments */ public interface Part { public InputStream getInputStream() throws IOException; public String getContentType(); public String getName(); public long getSize(); public void write(String fileName) throws IOException; public void delete() throws IOException; /** * Obtains the value of the specified mime header for the part. * @param name Header name * @return The header value or <code>null</code> if the header is not * present */ public String getHeader(String name); public Collection<String> getHeaders(String name); public Collection<String> getHeaderNames(); }
54,602
Bug 54602 B2CConverter character decode underflow leaves bytes in buffer
If a request contains a uri that ends in a multi byte character which is missing a byte the extra bytes are left in a buffer which is reused by a future request. The problem comes from two different things: 1) If B2CConverter tries to convert a ByteChunk which ends in a character underflow it does not convert that last character and it is left in a buffer in B2CConver. 2) The B2CConverter in org.apache.catalina.connector.Request is not recycled with the rest of the objects. It looks like this is done intentionally based on the comment above it's declaration. The issue with B2CConverter can be demonstrated with the code below, which is a simplification of what is done inside of CoyoteAdapter.convertURI(): <code> B2CConverter conv = new B2CConverter("UTF-8"); ByteChunk bc = new ByteChunk(); CharChunk cc = new CharChunk(); byte[] bytes = { 0x61, 0x62, 0x63, 0x64, -8, -69, -73, -77 }; bc.append(bytes, 0, bytes.length); cc.allocate(bc.getLength(), -1); conv.convert(bc, cc, cc.getBuffer().length - cc.getEnd()); System.out.println(cc); cc.recycle(); bc.recycle(); bc.append(bytes, 0, bytes.length); cc.allocate(bc.getLength(), -1); conv.convert(bc, cc, cc.getBuffer().length - cc.getEnd()); System.out.println(cc); </code> If the B2CConverter was recycled with everything else in Request this would prevent a previous request from corrupting the next request but it doesn't fix the issue that a character is dropped from the initial decode. I tried playing with B2CConverter and the only way I could get the convert to get everything was by ignoring the limit argument and reading to the end of the stream. It looks like tomcat8 is moving in this direction with the move to NIO, however I tried playing with the latest B2CConverter and was still seeing issues with the given byte sequence.
resolved fixed
b2f0e7c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-22T21:38:20Z
2013-02-23T00:40:00Z
java/org/apache/catalina/connector/CoyoteAdapter.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.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.EnumSet; import javax.servlet.RequestDispatcher; import javax.servlet.SessionTrackingMode; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.Wrapper; import org.apache.catalina.comet.CometEvent; import org.apache.catalina.comet.CometEvent.EventType; import org.apache.catalina.core.AsyncContextImpl; import org.apache.catalina.util.ServerInfo; import org.apache.catalina.util.SessionConfig; import org.apache.catalina.util.URLEncoder; import org.apache.coyote.ActionCode; import org.apache.coyote.Adapter; 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.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.Cookies; import org.apache.tomcat.util.http.ServerCookie; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.res.StringManager; /** * Implementation of a request processor which delegates the processing to a * Coyote processor. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class CoyoteAdapter implements Adapter { private static final Log log = LogFactory.getLog(CoyoteAdapter.class); // -------------------------------------------------------------- Constants private static final String POWERED_BY = "Servlet/3.1 JSP/2.2 " + "(" + ServerInfo.getServerInfo() + " Java/" + System.getProperty("java.vm.vendor") + "/" + System.getProperty("java.runtime.version") + ")"; private static final EnumSet<SessionTrackingMode> SSL_ONLY = EnumSet.of(SessionTrackingMode.SSL); public static final int ADAPTER_NOTES = 1; protected static final boolean ALLOW_BACKSLASH = Boolean.valueOf(System.getProperty("org.apache.catalina.connector.CoyoteAdapter.ALLOW_BACKSLASH", "false")).booleanValue(); private static final ThreadLocal<String> THREAD_NAME = new ThreadLocal<String>() { @Override protected String initialValue() { return Thread.currentThread().getName(); } }; // ----------------------------------------------------------- Constructors /** * Construct a new CoyoteProcessor associated with the specified connector. * * @param connector CoyoteConnector that owns this processor */ public CoyoteAdapter(Connector connector) { super(); this.connector = connector; } // ----------------------------------------------------- Instance Variables /** * The CoyoteConnector with which this processor is associated. */ private final Connector connector; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Encoder for the Location URL in HTTP redirects. */ protected static final URLEncoder urlEncoder; // ----------------------------------------------------- Static Initializer /** * The safe character set. */ static { urlEncoder = new URLEncoder(); urlEncoder.addSafeCharacter('-'); urlEncoder.addSafeCharacter('_'); urlEncoder.addSafeCharacter('.'); urlEncoder.addSafeCharacter('*'); urlEncoder.addSafeCharacter('/'); } // -------------------------------------------------------- Adapter Methods /** * Event method. * * @return false to indicate an error, expected or not */ @Override public boolean event(org.apache.coyote.Request req, org.apache.coyote.Response res, SocketStatus status) { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request.getWrapper() == null) { return false; } boolean error = false; boolean read = false; try { if (status == SocketStatus.OPEN_READ) { if (response.isClosed()) { // The event has been closed asynchronously, so call end instead of // read to cleanup the pipeline request.getEvent().setEventType(CometEvent.EventType.END); request.getEvent().setEventSubType(null); } else { try { // Fill the read buffer of the servlet layer if (request.read()) { read = true; } } catch (IOException e) { error = true; } if (read) { request.getEvent().setEventType(CometEvent.EventType.READ); request.getEvent().setEventSubType(null); } else if (error) { request.getEvent().setEventType(CometEvent.EventType.ERROR); request.getEvent().setEventSubType(CometEvent.EventSubType.CLIENT_DISCONNECT); } else { request.getEvent().setEventType(CometEvent.EventType.END); request.getEvent().setEventSubType(null); } } } else if (status == SocketStatus.DISCONNECT) { request.getEvent().setEventType(CometEvent.EventType.ERROR); request.getEvent().setEventSubType(CometEvent.EventSubType.CLIENT_DISCONNECT); error = true; } else if (status == SocketStatus.ERROR) { request.getEvent().setEventType(CometEvent.EventType.ERROR); request.getEvent().setEventSubType(CometEvent.EventSubType.IOEXCEPTION); error = true; } else if (status == SocketStatus.STOP) { request.getEvent().setEventType(CometEvent.EventType.END); request.getEvent().setEventSubType(CometEvent.EventSubType.SERVER_SHUTDOWN); } else if (status == SocketStatus.TIMEOUT) { if (response.isClosed()) { // The event has been closed asynchronously, so call end instead of // read to cleanup the pipeline request.getEvent().setEventType(CometEvent.EventType.END); request.getEvent().setEventSubType(null); } else { request.getEvent().setEventType(CometEvent.EventType.ERROR); request.getEvent().setEventSubType(CometEvent.EventSubType.TIMEOUT); } } req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); // Calling the container connector.getService().getContainer().getPipeline().getFirst().event(request, response, request.getEvent()); if (!error && !response.isClosed() && (request.getAttribute( RequestDispatcher.ERROR_EXCEPTION) != null)) { // An unexpected exception occurred while processing the event, so // error should be called request.getEvent().setEventType(CometEvent.EventType.ERROR); request.getEvent().setEventSubType(null); error = true; connector.getService().getContainer().getPipeline().getFirst().event(request, response, request.getEvent()); } if (response.isClosed() || !request.isComet()) { if (status==SocketStatus.OPEN_READ && request.getEvent().getEventType() != EventType.END) { //CometEvent.close was called during an event other than END request.getEvent().setEventType(CometEvent.EventType.END); request.getEvent().setEventSubType(null); error = true; connector.getService().getContainer().getPipeline().getFirst().event(request, response, request.getEvent()); } res.action(ActionCode.COMET_END, null); } else if (!error && read && request.getAvailable()) { // If this was a read and not all bytes have been read, or if no data // was read from the connector, then it is an error request.getEvent().setEventType(CometEvent.EventType.ERROR); request.getEvent().setEventSubType(CometEvent.EventSubType.IOEXCEPTION); error = true; connector.getService().getContainer().getPipeline().getFirst().event(request, response, request.getEvent()); } return (!error); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (!(t instanceof IOException)) { log.error(sm.getString("coyoteAdapter.service"), t); } error = true; return false; } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (error || response.isClosed() || !request.isComet()) { request.getMappingData().context.logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); request.recycle(); request.setFilterChain(null); response.recycle(); } } } @Override public boolean asyncDispatch(org.apache.coyote.Request req, org.apache.coyote.Response res, SocketStatus status) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { throw new IllegalStateException( "Dispatch may only happen on an existing request."); } boolean comet = false; boolean success = true; AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); req.getRequestProcessor().setWorkerThreadName(Thread.currentThread().getName()); try { if (!request.isAsync() && !comet) { // Error or timeout - need to tell listeners the request is over // Have to test this first since state may change while in this // method and this is only required if entering this method in // this state Context ctxt = request.getMappingData().context; if (ctxt != null) { ctxt.fireRequestDestroyEvent(request); } // Lift any suspension (e.g. if sendError() was used by an async // request) to allow the response to be written to the client response.setSuspended(false); } if (status==SocketStatus.TIMEOUT) { success = true; if (!asyncConImpl.timeout()) { asyncConImpl.setErrorState(null, false); } } else if (status==SocketStatus.ASYNC_READ_ERROR) { success = true; Throwable t = (Throwable)req.getAttribute(RequestDispatcher.ERROR_EXCEPTION); req.getAttributes().remove(RequestDispatcher.ERROR_EXCEPTION); asyncConImpl.notifyReadError(t); if (t != null) { asyncConImpl.setErrorState(t, true); } } else if (status==SocketStatus.ASYNC_WRITE_ERROR) { success = true; Throwable t = (Throwable)req.getAttribute(RequestDispatcher.ERROR_EXCEPTION); req.getAttributes().remove(RequestDispatcher.ERROR_EXCEPTION); asyncConImpl.notifyWriteError(t); if (t != null) { asyncConImpl.setErrorState(t, true); } } if (!request.isAsyncDispatching() && request.isAsync() && request.isAsyncOperation()) { if (status == SocketStatus.OPEN_WRITE) { // TODO Notify write listener success = asyncConImpl.canWrite(); } else if (status == SocketStatus.OPEN_READ) { // TODO Notify read listener success = asyncConImpl.canRead(); } } if (request.isAsyncDispatching()) { success = true; connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); Throwable t = (Throwable) request.getAttribute( RequestDispatcher.ERROR_EXCEPTION); if (t != null) { asyncConImpl.setErrorState(t, true); } } if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN_READ)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } if (!request.isAsync() && !comet) { request.finishRequest(); response.finishResponse(); req.action(ActionCode.POST_REQUEST , null); request.getMappingData().context.logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } } catch (IOException e) { success = false; // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); success = false; log.error(sm.getString("coyoteAdapter.service"), t); } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!success || (!comet && !request.isAsync())) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } return success; } /** * Service method. */ @Override public void service(org.apache.coyote.Request req, org.apache.coyote.Response res) throws Exception { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { // Create objects request = connector.createRequest(); request.setCoyoteRequest(req); response = connector.createResponse(); response.setCoyoteResponse(res); // Link objects request.setResponse(response); response.setRequest(request); // Set as notes req.setNote(ADAPTER_NOTES, request); res.setNote(ADAPTER_NOTES, response); // Set query string encoding req.getParameters().setQueryStringEncoding (connector.getURIEncoding()); } if (connector.getXpoweredBy()) { response.addHeader("X-Powered-By", POWERED_BY); } boolean comet = false; boolean async = false; try { // Parse and set Catalina and configuration specific // request parameters req.getRequestProcessor().setWorkerThreadName(THREAD_NAME.get()); boolean postParseSuccess = postParseRequest(req, request, res, response); if (postParseSuccess) { //check valves if we support async request.setAsyncSupported(connector.getService().getContainer().getPipeline().isAsyncSupported()); // Calling the container connector.getService().getContainer().getPipeline().getFirst().invoke(request, response); if (request.isComet()) { if (!response.isClosed() && !response.isError()) { if (request.getAvailable() || (request.getContentLength() > 0 && (!request.isParametersParsed()))) { // Invoke a read event right away if there are available bytes if (event(req, res, SocketStatus.OPEN_READ)) { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { comet = true; res.action(ActionCode.COMET_BEGIN, null); } } else { // Clear the filter chain, as otherwise it will not be reset elsewhere // since this is a Comet request request.setFilterChain(null); } } } AsyncContextImpl asyncConImpl = (AsyncContextImpl)request.getAsyncContext(); if (asyncConImpl != null) { async = true; } else if (!comet) { request.finishRequest(); response.finishResponse(); if (postParseSuccess && request.getMappingData().context != null) { // Log only if processing was invoked. // If postParseRequest() failed, it has already logged it. // If context is null this was the start of a comet request // that failed and has already been logged. request.getMappingData().context.logAccess( request, response, System.currentTimeMillis() - req.getStartTime(), false); } req.action(ActionCode.POST_REQUEST , null); } } catch (IOException e) { // Ignore } finally { req.getRequestProcessor().setWorkerThreadName(null); // Recycle the wrapper request and response if (!comet && !async) { request.recycle(); response.recycle(); } else { // Clear converters so that the minimum amount of memory // is used by this processor request.clearEncoders(); response.clearEncoders(); } } } @Override public void log(org.apache.coyote.Request req, org.apache.coyote.Response res, long time) { Request request = (Request) req.getNote(ADAPTER_NOTES); Response response = (Response) res.getNote(ADAPTER_NOTES); if (request == null) { // Create objects request = connector.createRequest(); request.setCoyoteRequest(req); response = connector.createResponse(); response.setCoyoteResponse(res); // Link objects request.setResponse(response); response.setRequest(request); // Set as notes req.setNote(ADAPTER_NOTES, request); res.setNote(ADAPTER_NOTES, response); // Set query string encoding req.getParameters().setQueryStringEncoding (connector.getURIEncoding()); } try { // Log at the lowest level available. logAccess() will be // automatically called on parent containers. boolean logged = false; if (request.mappingData != null) { if (request.mappingData.context != null) { logged = true; request.mappingData.context.logAccess( request, response, time, true); } else if (request.mappingData.host != null) { logged = true; request.mappingData.host.logAccess( request, response, time, true); } } if (!logged) { connector.getService().getContainer().logAccess( request, response, time, true); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteAdapter.accesslogFail"), t); } finally { request.recycle(); response.recycle(); } } @Override public String getDomain() { return connector.getDomain(); } // ------------------------------------------------------ Protected Methods /** * Parse additional request parameters. */ protected boolean postParseRequest(org.apache.coyote.Request req, Request request, org.apache.coyote.Response res, Response response) throws Exception { // XXX the processor may have set a correct scheme and port prior to this point, // in ajp13 protocols dont make sense to get the port from the connector... // otherwise, use connector configuration if (! req.scheme().isNull()) { // use processor specified scheme to determine secure state request.setSecure(req.scheme().equals("https")); } else { // use connector scheme and secure configuration, (defaults to // "http" and false respectively) req.scheme().setString(connector.getScheme()); request.setSecure(connector.getSecure()); } // FIXME: the code below doesnt belongs to here, // this is only have sense // in Http11, not in ajp13.. // At this point the Host header has been processed. // Override if the proxyPort/proxyHost are set String proxyName = connector.getProxyName(); int proxyPort = connector.getProxyPort(); if (proxyPort != 0) { req.setServerPort(proxyPort); } if (proxyName != null) { req.serverName().setString(proxyName); } // Copy the raw URI to the decodedURI MessageBytes decodedURI = req.decodedURI(); decodedURI.duplicate(req.requestURI()); if (decodedURI.getType() == MessageBytes.T_BYTES) { // Parse the path parameters. This will: // - strip out the path parameters // - convert the decodedURI to bytes parsePathParameters(req, request); // URI decoding // %xx decoding of the URL try { req.getURLDecoder().convert(decodedURI, false); } catch (IOException ioe) { res.setStatus(400); res.setMessage("Invalid URI: " + ioe.getMessage()); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Normalization if (!normalize(req.decodedURI())) { res.setStatus(400); res.setMessage("Invalid URI"); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } // Character decoding convertURI(decodedURI, request); // Check that the URI is still normalized if (!checkNormalize(req.decodedURI())) { res.setStatus(400); res.setMessage("Invalid URI character encoding"); connector.getService().getContainer().logAccess( request, response, 0, true); return false; } } else { // The URL is chars or String, and has been sent using an in-memory // protocol handler, we have to assume the URL has been properly // decoded already decodedURI.toChars(); // Remove all path parameters; any needed path parameter should be set // using the request object rather than passing it in the URL CharChunk uriCC = decodedURI.getCharChunk(); int semicolon = uriCC.indexOf(';'); if (semicolon > 0) { decodedURI.setChars (uriCC.getBuffer(), uriCC.getStart(), semicolon); } } // Set the remote principal String principal = req.getRemoteUser().toString(); if (principal != null) { request.setUserPrincipal(new CoyotePrincipal(principal)); } // Set the authorization type String authtype = req.getAuthType().toString(); if (authtype != null) { request.setAuthType(authtype); } // Request mapping. MessageBytes serverName; if (connector.getUseIPVHosts()) { serverName = req.localName(); if (serverName.isNull()) { // well, they did ask for it res.action(ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, null); } } else { serverName = req.serverName(); } if (request.isAsyncStarted()) { //TODO SERVLET3 - async //reset mapping data, should prolly be done elsewhere request.getMappingData().recycle(); } boolean mapRequired = true; String version = null; while (mapRequired) { if (version != null) { // Once we have a version - that is it mapRequired = false; } // This will map the the latest version by default connector.getService().getMapper().map(serverName, decodedURI, version, request.getMappingData()); request.setContext(request.getMappingData().context); request.setWrapper(request.getMappingData().wrapper); // Single contextVersion therefore no possibility of remap if (request.getMappingData().contexts == null) { mapRequired = false; } // If there is no context at this point, it is likely no ROOT context // has been deployed if (request.getContext() == null) { res.setStatus(404); res.setMessage("Not found"); // No context, so use host Host host = request.getHost(); // Make sure there is a host (might not be during shutdown) if (host != null) { host.logAccess(request, response, 0, true); } return false; } // Now we have the context, we can parse the session ID from the URL // (if any). Need to do this before we redirect in case we need to // include the session id in the redirect String sessionID = null; if (request.getServletContext().getEffectiveSessionTrackingModes() .contains(SessionTrackingMode.URL)) { // Get the session ID if there was one sessionID = request.getPathParameter( SessionConfig.getSessionUriParamName( request.getContext())); if (sessionID != null) { request.setRequestedSessionId(sessionID); request.setRequestedSessionURL(true); } } // Look for session ID in cookies and SSL session parseSessionCookiesId(req, request); parseSessionSslId(request); sessionID = request.getRequestedSessionId(); if (mapRequired) { if (sessionID == null) { // No session means no possibility of needing to remap mapRequired = false; } else { // Find the context associated with the session Context[] contexts = request.getMappingData().contexts; for (int i = (contexts.length); i > 0; i--) { Context ctxt = contexts[i - 1]; if (ctxt.getManager().findSession(sessionID) != null) { // Was the correct context already mapped? if (ctxt.equals(request.getMappingData().context)) { mapRequired = false; } else { // Set version so second time through mapping the // correct context is found version = ctxt.getWebappVersion(); // Reset mapping request.getMappingData().recycle(); break; } } } if (version == null) { // No matching context found. No need to re-map mapRequired = false; } } } if (!mapRequired && request.getContext().getPaused()) { // Found a matching context but it is paused. Mapping data will // be wrong since some Wrappers may not be registered at this // point. try { Thread.sleep(1000); } catch (InterruptedException e) { // Should never happen } // Reset mapping request.getMappingData().recycle(); mapRequired = true; } } // Possible redirect MessageBytes redirectPathMB = request.getMappingData().redirectPath; if (!redirectPathMB.isNull()) { String redirectPath = urlEncoder.encode(redirectPathMB.toString()); String query = request.getQueryString(); if (request.isRequestedSessionIdFromURL()) { // This is not optimal, but as this is not very common, it // shouldn't matter redirectPath = redirectPath + ";" + SessionConfig.getSessionUriParamName( request.getContext()) + "=" + request.getRequestedSessionId(); } if (query != null) { // This is not optimal, but as this is not very common, it // shouldn't matter redirectPath = redirectPath + "?" + query; } response.sendRedirect(redirectPath); request.getContext().logAccess(request, response, 0, true); return false; } // Filter trace method if (!connector.getAllowTrace() && req.method().equalsIgnoreCase("TRACE")) { Wrapper wrapper = request.getWrapper(); String header = null; if (wrapper != null) { String[] methods = wrapper.getServletMethods(); if (methods != null) { for (int i=0; i<methods.length; i++) { if ("TRACE".equals(methods[i])) { continue; } if (header == null) { header = methods[i]; } else { header += ", " + methods[i]; } } } } res.setStatus(405); res.addHeader("Allow", header); res.setMessage("TRACE method is not allowed"); request.getContext().logAccess(request, response, 0, true); return false; } return true; } /** * Extract the path parameters from the request. This assumes parameters are * of the form /path;name=value;name2=value2/ etc. Currently only really * interested in the session ID that will be in this form. Other parameters * can safely be ignored. * * @param req * @param request */ protected void parsePathParameters(org.apache.coyote.Request req, Request request) { // Process in bytes (this is default format so this is normally a NO-OP req.decodedURI().toBytes(); ByteChunk uriBC = req.decodedURI().getByteChunk(); int semicolon = uriBC.indexOf(';', 0); // What encoding to use? Some platforms, eg z/os, use a default // encoding that doesn't give the expected result so be explicit String enc = connector.getURIEncodingLower(); if (enc == null) { enc = "iso-8859-1"; } Charset charset = null; try { charset = B2CConverter.getCharsetLower(enc); } catch (UnsupportedEncodingException e1) { log.warn(sm.getString("coyoteAdapter.parsePathParam", enc)); } if (log.isDebugEnabled()) { log.debug(sm.getString("coyoteAdapter.debug", "uriBC", uriBC.toString())); log.debug(sm.getString("coyoteAdapter.debug", "semicolon", String.valueOf(semicolon))); log.debug(sm.getString("coyoteAdapter.debug", "enc", enc)); } while (semicolon > -1) { // Parse path param, and extract it from the decoded request URI int start = uriBC.getStart(); int end = uriBC.getEnd(); int pathParamStart = semicolon + 1; int pathParamEnd = ByteChunk.findBytes(uriBC.getBuffer(), start + pathParamStart, end, new byte[] {';', '/'}); String pv = null; if (pathParamEnd >= 0) { if (charset != null) { pv = new String(uriBC.getBuffer(), start + pathParamStart, pathParamEnd - pathParamStart, charset); } // Extract path param from decoded request URI byte[] buf = uriBC.getBuffer(); for (int i = 0; i < end - start - pathParamEnd; i++) { buf[start + semicolon + i] = buf[start + i + pathParamEnd]; } uriBC.setBytes(buf, start, end - start - pathParamEnd + semicolon); } else { if (charset != null) { pv = new String(uriBC.getBuffer(), start + pathParamStart, (end - start) - pathParamStart, charset); } uriBC.setEnd(start + semicolon); } if (log.isDebugEnabled()) { log.debug(sm.getString("coyoteAdapter.debug", "pathParamStart", String.valueOf(pathParamStart))); log.debug(sm.getString("coyoteAdapter.debug", "pathParamEnd", String.valueOf(pathParamEnd))); log.debug(sm.getString("coyoteAdapter.debug", "pv", pv)); } if (pv != null) { int equals = pv.indexOf('='); if (equals > -1) { String name = pv.substring(0, equals); String value = pv.substring(equals + 1); request.addPathParameter(name, value); if (log.isDebugEnabled()) { log.debug(sm.getString("coyoteAdapter.debug", "equals", String.valueOf(equals))); log.debug(sm.getString("coyoteAdapter.debug", "name", name)); log.debug(sm.getString("coyoteAdapter.debug", "value", value)); } } } semicolon = uriBC.indexOf(';', semicolon); } } /** * Look for SSL session ID if required. Only look for SSL Session ID if it * is the only tracking method enabled. */ protected void parseSessionSslId(Request request) { if (request.getRequestedSessionId() == null && SSL_ONLY.equals(request.getServletContext() .getEffectiveSessionTrackingModes()) && request.connector.secure) { // TODO Is there a better way to map SSL sessions to our sesison ID? // TODO The request.getAttribute() will cause a number of other SSL // attribute to be populated. Is this a performance concern? request.setRequestedSessionId( request.getAttribute(SSLSupport.SESSION_ID_KEY).toString()); request.setRequestedSessionSSL(true); } } /** * Parse session id in URL. */ protected void parseSessionCookiesId(org.apache.coyote.Request req, Request request) { // If session tracking via cookies has been disabled for the current // context, don't go looking for a session ID in a cookie as a cookie // from a parent context with a session ID may be present which would // overwrite the valid session ID encoded in the URL Context context = request.getMappingData().context; if (context != null && !context.getServletContext() .getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { return; } // Parse session id from cookies Cookies serverCookies = req.getCookies(); int count = serverCookies.getCookieCount(); if (count <= 0) { return; } String sessionCookieName = SessionConfig.getSessionCookieName(context); for (int i = 0; i < count; i++) { ServerCookie scookie = serverCookies.getCookie(i); if (scookie.getName().equals(sessionCookieName)) { // Override anything requested in the URL if (!request.isRequestedSessionIdFromCookie()) { // Accept only the first session id cookie convertMB(scookie.getValue()); request.setRequestedSessionId (scookie.getValue().toString()); request.setRequestedSessionCookie(true); request.setRequestedSessionURL(false); if (log.isDebugEnabled()) { log.debug(" Requested cookie session id is " + request.getRequestedSessionId()); } } else { if (!request.isRequestedSessionIdValid()) { // Replace the session id until one is valid convertMB(scookie.getValue()); request.setRequestedSessionId (scookie.getValue().toString()); } } } } } /** * Character conversion of the URI. */ protected void convertURI(MessageBytes uri, Request request) throws Exception { ByteChunk bc = uri.getByteChunk(); int length = bc.getLength(); CharChunk cc = uri.getCharChunk(); cc.allocate(length, -1); String enc = connector.getURIEncoding(); if (enc != null) { B2CConverter conv = request.getURIConverter(); try { if (conv == null) { conv = new B2CConverter(enc); request.setURIConverter(conv); } } catch (IOException e) { // Ignore log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); } if (conv != null) { try { conv.convert(bc, cc); uri.setChars(cc.getBuffer(), cc.getStart(), cc.getLength()); return; } catch (IOException e) { log.error("Invalid URI character encoding; trying ascii"); cc.recycle(); } } } // Default encoding: fast conversion byte[] bbuf = bc.getBuffer(); char[] cbuf = cc.getBuffer(); int start = bc.getStart(); for (int i = 0; i < length; i++) { cbuf[i] = (char) (bbuf[i + start] & 0xff); } uri.setChars(cbuf, 0, length); } /** * Character conversion of the a US-ASCII MessageBytes. */ protected void convertMB(MessageBytes mb) { // This is of course only meaningful for bytes if (mb.getType() != MessageBytes.T_BYTES) { return; } ByteChunk bc = mb.getByteChunk(); CharChunk cc = mb.getCharChunk(); int length = bc.getLength(); cc.allocate(length, -1); // Default encoding: fast conversion byte[] bbuf = bc.getBuffer(); char[] cbuf = cc.getBuffer(); int start = bc.getStart(); for (int i = 0; i < length; i++) { cbuf[i] = (char) (bbuf[i + start] & 0xff); } mb.setChars(cbuf, 0, length); } /** * Normalize URI. * <p> * This method normalizes "\", "//", "/./" and "/../". This method will * return false when trying to go above the root, or if the URI contains * a null byte. * * @param uriMB URI to be normalized */ public static boolean normalize(MessageBytes uriMB) { ByteChunk uriBC = uriMB.getByteChunk(); final byte[] b = uriBC.getBytes(); final int start = uriBC.getStart(); int end = uriBC.getEnd(); // An empty URL is not acceptable if (start == end) { return false; } // URL * is acceptable if ((end - start == 1) && b[start] == (byte) '*') { return true; } int pos = 0; int index = 0; // Replace '\' with '/' // Check for null byte for (pos = start; pos < end; pos++) { if (b[pos] == (byte) '\\') { if (ALLOW_BACKSLASH) { b[pos] = (byte) '/'; } else { return false; } } if (b[pos] == (byte) 0) { return false; } } // The URL must start with '/' if (b[start] != (byte) '/') { return false; } // Replace "//" with "/" for (pos = start; pos < (end - 1); pos++) { if (b[pos] == (byte) '/') { while ((pos + 1 < end) && (b[pos + 1] == (byte) '/')) { copyBytes(b, pos, pos + 1, end - pos - 1); end--; } } } // If the URI ends with "/." or "/..", then we append an extra "/" // Note: It is possible to extend the URI by 1 without any side effect // as the next character is a non-significant WS. if (((end - start) >= 2) && (b[end - 1] == (byte) '.')) { if ((b[end - 2] == (byte) '/') || ((b[end - 2] == (byte) '.') && (b[end - 3] == (byte) '/'))) { b[end] = (byte) '/'; end++; } } uriBC.setEnd(end); index = 0; // Resolve occurrences of "/./" in the normalized path while (true) { index = uriBC.indexOf("/./", 0, 3, index); if (index < 0) { break; } copyBytes(b, start + index, start + index + 2, end - start - index - 2); end = end - 2; uriBC.setEnd(end); } index = 0; // Resolve occurrences of "/../" in the normalized path while (true) { index = uriBC.indexOf("/../", 0, 4, index); if (index < 0) { break; } // Prevent from going outside our context if (index == 0) { return false; } int index2 = -1; for (pos = start + index - 1; (pos >= 0) && (index2 < 0); pos --) { if (b[pos] == (byte) '/') { index2 = pos; } } copyBytes(b, start + index2, start + index + 3, end - start - index - 3); end = end + index2 - index - 3; uriBC.setEnd(end); index = index2; } return true; } /** * Check that the URI is normalized following character decoding. * <p> * This method checks for "\", 0, "//", "/./" and "/../". This method will * return false if sequences that are supposed to be normalized are still * present in the URI. * * @param uriMB URI to be checked (should be chars) */ public static boolean checkNormalize(MessageBytes uriMB) { CharChunk uriCC = uriMB.getCharChunk(); char[] c = uriCC.getChars(); int start = uriCC.getStart(); int end = uriCC.getEnd(); int pos = 0; // Check for '\' and 0 for (pos = start; pos < end; pos++) { if (c[pos] == '\\') { return false; } if (c[pos] == 0) { return false; } } // Check for "//" for (pos = start; pos < (end - 1); pos++) { if (c[pos] == '/') { if (c[pos + 1] == '/') { return false; } } } // Check for ending with "/." or "/.." if (((end - start) >= 2) && (c[end - 1] == '.')) { if ((c[end - 2] == '/') || ((c[end - 2] == '.') && (c[end - 3] == '/'))) { return false; } } // Check for "/./" if (uriCC.indexOf("/./", 0, 3, 0) >= 0) { return false; } // Check for "/../" if (uriCC.indexOf("/../", 0, 4, 0) >= 0) { return false; } return true; } // ------------------------------------------------------ Protected Methods /** * Copy an array of bytes to a different position. Used during * normalization. */ protected static void copyBytes(byte[] b, int dest, int src, int len) { for (int pos = 0; pos < len; pos++) { b[pos + dest] = b[pos + src]; } } }
54,585
Bug 54585 WebappLoader doesn't honor delegate attr while constructing jsp_classpath
If custom WebappClassLoader is created with delegate=true then parent-first classloading model is used. Everything works here as expected. However jsp_classpath is always constructed in the following manner: customWebappClassLoader.urls;parent.urls;parent...parent.urls Whereas it is expected to me that if delegate=true then parent's urls should come first.
resolved fixed
9ad4904
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-02-28T00:36:50Z
2013-02-20T03:13:20Z
java/org/apache/catalina/loader/WebappLoader.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.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.io.FileOutputStream; import java.io.FilePermission; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLDecoder; import java.util.ArrayList; import java.util.jar.JarFile; import javax.management.ObjectName; import javax.servlet.ServletContext; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Loader; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.modeler.Registry; import org.apache.tomcat.util.res.StringManager; /** * Classloader implementation which is specialized for handling web * applications in the most efficient way, while being Catalina aware (all * accesses to resources are made through the DirContext interface). * This class loader supports detection of modified * Java classes, which can be used to implement auto-reload support. * <p> * This class loader is configured by adding the pathnames of directories, * JAR files, and ZIP files with the <code>addRepository()</code> method, * prior to calling <code>start()</code>. When a new class is required, * these repositories will be consulted first to locate the class. If it * is not present, the system class loader will be used instead. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class WebappLoader extends LifecycleMBeanBase implements Loader, PropertyChangeListener { // ----------------------------------------------------------- Constructors /** * Construct a new WebappLoader with no defined parent class loader * (so that the actual parent will be the system class loader). */ public WebappLoader() { this(null); } /** * Construct a new WebappLoader with the specified class loader * to be defined as the parent of the ClassLoader we ultimately create. * * @param parent The parent class loader */ public WebappLoader(ClassLoader parent) { super(); this.parentClassLoader = parent; } // ----------------------------------------------------- Instance Variables /** * The class loader being managed by this Loader component. */ private WebappClassLoader classLoader = null; /** * The Context with which this Loader has been associated. */ private Context context = null; /** * The "follow standard delegation model" flag that will be used to * configure our ClassLoader. */ private boolean delegate = false; /** * The Java class name of the ClassLoader implementation to be used. * This class should extend WebappClassLoader, otherwise, a different * loader implementation must be used. */ private String loaderClass = "org.apache.catalina.loader.WebappClassLoader"; /** * The parent class loader of the class loader we will create. */ private ClassLoader parentClassLoader = null; /** * The reloadable flag for this Loader. */ private boolean reloadable = false; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The property change support for this component. */ protected final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * Classpath set in the loader. */ private String classpath = null; /** * Repositories that are set in the loader, for JMX. */ private ArrayList<String> loaderRepositories = null; // ------------------------------------------------------------- Properties /** * Return the Java class loader to be used by this Container. */ @Override public ClassLoader getClassLoader() { return classLoader; } @Override public Context getContext() { return context; } @Override public void setContext(Context context) { if (this.context == context) { return; } if (getState().isAvailable()) { throw new IllegalStateException( sm.getString("webappLoader.setContext.ise")); } // Deregister from the old Context (if any) if (this.context != null) { this.context.removePropertyChangeListener(this); } // Process this property change Context oldContext = this.context; this.context = context; support.firePropertyChange("context", oldContext, this.context); // Register with the new Container (if any) if (this.context != null) { setReloadable(this.context.getReloadable()); this.context.addPropertyChangeListener(this); } } /** * Return the "follow standard delegation model" flag used to configure * our ClassLoader. */ @Override public boolean getDelegate() { return (this.delegate); } /** * Set the "follow standard delegation model" flag used to configure * our ClassLoader. * * @param delegate The new flag */ @Override public void setDelegate(boolean delegate) { boolean oldDelegate = this.delegate; this.delegate = delegate; support.firePropertyChange("delegate", Boolean.valueOf(oldDelegate), Boolean.valueOf(this.delegate)); } /** * Return the ClassLoader class name. */ public String getLoaderClass() { return (this.loaderClass); } /** * Set the ClassLoader class name. * * @param loaderClass The new ClassLoader class name */ public void setLoaderClass(String loaderClass) { this.loaderClass = loaderClass; } /** * Return the reloadable flag for this Loader. */ @Override public boolean getReloadable() { return (this.reloadable); } /** * Set the reloadable flag for this Loader. * * @param reloadable The new reloadable flag */ @Override public void setReloadable(boolean reloadable) { // Process this property change boolean oldReloadable = this.reloadable; this.reloadable = reloadable; support.firePropertyChange("reloadable", Boolean.valueOf(oldReloadable), Boolean.valueOf(this.reloadable)); } // --------------------------------------------------------- Public Methods /** * Add a property change listener to this component. * * @param listener The listener to add */ @Override public void addPropertyChangeListener(PropertyChangeListener listener) { support.addPropertyChangeListener(listener); } /** * 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 void backgroundProcess() { if (reloadable && modified()) { try { Thread.currentThread().setContextClassLoader (WebappLoader.class.getClassLoader()); if (context != null) { context.reload(); } } finally { if (context != null && context.getLoader() != null) { Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } } } else { closeJARs(false); } } public String[] getLoaderRepositories() { if( loaderRepositories==null ) return null; String res[]=new String[ loaderRepositories.size()]; loaderRepositories.toArray(res); return res; } public String getLoaderRepositoriesString() { String repositories[]=getLoaderRepositories(); StringBuilder sb=new StringBuilder(); for( int i=0; i<repositories.length ; i++ ) { sb.append( repositories[i]).append(":"); } return sb.toString(); } /** * Classpath, as set in org.apache.catalina.jsp_classpath context * property * * @return The classpath */ public String getClasspath() { return classpath; } /** * Has the internal repository associated with this Loader been modified, * such that the loaded classes should be reloaded? */ @Override public boolean modified() { return classLoader != null ? classLoader.modified() : false ; } /** * Used to periodically signal to the classloader to release JAR resources. */ public void closeJARs(boolean force) { if (classLoader !=null) { classLoader.closeJARs(force); } } /** * Remove a property change listener from this component. * * @param listener The listener to remove */ @Override public void removePropertyChangeListener(PropertyChangeListener listener) { support.removePropertyChangeListener(listener); } /** * Return a String representation of this component. */ @Override public String toString() { StringBuilder sb = new StringBuilder("WebappLoader["); if (context != null) sb.append(context.getName()); sb.append("]"); return (sb.toString()); } /** * Start associated {@link ClassLoader} 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.isDebugEnabled()) log.debug(sm.getString("webappLoader.starting")); if (context.getResources() == null) { log.info("No resources for " + context); setState(LifecycleState.STARTING); return; } // Construct a class loader based on our current repositories list try { classLoader = createClassLoader(); classLoader.setResources(context.getResources()); classLoader.setDelegate(this.delegate); // Configure our repositories setRepositories(); setClassPath(); setPermissions(); ((Lifecycle) classLoader).start(); String contextName = context.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(context.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + context.getParent().getName()); Registry.getRegistry(null, null) .registerComponent(classLoader, cloname, null); } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); log.error( "LifecycleException ", t ); throw new LifecycleException("start: ", t); } setState(LifecycleState.STARTING); } /** * Stop associated {@link ClassLoader} 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 void stopInternal() throws LifecycleException { if (log.isDebugEnabled()) log.debug(sm.getString("webappLoader.stopping")); setState(LifecycleState.STOPPING); // Remove context attributes as appropriate ServletContext servletContext = context.getServletContext(); servletContext.removeAttribute(Globals.CLASS_PATH_ATTR); // Throw away our current class loader if (classLoader != null) { ((Lifecycle) classLoader).stop(); } try { String contextName = context.getName(); if (!contextName.startsWith("/")) { contextName = "/" + contextName; } ObjectName cloname = new ObjectName(context.getDomain() + ":type=WebappClassLoader,context=" + contextName + ",host=" + context.getParent().getName()); Registry.getRegistry(null, null).unregisterComponent(cloname); } catch (Exception e) { log.error("LifecycleException ", e); } classLoader = null; } // ----------------------------------------- PropertyChangeListener Methods /** * Process property change events from our associated Context. * * @param event The property change event that has occurred */ @Override public void propertyChange(PropertyChangeEvent event) { // Validate the source of this event if (!(event.getSource() instanceof Context)) return; // Process a relevant property change if (event.getPropertyName().equals("reloadable")) { try { setReloadable ( ((Boolean) event.getNewValue()).booleanValue() ); } catch (NumberFormatException e) { log.error(sm.getString("webappLoader.reloadable", event.getNewValue().toString())); } } } // ------------------------------------------------------- Private Methods /** * Create associated classLoader. */ private WebappClassLoader createClassLoader() throws Exception { Class<?> clazz = Class.forName(loaderClass); WebappClassLoader classLoader = null; if (parentClassLoader == null) { parentClassLoader = context.getParentClassLoader(); } Class<?>[] argTypes = { ClassLoader.class }; Object[] args = { parentClassLoader }; Constructor<?> constr = clazz.getConstructor(argTypes); classLoader = (WebappClassLoader) constr.newInstance(args); return classLoader; } /** * Configure associated class loader permissions. */ private void setPermissions() { if (!Globals.IS_SECURITY_ENABLED) return; if (context == null) return; // Tell the class loader the root of the context ServletContext servletContext = context.getServletContext(); // Assigning permissions for the work directory File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir != null) { try { String workDirPath = workDir.getCanonicalPath(); classLoader.addPermission (new FilePermission(workDirPath, "read,write")); classLoader.addPermission (new FilePermission(workDirPath + File.separator + "-", "read,write,delete")); } catch (IOException e) { // Ignore } } try { URL rootURL = servletContext.getResource("/"); classLoader.addPermission(rootURL); String contextRoot = servletContext.getRealPath("/"); if (contextRoot != null) { try { contextRoot = (new File(contextRoot)).getCanonicalPath(); classLoader.addPermission(contextRoot); } catch (IOException e) { // Ignore } } URL classesURL = servletContext.getResource("/WEB-INF/classes/"); classLoader.addPermission(classesURL); URL libURL = servletContext.getResource("/WEB-INF/lib/"); classLoader.addPermission(libURL); if (contextRoot != null) { if (libURL != null) { File rootDir = new File(contextRoot); File libDir = new File(rootDir, "WEB-INF/lib/"); try { String path = libDir.getCanonicalPath(); classLoader.addPermission(path); } catch (IOException e) { // Ignore } } } else { if (workDir != null) { if (libURL != null) { File libDir = new File(workDir, "WEB-INF/lib/"); try { String path = libDir.getCanonicalPath(); classLoader.addPermission(path); } catch (IOException e) { // Ignore } } if (classesURL != null) { File classesDir = new File(workDir, "WEB-INF/classes/"); try { String path = classesDir.getCanonicalPath(); classLoader.addPermission(path); } catch (IOException e) { // Ignore } } } } } catch (MalformedURLException e) { // Ignore } } /** * Configure the repositories for our class loader, based on the * associated Context. * @throws IOException */ private void setRepositories() throws IOException { if (context == null) return; ServletContext servletContext = context.getServletContext(); if (servletContext == null) return; loaderRepositories=new ArrayList<>(); // Loading the work directory File workDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR); if (workDir == null) { log.info("No work dir for " + servletContext); } if( log.isDebugEnabled() && workDir != null) log.debug(sm.getString("webappLoader.deploy", workDir.getAbsolutePath())); classLoader.setWorkDir(workDir); WebResourceRoot resources = context.getResources(); // Setting up the class repository (/WEB-INF/classes), if it exists String classesPath = "/WEB-INF/classes"; WebResource classes = resources.getResource(classesPath); if (classes.isDirectory()) { File classRepository = null; String absoluteClassesPath = classes.getCanonicalPath(); if (absoluteClassesPath != null) { classRepository = new File(absoluteClassesPath); } else { classRepository = new File(workDir, classesPath); if (!classRepository.mkdirs() && !classRepository.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } if (!copyDir(classes, classRepository)) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } if(log.isDebugEnabled()) log.debug(sm.getString("webappLoader.classDeploy", classesPath, classRepository.getAbsolutePath())); // Adding the repository to the class loader classLoader.setRepository(classesPath + "/", classRepository); loaderRepositories.add(classesPath + "/" ); } // Setting up the JAR repository (/WEB-INF/lib), if it exists String libPath = "/WEB-INF/lib"; classLoader.setJarPath(libPath); WebResource libDir = resources.getResource(libPath); if (libDir.isDirectory()) { boolean copyJars = false; String absoluteLibPath = libDir.getCanonicalPath(); File destDir = null; if (absoluteLibPath != null) { destDir = new File(absoluteLibPath); } else { copyJars = true; destDir = new File(workDir, libPath); if (!destDir.mkdirs() && !destDir.isDirectory()) { throw new IOException( sm.getString("webappLoader.mkdirFailure")); } } WebResource[] jars = resources.listResources(libPath); for (WebResource jar : jars) { String jarName = jar.getName(); if (!jarName.endsWith(".jar")) continue; String filename = libPath + "/" + jarName; // Copy JAR in the work directory, always (the JAR file // would get locked otherwise, which would make it // impossible to update it or remove it at runtime) File destFile = new File(destDir, jarName); if (log.isDebugEnabled()) { log.debug(sm.getString("webappLoader.jarDeploy", filename, destFile.getAbsolutePath())); } // Bug 45403 - Check that the resource is readable if (!jar.canRead()) { IOException ioe = new IOException(sm.getString( "webappLoader.readFailure", filename)); throw ioe; } if (copyJars) { if (!copy(jar.getInputStream(),destFile)) { throw new IOException( sm.getString("webappLoader.copyFailure")); } } try { JarFile jarFile = new JarFile(destFile); classLoader.addJar(filename, jarFile, destFile); } catch (Exception ex) { // Catch the exception if there is an empty jar file // Should ignore and continue loading other jar files // in the dir } loaderRepositories.add( filename ); } } } /** * Set the appropriate context attribute for our class path. This * is required only because Jasper depends on it. */ private void setClassPath() { // Validate our current state information if (context == null) return; ServletContext servletContext = context.getServletContext(); if (servletContext == null) return; StringBuilder classpath = new StringBuilder(); // Assemble the class path information from our class loader chain ClassLoader loader = getClassLoader(); while (loader != null) { if (!buildClassPath(servletContext, classpath, loader)) { break; } loader = loader.getParent(); } this.classpath=classpath.toString(); // Store the assembled class path as a servlet context attribute servletContext.setAttribute(Globals.CLASS_PATH_ATTR, classpath.toString()); } private boolean buildClassPath(ServletContext servletContext, StringBuilder classpath, ClassLoader loader) { if (loader instanceof URLClassLoader) { URL repositories[] = ((URLClassLoader) loader).getURLs(); for (int i = 0; i < repositories.length; i++) { String repository = repositories[i].toString(); if (repository.startsWith("file://")) repository = utf8Decode(repository.substring(7)); else if (repository.startsWith("file:")) repository = utf8Decode(repository.substring(5)); else if (repository.startsWith("jndi:")) repository = servletContext.getRealPath(repository.substring(5)); else continue; if (repository == null) continue; if (classpath.length() > 0) classpath.append(File.pathSeparator); classpath.append(repository); } } else { String cp = getClasspath(loader); if (cp == null) { log.info( "Unknown loader " + loader + " " + loader.getClass()); } else { if (classpath.length() > 0) classpath.append(File.pathSeparator); classpath.append(cp); } return false; } return true; } private String utf8Decode(String input) { String result = null; try { result = URLDecoder.decode(input, "UTF-8"); } catch (UnsupportedEncodingException uee) { // Impossible. All JVMs are required to support UTF-8. } return result; } // try to extract the classpath from a loader that is not URLClassLoader private String getClasspath( ClassLoader loader ) { try { Method m=loader.getClass().getMethod("getClasspath", new Class[] {}); if( log.isTraceEnabled()) log.trace("getClasspath " + m ); if( m==null ) return null; Object o=m.invoke( loader, new Object[] {} ); if( log.isDebugEnabled() ) log.debug("gotClasspath " + o); if( o instanceof String ) return (String)o; return null; } catch( Exception ex ) { Throwable t = ExceptionUtils.unwrapInvocationTargetException(ex); ExceptionUtils.handleThrowable(t); if (log.isDebugEnabled()) log.debug("getClasspath ", ex); } return null; } /** * Copy directory. */ private boolean copyDir(WebResource src, File destDir) { WebResource[] resources = src.getWebResourceRoot().listResources(src.getWebappPath()); for (WebResource resource : resources) { File currentFile = new File(destDir, resource.getName()); if (resource.isFile()) { InputStream is = resource.getInputStream(); if (!copy(is, currentFile)) return false; } else if (resource.isDirectory()) { if (!currentFile.isDirectory() && !currentFile.mkdir()) return false; if (!copyDir(resource, currentFile)) return false; } } return true; } /** * Copy a file to the specified temp directory. This is required only * because Jasper depends on it. */ private boolean copy(InputStream is, File file) { try (FileOutputStream os = new FileOutputStream(file)){ byte[] buf = new byte[4096]; while (true) { int len = is.read(buf); if (len < 0) break; os.write(buf, 0, len); } } catch (IOException e) { return false; } finally { try { is.close(); } catch (IOException e) { // Ignore } } return true; } private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog( WebappLoader.class ); @Override protected String getDomainInternal() { return context.getDomain(); } @Override protected String getObjectNameKeyProperties() { StringBuilder name = new StringBuilder("type=Loader"); name.append(",context="); String contextName = context.getName(); if (!contextName.startsWith("/")) { name.append("/"); } name.append(contextName); name.append(",host="); name.append(context.getParent().getName()); return name.toString(); } }
54,638
Bug 54638 /manager/status?XML=true
Hi all, in /manager/status?XML=true, informations about memory pools are incorrect. for every row all the values (initial,committed,maximum,used) are the same: Memory Pools Name:Eden Space Type:Heap memory Initial:143130624 Committed:143130624 Maximum:143130624 Used:143130624 Name:Survivor Space Type:Heap memory Initial:17891328 Committed:17891328 Maximum:17891328 Used:17891328 Name:Tenured Gen Type:Heap memory Initial:357957632 Committed:357957632 Maximum:357957632 Used:357957632 Name:Code Cache Type:Non-heap memory Initial:163840 Committed:8421376 Maximum:33554432 Used:163840 Name:Perm Gen Type:Non-heap memory Initial:12582912 Committed:23330816 Maximum:67108864 Used:12582912 Name:Perm Gen [shared-ro] Type:Non-heap memory Initial:10485760 Committed:10485760 Maximum:10485760 Used:10485760 Name:Perm Gen [shared-rw] Type:Non-heap memory Initial:12582912 Committed:12582912 Maximum:12582912 Used:12582912 Instead in the gui page values are correct.
resolved fixed
78b3c10
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-06T00:40:04Z
2013-03-05T16:13:20Z
java/org/apache/catalina/manager/StatusTransformer.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.manager; import java.io.PrintWriter; import java.lang.management.ManagementFactory; import java.lang.management.MemoryPoolMXBean; import java.lang.management.MemoryUsage; import java.lang.reflect.Method; import java.text.MessageFormat; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import java.util.Vector; import javax.management.MBeanServer; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.util.RequestUtil; import org.apache.tomcat.util.ExceptionUtils; /** * This is a refactoring of the servlet to externalize * the output into a simple class. Although we could * use XSLT, that is unnecessarily complex. * * @author Peter Lin * @version $Id$ */ public class StatusTransformer { // --------------------------------------------------------- Public Methods public static void setContentType(HttpServletResponse response, int mode) { if (mode == 0){ response.setContentType("text/html;charset="+Constants.CHARSET); } else if (mode == 1){ response.setContentType("text/xml;charset="+Constants.CHARSET); } } /** * Write an HTML or XML header. * * @param writer the PrintWriter to use * @param args Path prefix for URLs * @param mode - 0 = HTML header, 1 = XML declaration * */ public static void writeHeader(PrintWriter writer, Object[] args, int mode) { if (mode == 0){ // HTML Header Section writer.print(Constants.HTML_HEADER_SECTION); } else if (mode == 1){ writer.write(Constants.XML_DECLARATION); writer.print(MessageFormat.format (Constants.XML_STYLE, args)); writer.write("<status>"); } } /** * Write the header body. XML output doesn't bother * to output this stuff, since it's just title. * * @param writer The output writer * @param args What to write * @param mode 0 means write */ public static void writeBody(PrintWriter writer, Object[] args, int mode) { if (mode == 0){ writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); } } /** * Write the manager webapp information. * * @param writer The output writer * @param args What to write * @param mode 0 means write */ public static void writeManager(PrintWriter writer, Object[] args, int mode) { if (mode == 0){ writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); } } public static void writePageHeading(PrintWriter writer, Object[] args, int mode) { if (mode == 0){ writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); } } public static void writeServerInfo(PrintWriter writer, Object[] args, int mode){ if (mode == 0){ writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); } } /** * */ public static void writeFooter(PrintWriter writer, int mode) { if (mode == 0){ // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); } else if (mode == 1){ writer.write("</status>"); } } /** * Write the OS state. Mode 0 will generate HTML. * Mode 1 will generate XML. */ public static void writeOSState(PrintWriter writer, int mode) { long[] result = new long[16]; boolean ok = false; try { String methodName = "info"; Class<?> paramTypes[] = new Class[1]; paramTypes[0] = result.getClass(); Object paramValues[] = new Object[1]; paramValues[0] = result; Method method = Class.forName("org.apache.tomcat.jni.OS") .getMethod(methodName, paramTypes); method.invoke(null, paramValues); ok = true; } catch (Throwable t) { t = ExceptionUtils.unwrapInvocationTargetException(t); ExceptionUtils.handleThrowable(t); } if (ok) { if (mode == 0){ writer.print("<h1>OS</h1>"); writer.print("<p>"); writer.print(" Physical memory: "); writer.print(formatSize(Long.valueOf(result[0]), true)); writer.print(" Available memory: "); writer.print(formatSize(Long.valueOf(result[1]), true)); writer.print(" Total page file: "); writer.print(formatSize(Long.valueOf(result[2]), true)); writer.print(" Free page file: "); writer.print(formatSize(Long.valueOf(result[3]), true)); writer.print(" Memory load: "); writer.print(Long.valueOf(result[6])); writer.print("<br>"); writer.print(" Process kernel time: "); writer.print(formatTime(Long.valueOf(result[11] / 1000), true)); writer.print(" Process user time: "); writer.print(formatTime(Long.valueOf(result[12] / 1000), true)); writer.print("</p>"); } else if (mode == 1){ // NO-OP } } } /** * Write the VM state. Mode 0 will generate HTML. * Mode 1 will generate XML. */ public static void writeVMState(PrintWriter writer, int mode) throws Exception { SortedMap<String, MemoryPoolMXBean> memoryPoolMBeans = new TreeMap<>(); for (MemoryPoolMXBean mbean: ManagementFactory.getMemoryPoolMXBeans()) { String sortKey = mbean.getType() + ":" + mbean.getName(); memoryPoolMBeans.put(sortKey, mbean); } if (mode == 0){ writer.print("<h1>JVM</h1>"); writer.print("<p>"); writer.print(" Free memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().freeMemory()), true)); writer.print(" Total memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().totalMemory()), true)); writer.print(" Max memory: "); writer.print(formatSize( Long.valueOf(Runtime.getRuntime().maxMemory()), true)); writer.print("</p>"); writer.write("<table border=\"0\"><thead><tr><th>Memory Pool</th><th>Type</th><th>Initial</th><th>Total</th><th>Maximum</th><th>Used</th></tr></thead><tbody>"); for (MemoryPoolMXBean memoryPoolMBean : memoryPoolMBeans.values()) { MemoryUsage usage = memoryPoolMBean.getUsage(); writer.write("<tr><td>"); writer.print(memoryPoolMBean.getName()); writer.write("</td><td>"); writer.print(memoryPoolMBean.getType()); writer.write("</td><td>"); writer.print(formatSize(Long.valueOf(usage.getInit()), true)); writer.write("</td><td>"); writer.print(formatSize(Long.valueOf(usage.getCommitted()), true)); writer.write("</td><td>"); writer.print(formatSize(Long.valueOf(usage.getMax()), true)); writer.write("</td><td>"); writer.print(formatSize(Long.valueOf(usage.getUsed()), true)); if (usage.getMax() > 0) { writer.write(" (" + (usage.getUsed() * 100 / usage.getMax()) + "%)"); } writer.write("</td></tr>"); } writer.write("</tbody></table>"); } else if (mode == 1){ writer.write("<jvm>"); writer.write("<memory"); writer.write(" free='" + Runtime.getRuntime().freeMemory() + "'"); writer.write(" total='" + Runtime.getRuntime().totalMemory() + "'"); writer.write(" max='" + Runtime.getRuntime().maxMemory() + "'/>"); for (MemoryPoolMXBean memoryPoolMBean : memoryPoolMBeans.values()) { MemoryUsage usage = memoryPoolMBean.getUsage(); writer.write("<memorypool"); writer.write(" name='" + memoryPoolMBean.getName() + "'"); writer.write(" type='" + memoryPoolMBean.getType() + "'"); writer.write(" usageInit='" + usage.getInit() + "'"); writer.write(" usageCommitted='" + usage.getCommitted() + "'"); writer.write(" usageMax='" + usage.getMax() + "'"); writer.write(" usageUsed='" + usage.getInit() + "'/>"); } writer.write("</jvm>"); } } /** * Write connector state. */ public static void writeConnectorState(PrintWriter writer, ObjectName tpName, String name, MBeanServer mBeanServer, Vector<ObjectName> globalRequestProcessors, Vector<ObjectName> requestProcessors, int mode) throws Exception { if (mode == 0) { writer.print("<h1>"); writer.print(name); writer.print("</h1>"); writer.print("<p>"); writer.print(" Max threads: "); writer.print(mBeanServer.getAttribute(tpName, "maxThreads")); writer.print(" Current thread count: "); writer.print(mBeanServer.getAttribute(tpName, "currentThreadCount")); writer.print(" Current thread busy: "); writer.print(mBeanServer.getAttribute(tpName, "currentThreadsBusy")); try { Object value = mBeanServer.getAttribute(tpName, "keepAliveCount"); writer.print(" Keeped alive sockets count: "); writer.print(value); } catch (Exception e) { // Ignore } writer.print("<br>"); ObjectName grpName = null; Enumeration<ObjectName> enumeration = globalRequestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("name"))) { grpName = objectName; } } if (grpName == null) { return; } writer.print(" Max processing time: "); writer.print(formatTime(mBeanServer.getAttribute (grpName, "maxTime"), false)); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (grpName, "processingTime"), true)); writer.print(" Request count: "); writer.print(mBeanServer.getAttribute(grpName, "requestCount")); writer.print(" Error count: "); writer.print(mBeanServer.getAttribute(grpName, "errorCount")); writer.print(" Bytes received: "); writer.print(formatSize(mBeanServer.getAttribute (grpName, "bytesReceived"), true)); writer.print(" Bytes sent: "); writer.print(formatSize(mBeanServer.getAttribute (grpName, "bytesSent"), true)); writer.print("</p>"); writer.print("<table border=\"0\"><tr><th>Stage</th><th>Time</th><th>B Sent</th><th>B Recv</th><th>Client</th><th>VHost</th><th>Request</th></tr>"); enumeration = requestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("worker"))) { writer.print("<tr>"); writeProcessorState(writer, objectName, mBeanServer, mode); writer.print("</tr>"); } } writer.print("</table>"); writer.print("<p>"); writer.print("P: Parse and prepare request S: Service F: Finishing R: Ready K: Keepalive"); writer.print("</p>"); } else if (mode == 1){ writer.write("<connector name='" + name + "'>"); writer.write("<threadInfo "); writer.write(" maxThreads=\"" + mBeanServer.getAttribute(tpName, "maxThreads") + "\""); writer.write(" currentThreadCount=\"" + mBeanServer.getAttribute(tpName, "currentThreadCount") + "\""); writer.write(" currentThreadsBusy=\"" + mBeanServer.getAttribute(tpName, "currentThreadsBusy") + "\""); writer.write(" />"); ObjectName grpName = null; Enumeration<ObjectName> enumeration = globalRequestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("name"))) { grpName = objectName; } } if (grpName != null) { writer.write("<requestInfo "); writer.write(" maxTime=\"" + mBeanServer.getAttribute(grpName, "maxTime") + "\""); writer.write(" processingTime=\"" + mBeanServer.getAttribute(grpName, "processingTime") + "\""); writer.write(" requestCount=\"" + mBeanServer.getAttribute(grpName, "requestCount") + "\""); writer.write(" errorCount=\"" + mBeanServer.getAttribute(grpName, "errorCount") + "\""); writer.write(" bytesReceived=\"" + mBeanServer.getAttribute(grpName, "bytesReceived") + "\""); writer.write(" bytesSent=\"" + mBeanServer.getAttribute(grpName, "bytesSent") + "\""); writer.write(" />"); writer.write("<workers>"); enumeration = requestProcessors.elements(); while (enumeration.hasMoreElements()) { ObjectName objectName = enumeration.nextElement(); if (name.equals(objectName.getKeyProperty("worker"))) { writeProcessorState(writer, objectName, mBeanServer, mode); } } writer.write("</workers>"); } writer.write("</connector>"); } } /** * Write processor state. */ protected static void writeProcessorState(PrintWriter writer, ObjectName pName, MBeanServer mBeanServer, int mode) throws Exception { Integer stageValue = (Integer) mBeanServer.getAttribute(pName, "stage"); int stage = stageValue.intValue(); boolean fullStatus = true; boolean showRequest = true; String stageStr = null; switch (stage) { case (1/*org.apache.coyote.Constants.STAGE_PARSE*/): stageStr = "P"; fullStatus = false; break; case (2/*org.apache.coyote.Constants.STAGE_PREPARE*/): stageStr = "P"; fullStatus = false; break; case (3/*org.apache.coyote.Constants.STAGE_SERVICE*/): stageStr = "S"; break; case (4/*org.apache.coyote.Constants.STAGE_ENDINPUT*/): stageStr = "F"; break; case (5/*org.apache.coyote.Constants.STAGE_ENDOUTPUT*/): stageStr = "F"; break; case (7/*org.apache.coyote.Constants.STAGE_ENDED*/): stageStr = "R"; fullStatus = false; break; case (6/*org.apache.coyote.Constants.STAGE_KEEPALIVE*/): stageStr = "K"; fullStatus = true; showRequest = false; break; case (0/*org.apache.coyote.Constants.STAGE_NEW*/): stageStr = "R"; fullStatus = false; break; default: // Unknown stage stageStr = "?"; fullStatus = false; } if (mode == 0) { writer.write("<td><strong>"); writer.write(stageStr); writer.write("</strong></td>"); if (fullStatus) { writer.write("<td>"); writer.print(formatTime(mBeanServer.getAttribute (pName, "requestProcessingTime"), false)); writer.write("</td>"); writer.write("<td>"); if (showRequest) { writer.print(formatSize(mBeanServer.getAttribute (pName, "requestBytesSent"), false)); } else { writer.write("?"); } writer.write("</td>"); writer.write("<td>"); if (showRequest) { writer.print(formatSize(mBeanServer.getAttribute (pName, "requestBytesReceived"), false)); } else { writer.write("?"); } writer.write("</td>"); writer.write("<td>"); writer.print(filter(mBeanServer.getAttribute (pName, "remoteAddr"))); writer.write("</td>"); writer.write("<td nowrap>"); writer.write(filter(mBeanServer.getAttribute (pName, "virtualHost"))); writer.write("</td>"); writer.write("<td nowrap>"); if (showRequest) { writer.write(filter(mBeanServer.getAttribute (pName, "method"))); writer.write(" "); writer.write(filter(mBeanServer.getAttribute (pName, "currentUri"))); String queryString = (String) mBeanServer.getAttribute (pName, "currentQueryString"); if ((queryString != null) && (!queryString.equals(""))) { writer.write("?"); writer.print(RequestUtil.filter(queryString)); } writer.write(" "); writer.write(filter(mBeanServer.getAttribute (pName, "protocol"))); } else { writer.write("?"); } writer.write("</td>"); } else { writer.write("<td>?</td><td>?</td><td>?</td><td>?</td><td>?</td><td>?</td>"); } } else if (mode == 1){ writer.write("<worker "); writer.write(" stage=\"" + stageStr + "\""); if (fullStatus) { writer.write(" requestProcessingTime=\"" + mBeanServer.getAttribute (pName, "requestProcessingTime") + "\""); writer.write(" requestBytesSent=\""); if (showRequest) { writer.write("" + mBeanServer.getAttribute (pName, "requestBytesSent")); } else { writer.write("0"); } writer.write("\""); writer.write(" requestBytesReceived=\""); if (showRequest) { writer.write("" + mBeanServer.getAttribute (pName, "requestBytesReceived")); } else { writer.write("0"); } writer.write("\""); writer.write(" remoteAddr=\"" + filter(mBeanServer.getAttribute (pName, "remoteAddr")) + "\""); writer.write(" virtualHost=\"" + filter(mBeanServer.getAttribute (pName, "virtualHost")) + "\""); if (showRequest) { writer.write(" method=\"" + filter(mBeanServer.getAttribute (pName, "method")) + "\""); writer.write(" currentUri=\"" + filter(mBeanServer.getAttribute (pName, "currentUri")) + "\""); String queryString = (String) mBeanServer.getAttribute (pName, "currentQueryString"); if ((queryString != null) && (!queryString.equals(""))) { writer.write(" currentQueryString=\"" + RequestUtil.filter(queryString) + "\""); } else { writer.write(" currentQueryString=\"&#63;\""); } writer.write(" protocol=\"" + filter(mBeanServer.getAttribute (pName, "protocol")) + "\""); } else { writer.write(" method=\"&#63;\""); writer.write(" currentUri=\"&#63;\""); writer.write(" currentQueryString=\"&#63;\""); writer.write(" protocol=\"&#63;\""); } } else { writer.write(" requestProcessingTime=\"0\""); writer.write(" requestBytesSent=\"0\""); writer.write(" requestBytesReceived=\"0\""); writer.write(" remoteAddr=\"&#63;\""); writer.write(" virtualHost=\"&#63;\""); writer.write(" method=\"&#63;\""); writer.write(" currentUri=\"&#63;\""); writer.write(" currentQueryString=\"&#63;\""); writer.write(" protocol=\"&#63;\""); } writer.write(" />"); } } /** * Write applications state. */ public static void writeDetailedState(PrintWriter writer, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0){ ObjectName queryHosts = new ObjectName("*:j2eeType=WebModule,*"); Set<ObjectName> hostsON = mBeanServer.queryNames(queryHosts, null); // Navigation menu writer.print("<h1>"); writer.print("Application list"); writer.print("</h1>"); writer.print("<p>"); int count = 0; Iterator<ObjectName> iterator = hostsON.iterator(); while (iterator.hasNext()) { ObjectName contextON = iterator.next(); String webModuleName = contextON.getKeyProperty("name"); if (webModuleName.startsWith("//")) { webModuleName = webModuleName.substring(2); } int slash = webModuleName.indexOf("/"); if (slash == -1) { count++; continue; } writer.print("<a href=\"#" + (count++) + ".0\">"); writer.print(filter(webModuleName)); writer.print("</a>"); if (iterator.hasNext()) { writer.print("<br>"); } } writer.print("</p>"); // Webapp list count = 0; iterator = hostsON.iterator(); while (iterator.hasNext()) { ObjectName contextON = iterator.next(); writer.print("<a class=\"A.name\" name=\"" + (count++) + ".0\">"); writeContext(writer, contextON, mBeanServer, mode); } } else if (mode == 1){ // for now we don't write out the Detailed state in XML } } /** * Write context state. */ protected static void writeContext(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0){ String webModuleName = objectName.getKeyProperty("name"); String name = webModuleName; if (name == null) { return; } String hostName = null; String contextName = null; if (name.startsWith("//")) { name = name.substring(2); } int slash = name.indexOf("/"); if (slash != -1) { hostName = name.substring(0, slash); contextName = name.substring(slash); } else { return; } ObjectName queryManager = new ObjectName (objectName.getDomain() + ":type=Manager,context=" + contextName + ",host=" + hostName + ",*"); Set<ObjectName> managersON = mBeanServer.queryNames(queryManager, null); ObjectName managerON = null; Iterator<ObjectName> iterator2 = managersON.iterator(); while (iterator2.hasNext()) { managerON = iterator2.next(); } ObjectName queryJspMonitor = new ObjectName (objectName.getDomain() + ":type=JspMonitor,WebModule=" + webModuleName + ",*"); Set<ObjectName> jspMonitorONs = mBeanServer.queryNames(queryJspMonitor, null); // Special case for the root context if (contextName.equals("/")) { contextName = ""; } writer.print("<h1>"); writer.print(filter(name)); writer.print("</h1>"); writer.print("</a>"); writer.print("<p>"); Object startTime = mBeanServer.getAttribute(objectName, "startTime"); writer.print(" Start time: " + new Date(((Long) startTime).longValue())); writer.print(" Startup time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "startupTime"), false)); writer.print(" TLD scan time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "tldScanTime"), false)); if (managerON != null) { writeManager(writer, managerON, mBeanServer, mode); } if (jspMonitorONs != null) { writeJspMonitor(writer, jspMonitorONs, mBeanServer, mode); } writer.print("</p>"); String onStr = objectName.getDomain() + ":j2eeType=Servlet,WebModule=" + webModuleName + ",*"; ObjectName servletObjectName = new ObjectName(onStr); Set<ObjectInstance> set = mBeanServer.queryMBeans(servletObjectName, null); Iterator<ObjectInstance> iterator = set.iterator(); while (iterator.hasNext()) { ObjectInstance oi = iterator.next(); writeWrapper(writer, oi.getObjectName(), mBeanServer, mode); } } else if (mode == 1){ // for now we don't write out the context in XML } } /** * Write detailed information about a manager. */ public static void writeManager(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0) { writer.print("<br>"); writer.print(" Active sessions: "); writer.print(mBeanServer.getAttribute (objectName, "activeSessions")); writer.print(" Session count: "); writer.print(mBeanServer.getAttribute (objectName, "sessionCounter")); writer.print(" Max active sessions: "); writer.print(mBeanServer.getAttribute(objectName, "maxActive")); writer.print(" Rejected session creations: "); writer.print(mBeanServer.getAttribute (objectName, "rejectedSessions")); writer.print(" Expired sessions: "); writer.print(mBeanServer.getAttribute (objectName, "expiredSessions")); writer.print(" Longest session alive time: "); writer.print(formatSeconds(mBeanServer.getAttribute( objectName, "sessionMaxAliveTime"))); writer.print(" Average session alive time: "); writer.print(formatSeconds(mBeanServer.getAttribute( objectName, "sessionAverageAliveTime"))); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "processingTime"), false)); } else if (mode == 1) { // for now we don't write out the wrapper details } } /** * Write JSP monitoring information. */ public static void writeJspMonitor(PrintWriter writer, Set<ObjectName> jspMonitorONs, MBeanServer mBeanServer, int mode) throws Exception { int jspCount = 0; int jspReloadCount = 0; Iterator<ObjectName> iter = jspMonitorONs.iterator(); while (iter.hasNext()) { ObjectName jspMonitorON = iter.next(); Object obj = mBeanServer.getAttribute(jspMonitorON, "jspCount"); jspCount += ((Integer) obj).intValue(); obj = mBeanServer.getAttribute(jspMonitorON, "jspReloadCount"); jspReloadCount += ((Integer) obj).intValue(); } if (mode == 0) { writer.print("<br>"); writer.print(" JSPs loaded: "); writer.print(jspCount); writer.print(" JSPs reloaded: "); writer.print(jspReloadCount); } else if (mode == 1) { // for now we don't write out anything } } /** * Write detailed information about a wrapper. */ public static void writeWrapper(PrintWriter writer, ObjectName objectName, MBeanServer mBeanServer, int mode) throws Exception { if (mode == 0) { String servletName = objectName.getKeyProperty("name"); String[] mappings = (String[]) mBeanServer.invoke(objectName, "findMappings", null, null); writer.print("<h2>"); writer.print(filter(servletName)); if ((mappings != null) && (mappings.length > 0)) { writer.print(" [ "); for (int i = 0; i < mappings.length; i++) { writer.print(filter(mappings[i])); if (i < mappings.length - 1) { writer.print(" , "); } } writer.print(" ] "); } writer.print("</h2>"); writer.print("<p>"); writer.print(" Processing time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "processingTime"), true)); writer.print(" Max time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "maxTime"), false)); writer.print(" Request count: "); writer.print(mBeanServer.getAttribute(objectName, "requestCount")); writer.print(" Error count: "); writer.print(mBeanServer.getAttribute(objectName, "errorCount")); writer.print(" Load time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "loadTime"), false)); writer.print(" Classloading time: "); writer.print(formatTime(mBeanServer.getAttribute (objectName, "classLoadTime"), false)); writer.print("</p>"); } else if (mode == 1){ // for now we don't write out the wrapper details } } /** * Filter the specified message string for characters that are sensitive * in HTML. This avoids potential attacks caused by including JavaScript * codes in the request URL that is often reported in error messages. * * @param obj The message string to be filtered */ public static String filter(Object obj) { if (obj == null) return ("?"); String message = obj.toString(); char content[] = new char[message.length()]; message.getChars(0, message.length(), content, 0); StringBuilder result = new StringBuilder(content.length + 50); for (int i = 0; i < content.length; i++) { switch (content[i]) { case '<': result.append("&lt;"); break; case '>': result.append("&gt;"); break; case '&': result.append("&amp;"); break; case '"': result.append("&quot;"); break; default: result.append(content[i]); } } return (result.toString()); } /** * Display the given size in bytes, either as KB or MB. * * @param mb true to display megabytes, false for kilobytes */ public static String formatSize(Object obj, boolean mb) { long bytes = -1L; if (obj instanceof Long) { bytes = ((Long) obj).longValue(); } else if (obj instanceof Integer) { bytes = ((Integer) obj).intValue(); } if (mb) { StringBuilder buff = new StringBuilder(); if (bytes < 0) { buff.append('-'); bytes = -bytes; } long mbytes = bytes / (1024 * 1024); long rest = ((bytes - (mbytes * (1024 * 1024))) * 100) / (1024 * 1024); buff.append(mbytes).append('.'); if (rest < 10) { buff.append('0'); } buff.append(rest).append(" MB"); return buff.toString(); } else { return ((bytes / 1024) + " KB"); } } /** * Display the given time in ms, either as ms or s. * * @param seconds true to display seconds, false for milliseconds */ public static String formatTime(Object obj, boolean seconds) { long time = -1L; if (obj instanceof Long) { time = ((Long) obj).longValue(); } else if (obj instanceof Integer) { time = ((Integer) obj).intValue(); } if (seconds) { return ((((float) time ) / 1000) + " s"); } else { return (time + " ms"); } } /** * Formats the given time (given in seconds) as a string. * * @param obj Time object to be formatted as string * * @return String formatted time */ public static String formatSeconds(Object obj) { long time = -1L; if (obj instanceof Long) { time = ((Long) obj).longValue(); } else if (obj instanceof Integer) { time = ((Integer) obj).intValue(); } return (time + " s"); } }
54,612
Bug 54612 Fatal Error when trying to send data to WebSocket with conection closed
null
resolved fixed
1255d32
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-06T17:23:57Z
2013-02-27T10:13:20Z
java/org/apache/catalina/websocket/WsOutbound.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.websocket; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.res.StringManager; /** * Provides the means to write WebSocket messages to the client. All methods * that write to the client (or update a buffer that is later written to the * client) are synchronized to prevent multiple threads trying to write to the * client at the same time. */ public class WsOutbound { private static final StringManager sm = StringManager.getManager(Constants.Package); public static final int DEFAULT_BUFFER_SIZE = 8192; private OutputStream outputStream; private ByteBuffer bb; private CharBuffer cb; private boolean closed = false; private Boolean text = null; private boolean firstFrame = true; public WsOutbound(OutputStream outputStream) { this(outputStream, DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE); } public WsOutbound(OutputStream outputStream, int byteBufferSize, int charBufferSize) { this.outputStream = outputStream; this.bb = ByteBuffer.allocate(byteBufferSize); this.cb = CharBuffer.allocate(charBufferSize); } /** * Adds the data to the buffer for binary data. If a textual message is * currently in progress that message will be completed and a new binary * message started. If the buffer for binary data is full, the buffer will * be flushed and a new binary continuation fragment started. * * @param b The byte (only the least significant byte is used) of data to * send to the client. * * @throws IOException If a flush is required and an error occurs writing * the WebSocket frame to the client */ public synchronized void writeBinaryData(int b) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (bb.position() == bb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.FALSE; } else if (text == Boolean.TRUE) { // Flush the character data flush(); text = Boolean.FALSE; } bb.put((byte) (b & 0xFF)); } /** * Adds the data to the buffer for textual data. If a binary message is * currently in progress that message will be completed and a new textual * message started. If the buffer for textual data is full, the buffer will * be flushed and a new textual continuation fragment started. * * @param c The character to send to the client. * * @throws IOException If a flush is required and an error occurs writing * the WebSocket frame to the client */ public synchronized void writeTextData(char c) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); } /** * Flush any message (binary or textual) that may be buffered and then send * a WebSocket binary message as a single frame with the provided buffer as * the payload of the message. * * @param msgBb The buffer containing the payload * * @throws IOException If an error occurs writing to the client */ public synchronized void writeBinaryMessage(ByteBuffer msgBb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.FALSE; doWriteBytes(msgBb, true); } /** * Flush any message (binary or textual) that may be buffered and then send * a WebSocket text message as a single frame with the provided buffer as * the payload of the message. * * @param msgCb The buffer containing the payload * * @throws IOException If an error occurs writing to the client */ public synchronized void writeTextMessage(CharBuffer msgCb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.TRUE; doWriteText(msgCb, true); } /** * Flush any message (binary or textual) that may be buffered. * * @throws IOException If an error occurs writing to the client */ public synchronized void flush() throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); } private void doFlush(boolean finalFragment) throws IOException { if (text == null) { // No data return; } if (text.booleanValue()) { cb.flip(); doWriteText(cb, finalFragment); } else { bb.flip(); doWriteBytes(bb, finalFragment); } } /** * Respond to a client close by sending a close that echoes the status code * and message. * * @param frame The close frame received from a client * * @throws IOException If an error occurs writing to the client */ protected void close(WsFrame frame) throws IOException { if (frame.getPayLoadLength() > 0) { // Must be status (2 bytes) plus optional message if (frame.getPayLoadLength() == 1) { throw new IOException(); } int status = (frame.getPayLoad().get() & 0xFF) << 8; status += frame.getPayLoad().get() & 0xFF; if (validateCloseStatus(status)) { // Echo the status back to the client close(status, frame.getPayLoad()); } else { // Invalid close code close(Constants.STATUS_PROTOCOL_ERROR, null); } } else { // No status close(0, null); } } private boolean validateCloseStatus(int status) { if (status == Constants.STATUS_CLOSE_NORMAL || status == Constants.STATUS_SHUTDOWN || status == Constants.STATUS_PROTOCOL_ERROR || status == Constants.STATUS_UNEXPECTED_DATA_TYPE || status == Constants.STATUS_BAD_DATA || status == Constants.STATUS_POLICY_VIOLATION || status == Constants.STATUS_MESSAGE_TOO_LARGE || status == Constants.STATUS_REQUIRED_EXTENSION || status == Constants.STATUS_UNEXPECTED_CONDITION || (status > 2999 && status < 5000)) { // Other 1xxx reserved / not permitted // 2xxx reserved // 3xxx framework defined // 4xxx application defined return true; } // <1000 unused // >4999 undefined return false; } /** * Send a close message to the client * * @param status Must be a valid status code or zero to send no code * @param data Optional message. If message is defined, a valid status * code must be provided. * * @throws IOException If an error occurs writing to the client */ public synchronized void close(int status, ByteBuffer data) throws IOException { if (closed) { return; } closed = true; outputStream.write(0x88); if (status == 0) { outputStream.write(0); } else if (data == null || data.position() == data.limit()) { outputStream.write(2); outputStream.write(status >>> 8); outputStream.write(status); } else { outputStream.write(2 + data.limit() - data.position()); outputStream.write(status >>> 8); outputStream.write(status); outputStream.write(data.array(), data.position(), data.limit() - data.position()); } outputStream.flush(); bb = null; cb = null; outputStream = null; } /** * Send a pong message to the client * * @param data Optional message. * * @throws IOException If an error occurs writing to the client */ public synchronized void pong(ByteBuffer data) throws IOException { sendControlMessage(data, Constants.OPCODE_PONG); } /** * Send a ping message to the client * * @param data Optional message. * * @throws IOException If an error occurs writing to the client */ public synchronized void ping(ByteBuffer data) throws IOException { sendControlMessage(data, Constants.OPCODE_PING); } /** * Generic function to send either a ping or a pong. * * @param data Optional message. * @param opcode The byte to include as the opcode. * * @throws IOException If an error occurs writing to the client */ private synchronized void sendControlMessage(ByteBuffer data, byte opcode) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(false); outputStream.write(0x80 | opcode); if (data == null) { outputStream.write(0); } else { outputStream.write(data.limit() - data.position()); outputStream.write(data.array(), data.position(), data.limit() - data.position()); } outputStream.flush(); } /** * Writes the provided bytes as the payload in a new WebSocket frame. * * @param buffer The bytes to include in the payload. * @param finalFragment Do these bytes represent the final fragment of a * WebSocket message? * @throws IOException */ private void doWriteBytes(ByteBuffer buffer, boolean finalFragment) throws IOException { // Work out the first byte int first = 0x00; if (finalFragment) { first = first + 0x80; } if (firstFrame) { if (text.booleanValue()) { first = first + 0x1; } else { first = first + 0x2; } } // Continuation frame is OpCode 0 outputStream.write(first); if (buffer.limit() < 126) { outputStream.write(buffer.limit()); } else if (buffer.limit() < 65536) { outputStream.write(126); outputStream.write(buffer.limit() >>> 8); outputStream.write(buffer.limit() & 0xFF); } else { // Will never be more than 2^31-1 outputStream.write(127); outputStream.write(0); outputStream.write(0); outputStream.write(0); outputStream.write(0); outputStream.write(buffer.limit() >>> 24); outputStream.write(buffer.limit() >>> 16); outputStream.write(buffer.limit() >>> 8); outputStream.write(buffer.limit() & 0xFF); } // Write the content outputStream.write(buffer.array(), 0, buffer.limit()); outputStream.flush(); // Reset if (finalFragment) { text = null; firstFrame = true; } else { firstFrame = false; } bb.clear(); } /* * Convert the textual message to bytes and then output it. */ private void doWriteText(CharBuffer buffer, boolean finalFragment) throws IOException { CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder(); do { CoderResult cr = encoder.encode(buffer, bb, true); if (cr.isError()) { cr.throwException(); } bb.flip(); if (buffer.hasRemaining()) { doWriteBytes(bb, false); } else { doWriteBytes(bb, finalFragment); } } while (buffer.hasRemaining()); // Reset - bb will be cleared in doWriteBytes() cb.clear(); } }
54,624
Bug 54624 Form authenticator hangs on re-authentication of POST request behind mod_proxy_ajp
Setup: Tomcat AJP connector behind mod_proxy_ajp, form-based authentication. When session expires and a POST request is submitted, Tomcat shows login form, user logs in, authenticator tries to restore the original POST request. Doing that, it tries to swallow the AJP message body before replacing the body of the request with the original POST request body. It tries to read the first 4 bytes of the AJP message (the message length) and blocks forever waiting for those 4 bytes.
resolved fixed
c9e056c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-06T20:45:28Z
2013-03-01T03:53:20Z
java/org/apache/catalina/authenticator/FormAuthenticator.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.io.InputStream; import java.security.Principal; import java.util.Enumeration; import java.util.Iterator; import java.util.Locale; import javax.servlet.RequestDispatcher; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Manager; import org.apache.catalina.Realm; import org.apache.catalina.Session; import org.apache.catalina.connector.Request; import org.apache.catalina.deploy.LoginConfig; 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.ByteChunk; import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.MimeHeaders; /** * An <b>Authenticator</b> and <b>Valve</b> implementation of FORM BASED * Authentication, as described in the Servlet API Specification, Version 2.2. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class FormAuthenticator extends AuthenticatorBase { private static final Log log = LogFactory.getLog(FormAuthenticator.class); // ----------------------------------------------------- Instance Variables /** * Character encoding to use to read the username and password parameters * from the request. If not set, the encoding of the request body will be * used. */ protected String characterEncoding = null; /** * Landing page to use if a user tries to access the login page directly or * if the session times out during login. If not set, error responses will * be sent instead. */ protected String landingPage = null; // ------------------------------------------------------------- Properties /** * Return the character encoding to use to read the username and password. */ public String getCharacterEncoding() { return characterEncoding; } /** * Set the character encoding to be used to read the username and password. */ public void setCharacterEncoding(String encoding) { characterEncoding = encoding; } /** * Return the landing page to use when FORM auth is mis-used. */ public String getLandingPage() { return landingPage; } /** * Set the landing page to use when the FORM auth is mis-used. */ public void setLandingPage(String landingPage) { this.landingPage = landingPage; } // --------------------------------------------------------- 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 { // References to objects we will need later Session session = null; // 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; } } // Have we authenticated this user before but have caching disabled? if (!cache) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Checking for reauthenticate in session " + session); } String username = (String) session.getNote(Constants.SESS_USERNAME_NOTE); String password = (String) session.getNote(Constants.SESS_PASSWORD_NOTE); if ((username != null) && (password != null)) { if (log.isDebugEnabled()) { log.debug("Reauthenticating username '" + username + "'"); } principal = context.getRealm().authenticate(username, password); if (principal != null) { session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); if (!matchRequest(request)) { register(request, response, principal, HttpServletRequest.FORM_AUTH, username, password); return true; } } if (log.isDebugEnabled()) { log.debug("Reauthentication failed, proceed normally"); } } } // Is this the re-submit of the original request URI after successful // authentication? If so, forward the *original* request instead. if (matchRequest(request)) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Restore request from session '" + session.getIdInternal() + "'"); } principal = (Principal) session.getNote(Constants.FORM_PRINCIPAL_NOTE); register(request, response, principal, HttpServletRequest.FORM_AUTH, (String) session.getNote(Constants.SESS_USERNAME_NOTE), (String) session.getNote(Constants.SESS_PASSWORD_NOTE)); // If we're caching principals we no longer need the username // and password in the session, so remove them if (cache) { session.removeNote(Constants.SESS_USERNAME_NOTE); session.removeNote(Constants.SESS_PASSWORD_NOTE); } if (restoreRequest(request, session)) { if (log.isDebugEnabled()) { log.debug("Proceed to restored request"); } return true; } else { if (log.isDebugEnabled()) { log.debug("Restore of original request failed"); } response.sendError(HttpServletResponse.SC_BAD_REQUEST); return false; } } // Acquire references to objects we will need to evaluate MessageBytes uriMB = MessageBytes.newInstance(); CharChunk uriCC = uriMB.getCharChunk(); uriCC.setLimit(-1); String contextPath = request.getContextPath(); String requestURI = request.getDecodedRequestURI(); // Is this the action request from the login page? boolean loginAction = requestURI.startsWith(contextPath) && requestURI.endsWith(Constants.FORM_ACTION); LoginConfig config = context.getLoginConfig(); // No -- Save this request and redirect to the form login page if (!loginAction) { session = request.getSessionInternal(true); if (log.isDebugEnabled()) { log.debug("Save request in session '" + session.getIdInternal() + "'"); } try { saveRequest(request, session); } catch (IOException ioe) { log.debug("Request body too big to save during authentication"); response.sendError(HttpServletResponse.SC_FORBIDDEN, sm.getString("authenticator.requestBodyTooBig")); return false; } forwardToLoginPage(request, response, config); return false; } // Yes -- Acknowledge the request, validate the specified credentials // and redirect to the error page if they are not correct request.getResponse().sendAcknowledgement(); Realm realm = context.getRealm(); if (characterEncoding != null) { request.setCharacterEncoding(characterEncoding); } String username = request.getParameter(Constants.FORM_USERNAME); String password = request.getParameter(Constants.FORM_PASSWORD); if (log.isDebugEnabled()) { log.debug("Authenticating username '" + username + "'"); } principal = realm.authenticate(username, password); if (principal == null) { forwardToErrorPage(request, response, config); return false; } if (log.isDebugEnabled()) { log.debug("Authentication of '" + username + "' was successful"); } if (session == null) { session = request.getSessionInternal(false); } if (session == null) { if (containerLog.isDebugEnabled()) { containerLog.debug ("User took so long to log on the session expired"); } if (landingPage == null) { response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, sm.getString("authenticator.sessionExpired")); } else { // Make the authenticator think the user originally requested // the landing page String uri = request.getContextPath() + landingPage; SavedRequest saved = new SavedRequest(); saved.setMethod("GET"); saved.setRequestURI(uri); saved.setDecodedRequestURI(uri); request.getSessionInternal(true).setNote( Constants.FORM_REQUEST_NOTE, saved); response.sendRedirect(response.encodeRedirectURL(uri)); } return false; } // Save the authenticated Principal in our session session.setNote(Constants.FORM_PRINCIPAL_NOTE, principal); // Save the username and password as well session.setNote(Constants.SESS_USERNAME_NOTE, username); session.setNote(Constants.SESS_PASSWORD_NOTE, password); // Redirect the user to the original request URI (which will cause // the original request to be restored) requestURI = savedRequestURL(session); if (log.isDebugEnabled()) { log.debug("Redirecting to original '" + requestURI + "'"); } if (requestURI == null) { if (landingPage == null) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, sm.getString("authenticator.formlogin")); } else { // Make the authenticator think the user originally requested // the landing page String uri = request.getContextPath() + landingPage; SavedRequest saved = new SavedRequest(); saved.setMethod("GET"); saved.setRequestURI(uri); saved.setDecodedRequestURI(uri); session.setNote(Constants.FORM_REQUEST_NOTE, saved); response.sendRedirect(response.encodeRedirectURL(uri)); } } else { response.sendRedirect(response.encodeRedirectURL(requestURI)); } return false; } @Override protected String getAuthMethod() { return HttpServletRequest.FORM_AUTH; } // ------------------------------------------------------ Protected Methods /** * Called to forward to the login page * * @param request Request we are processing * @param response Response we are populating * @param config Login configuration describing how authentication * should be performed * @throws IOException If the forward to the login page fails and the call * to {@link HttpServletResponse#sendError(int, String)} * throws an {@link IOException} */ protected void forwardToLoginPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { if (log.isDebugEnabled()) { log.debug(sm.getString("formAuthenticator.forwardLogin", request.getRequestURI(), request.getMethod(), config.getLoginPage(), context.getName())); } String loginPage = config.getLoginPage(); if (loginPage == null || loginPage.length() == 0) { String msg = sm.getString("formAuthenticator.noLoginPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } if (getChangeSessionIdOnAuthentication()) { Session session = request.getSessionInternal(false); if (session != null) { Manager manager = request.getContext().getManager(); manager.changeSessionId(session); request.changeSessionId(session.getId()); } } // Always use GET for the login page, regardless of the method used String oldMethod = request.getMethod(); request.getCoyoteRequest().method().setString("GET"); RequestDispatcher disp = context.getServletContext().getRequestDispatcher(loginPage); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardLoginFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } finally { // Restore original method so that it is written into access log request.getCoyoteRequest().method().setString(oldMethod); } } /** * Called to forward to the error page * * @param request Request we are processing * @param response Response we are populating * @param config Login configuration describing how authentication * should be performed * @throws IOException If the forward to the error page fails and the call * to {@link HttpServletResponse#sendError(int, String)} * throws an {@link IOException} */ protected void forwardToErrorPage(Request request, HttpServletResponse response, LoginConfig config) throws IOException { String errorPage = config.getErrorPage(); if (errorPage == null || errorPage.length() == 0) { String msg = sm.getString("formAuthenticator.noErrorPage", context.getName()); log.warn(msg); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); return; } RequestDispatcher disp = context.getServletContext().getRequestDispatcher (config.getErrorPage()); try { if (context.fireRequestInitEvent(request)) { disp.forward(request.getRequest(), response); context.fireRequestDestroyEvent(request); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); String msg = sm.getString("formAuthenticator.forwardErrorFail"); log.warn(msg, t); request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, msg); } } /** * Does this request match the saved one (so that it must be the redirect * we signaled after successful authentication? * * @param request The request to be verified */ protected boolean matchRequest(Request request) { // Has a session been created? Session session = request.getSessionInternal(false); if (session == null) { return false; } // Is there a saved request? SavedRequest sreq = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); if (sreq == null) { return false; } // Is there a saved principal? if (session.getNote(Constants.FORM_PRINCIPAL_NOTE) == null) { return false; } // Does the request URI match? String decodedRequestURI = request.getDecodedRequestURI(); if (decodedRequestURI == null) { return false; } return decodedRequestURI.equals(sreq.getDecodedRequestURI()); } /** * Restore the original request from information stored in our session. * If the original request is no longer present (because the session * timed out), return <code>false</code>; otherwise, return * <code>true</code>. * * @param request The request to be restored * @param session The session containing the saved information */ protected boolean restoreRequest(Request request, Session session) throws IOException { // Retrieve and remove the SavedRequest object from our session SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); session.removeNote(Constants.FORM_REQUEST_NOTE); session.removeNote(Constants.FORM_PRINCIPAL_NOTE); if (saved == null) { return false; } // Modify our current request to reflect the original one request.clearCookies(); Iterator<Cookie> cookies = saved.getCookies(); while (cookies.hasNext()) { request.addCookie(cookies.next()); } String method = saved.getMethod(); MimeHeaders rmh = request.getCoyoteRequest().getMimeHeaders(); rmh.recycle(); boolean cachable = "GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method); Iterator<String> names = saved.getHeaderNames(); while (names.hasNext()) { String name = names.next(); // The browser isn't expecting this conditional response now. // Assuming that it can quietly recover from an unexpected 412. // BZ 43687 if(!("If-Modified-Since".equalsIgnoreCase(name) || (cachable && "If-None-Match".equalsIgnoreCase(name)))) { Iterator<String> values = saved.getHeaderValues(name); while (values.hasNext()) { rmh.addValue(name).setString(values.next()); } } } request.clearLocales(); Iterator<Locale> locales = saved.getLocales(); while (locales.hasNext()) { request.addLocale(locales.next()); } request.getCoyoteRequest().getParameters().recycle(); request.getCoyoteRequest().getParameters().setQueryStringEncoding( request.getConnector().getURIEncoding()); // Swallow any request body since we will be replacing it byte[] buffer = new byte[4096]; InputStream is = request.createInputStream(); while (is.read(buffer) >= 0) { // Ignore request body } ByteChunk body = saved.getBody(); if (body != null) { request.getCoyoteRequest().action (ActionCode.REQ_SET_BODY_REPLAY, body); // Set content type MessageBytes contentType = MessageBytes.newInstance(); // If no content type specified, use default for POST String savedContentType = saved.getContentType(); if (savedContentType == null && "POST".equalsIgnoreCase(method)) { savedContentType = "application/x-www-form-urlencoded"; } contentType.setString(savedContentType); request.getCoyoteRequest().setContentType(contentType); } request.getCoyoteRequest().method().setString(method); return true; } /** * Save the original request information into our session. * * @param request The request to be saved * @param session The session to contain the saved information * @throws IOException */ protected void saveRequest(Request request, Session session) throws IOException { // Create and populate a SavedRequest object for this request SavedRequest saved = new SavedRequest(); Cookie cookies[] = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { saved.addCookie(cookies[i]); } } Enumeration<String> names = request.getHeaderNames(); while (names.hasMoreElements()) { String name = names.nextElement(); Enumeration<String> values = request.getHeaders(name); while (values.hasMoreElements()) { String value = values.nextElement(); saved.addHeader(name, value); } } Enumeration<Locale> locales = request.getLocales(); while (locales.hasMoreElements()) { Locale locale = locales.nextElement(); saved.addLocale(locale); } // May need to acknowledge a 100-continue expectation request.getResponse().sendAcknowledgement(); ByteChunk body = new ByteChunk(); body.setLimit(request.getConnector().getMaxSavePostSize()); byte[] buffer = new byte[4096]; int bytesRead; InputStream is = request.getInputStream(); while ( (bytesRead = is.read(buffer) ) >= 0) { body.append(buffer, 0, bytesRead); } // Only save the request body if there is something to save if (body.getLength() > 0) { saved.setContentType(request.getContentType()); saved.setBody(body); } saved.setMethod(request.getMethod()); saved.setQueryString(request.getQueryString()); saved.setRequestURI(request.getRequestURI()); saved.setDecodedRequestURI(request.getDecodedRequestURI()); // Stash the SavedRequest in our session for later use session.setNote(Constants.FORM_REQUEST_NOTE, saved); } /** * Return the request URI (with the corresponding query string, if any) * from the saved request so that we can redirect to it. * * @param session Our current session */ protected String savedRequestURL(Session session) { SavedRequest saved = (SavedRequest) session.getNote(Constants.FORM_REQUEST_NOTE); if (saved == null) { return (null); } StringBuilder sb = new StringBuilder(saved.getRequestURI()); if (saved.getQueryString() != null) { sb.append('?'); sb.append(saved.getQueryString()); } return (sb.toString()); } }
54,628
Bug 54628 there is something wrong when send binary data by websocket.
there is something wrong when send binary data by websocket. see org.apache.catalina.websocket.WsOutbound.doWriteBytes(ByteBuffer, boolean) I think // Write the content upgradeOutbound.write(buffer.array(), 0, buffer.limit()); upgradeOutbound.flush(); should change to : // Write the content upgradeOutbound.write(buffer.array(), buffer.arrayOffset(), buffer.limit()); upgradeOutbound.flush(); For example: byte[] bts = new byte[]{1,2,3,4,5} ByteBuffer bf = ByteBuffer.wrap(bts, 2, 2); out.writeBinaryMessage(bf); I mean write [3,4] to the client, but in fact [1,2,3,4] be sent;
resolved fixed
e1d16fd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-06T20:52:19Z
2013-03-02T13:13:20Z
java/org/apache/catalina/websocket/WsOutbound.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.websocket; import java.io.IOException; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.res.StringManager; /** * Provides the means to write WebSocket messages to the client. All methods * that write to the client (or update a buffer that is later written to the * client) are synchronized to prevent multiple threads trying to write to the * client at the same time. */ public class WsOutbound { private static final StringManager sm = StringManager.getManager(Constants.Package); public static final int DEFAULT_BUFFER_SIZE = 8192; private OutputStream outputStream; private ByteBuffer bb; private CharBuffer cb; private boolean closed = false; private Boolean text = null; private boolean firstFrame = true; public WsOutbound(OutputStream outputStream) { this(outputStream, DEFAULT_BUFFER_SIZE, DEFAULT_BUFFER_SIZE); } public WsOutbound(OutputStream outputStream, int byteBufferSize, int charBufferSize) { this.outputStream = outputStream; this.bb = ByteBuffer.allocate(byteBufferSize); this.cb = CharBuffer.allocate(charBufferSize); } /** * Adds the data to the buffer for binary data. If a textual message is * currently in progress that message will be completed and a new binary * message started. If the buffer for binary data is full, the buffer will * be flushed and a new binary continuation fragment started. * * @param b The byte (only the least significant byte is used) of data to * send to the client. * * @throws IOException If a flush is required and an error occurs writing * the WebSocket frame to the client */ public synchronized void writeBinaryData(int b) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (bb.position() == bb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.FALSE; } else if (text == Boolean.TRUE) { // Flush the character data flush(); text = Boolean.FALSE; } bb.put((byte) (b & 0xFF)); } /** * Adds the data to the buffer for textual data. If a binary message is * currently in progress that message will be completed and a new textual * message started. If the buffer for textual data is full, the buffer will * be flushed and a new textual continuation fragment started. * * @param c The character to send to the client. * * @throws IOException If a flush is required and an error occurs writing * the WebSocket frame to the client */ public synchronized void writeTextData(char c) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (cb.position() == cb.capacity()) { doFlush(false); } if (text == null) { text = Boolean.TRUE; } else if (text == Boolean.FALSE) { // Flush the binary data flush(); text = Boolean.TRUE; } cb.append(c); } /** * Flush any message (binary or textual) that may be buffered and then send * a WebSocket binary message as a single frame with the provided buffer as * the payload of the message. * * @param msgBb The buffer containing the payload * * @throws IOException If an error occurs writing to the client */ public synchronized void writeBinaryMessage(ByteBuffer msgBb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.FALSE; doWriteBytes(msgBb, true); } /** * Flush any message (binary or textual) that may be buffered and then send * a WebSocket text message as a single frame with the provided buffer as * the payload of the message. * * @param msgCb The buffer containing the payload * * @throws IOException If an error occurs writing to the client */ public synchronized void writeTextMessage(CharBuffer msgCb) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } if (text != null) { // Empty the buffer flush(); } text = Boolean.TRUE; doWriteText(msgCb, true); } /** * Flush any message (binary or textual) that may be buffered. * * @throws IOException If an error occurs writing to the client */ public synchronized void flush() throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(true); } private void doFlush(boolean finalFragment) throws IOException { if (text == null) { // No data return; } if (text.booleanValue()) { cb.flip(); doWriteText(cb, finalFragment); } else { bb.flip(); doWriteBytes(bb, finalFragment); } } /** * Respond to a client close by sending a close that echoes the status code * and message. * * @param frame The close frame received from a client * * @throws IOException If an error occurs writing to the client */ protected void close(WsFrame frame) throws IOException { if (frame.getPayLoadLength() > 0) { // Must be status (2 bytes) plus optional message if (frame.getPayLoadLength() == 1) { throw new IOException(); } int status = (frame.getPayLoad().get() & 0xFF) << 8; status += frame.getPayLoad().get() & 0xFF; if (validateCloseStatus(status)) { // Echo the status back to the client close(status, frame.getPayLoad()); } else { // Invalid close code close(Constants.STATUS_PROTOCOL_ERROR, null); } } else { // No status close(0, null); } } private boolean validateCloseStatus(int status) { if (status == Constants.STATUS_CLOSE_NORMAL || status == Constants.STATUS_SHUTDOWN || status == Constants.STATUS_PROTOCOL_ERROR || status == Constants.STATUS_UNEXPECTED_DATA_TYPE || status == Constants.STATUS_BAD_DATA || status == Constants.STATUS_POLICY_VIOLATION || status == Constants.STATUS_MESSAGE_TOO_LARGE || status == Constants.STATUS_REQUIRED_EXTENSION || status == Constants.STATUS_UNEXPECTED_CONDITION || (status > 2999 && status < 5000)) { // Other 1xxx reserved / not permitted // 2xxx reserved // 3xxx framework defined // 4xxx application defined return true; } // <1000 unused // >4999 undefined return false; } /** * Send a close message to the client * * @param status Must be a valid status code or zero to send no code * @param data Optional message. If message is defined, a valid status * code must be provided. * * @throws IOException If an error occurs writing to the client */ public synchronized void close(int status, ByteBuffer data) throws IOException { if (closed) { return; } // Send any partial data we have doFlush(false); closed = true; outputStream.write(0x88); if (status == 0) { outputStream.write(0); } else if (data == null || data.position() == data.limit()) { outputStream.write(2); outputStream.write(status >>> 8); outputStream.write(status); } else { outputStream.write(2 + data.limit() - data.position()); outputStream.write(status >>> 8); outputStream.write(status); outputStream.write(data.array(), data.position(), data.limit() - data.position()); } outputStream.flush(); bb = null; cb = null; outputStream = null; } /** * Send a pong message to the client * * @param data Optional message. * * @throws IOException If an error occurs writing to the client */ public synchronized void pong(ByteBuffer data) throws IOException { sendControlMessage(data, Constants.OPCODE_PONG); } /** * Send a ping message to the client * * @param data Optional message. * * @throws IOException If an error occurs writing to the client */ public synchronized void ping(ByteBuffer data) throws IOException { sendControlMessage(data, Constants.OPCODE_PING); } /** * Generic function to send either a ping or a pong. * * @param data Optional message. * @param opcode The byte to include as the opcode. * * @throws IOException If an error occurs writing to the client */ private synchronized void sendControlMessage(ByteBuffer data, byte opcode) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } doFlush(false); outputStream.write(0x80 | opcode); if (data == null) { outputStream.write(0); } else { outputStream.write(data.limit() - data.position()); outputStream.write(data.array(), data.position(), data.limit() - data.position()); } outputStream.flush(); } /** * Writes the provided bytes as the payload in a new WebSocket frame. * * @param buffer The bytes to include in the payload. * @param finalFragment Do these bytes represent the final fragment of a * WebSocket message? * @throws IOException */ private void doWriteBytes(ByteBuffer buffer, boolean finalFragment) throws IOException { if (closed) { throw new IOException(sm.getString("outbound.closed")); } // Work out the first byte int first = 0x00; if (finalFragment) { first = first + 0x80; } if (firstFrame) { if (text.booleanValue()) { first = first + 0x1; } else { first = first + 0x2; } } // Continuation frame is OpCode 0 outputStream.write(first); if (buffer.limit() < 126) { outputStream.write(buffer.limit()); } else if (buffer.limit() < 65536) { outputStream.write(126); outputStream.write(buffer.limit() >>> 8); outputStream.write(buffer.limit() & 0xFF); } else { // Will never be more than 2^31-1 outputStream.write(127); outputStream.write(0); outputStream.write(0); outputStream.write(0); outputStream.write(0); outputStream.write(buffer.limit() >>> 24); outputStream.write(buffer.limit() >>> 16); outputStream.write(buffer.limit() >>> 8); outputStream.write(buffer.limit() & 0xFF); } // Write the content outputStream.write(buffer.array(), 0, buffer.limit()); outputStream.flush(); // Reset if (finalFragment) { text = null; firstFrame = true; } else { firstFrame = false; } bb.clear(); } /* * Convert the textual message to bytes and then output it. */ private void doWriteText(CharBuffer buffer, boolean finalFragment) throws IOException { CharsetEncoder encoder = B2CConverter.UTF_8.newEncoder(); do { CoderResult cr = encoder.encode(buffer, bb, true); if (cr.isError()) { cr.throwException(); } bb.flip(); if (buffer.hasRemaining()) { doWriteBytes(bb, false); } else { doWriteBytes(bb, finalFragment); } } while (buffer.hasRemaining()); // Reset - bb will be cleared in doWriteBytes() cb.clear(); } }
54,671
Bug 54671 Spec says ServerContainerProvider#getServerContainer() should be public, but implemented package-private in Tomcat 8.0
null
resolved fixed
28c599f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-11T22:48:07Z
2013-03-12T03:46:40Z
java/javax/websocket/server/ServerContainerProvider.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 javax.websocket.server; import java.util.Iterator; import java.util.ServiceLoader; /** * Provides a standard mechanism for obtaining a reference to the * {@link ServerContainer}. */ public abstract class ServerContainerProvider { private static final String DEFAULT_PROVIDER_CLASS_NAME = "org.apache.tomcat.websocket.ServerContainerImpl"; /** * Use the service loader API to obtain a reference to the * {@link ServerContainer}. */ static ServerContainer getServerContainer() { ServerContainer result = null; ServiceLoader<ServerContainerProvider> serviceLoader = ServiceLoader.load(ServerContainerProvider.class); Iterator<ServerContainerProvider> iter = serviceLoader.iterator(); while (result == null && iter.hasNext()) { result = iter.next().getContainer(); } // Fall-back. Also used by unit tests if (result == null) { try { Class<ServerContainer> clazz = (Class<ServerContainer>) Class.forName( DEFAULT_PROVIDER_CLASS_NAME); result = clazz.newInstance(); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { // No options left. Just return null. } } return result; } protected abstract ServerContainer getContainer(); }
54,690
Bug 54690 HTTPS BIO/NIO connector does not enable TLS 1.1 and TLS 1.2 by default
null
closed fixed
fedf189
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-14T14:41:51Z
2013-03-13T21:26:40Z
java/org/apache/tomcat/util/net/jsse/JSSESocketFactory.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.jsse; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CRL; import java.security.cert.CRLException; import java.security.cert.CertPathParameters; import java.security.cert.CertStore; import java.security.cert.CertStoreParameters; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.CollectionCertStoreParameters; import java.security.cert.PKIXBuilderParameters; import java.security.cert.X509CertSelector; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Locale; import javax.net.ssl.CertPathTrustManagerParameters; import javax.net.ssl.KeyManager; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLException; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSession; import javax.net.ssl.SSLSessionContext; import javax.net.ssl.SSLSocket; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509KeyManager; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.Constants; import org.apache.tomcat.util.net.SSLUtil; import org.apache.tomcat.util.net.ServerSocketFactory; import org.apache.tomcat.util.res.StringManager; /** * SSL server socket factory. It <b>requires</b> a valid RSA key and * JSSE.<br/> * keytool -genkey -alias tomcat -keyalg RSA</br> * Use "changeit" as password (this is the default we use). * * @author Harish Prabandham * @author Costin Manolache * @author Stefan Freyr Stefansson * @author EKR -- renamed to JSSESocketFactory * @author Jan Luehe * @author Bill Barker */ public class JSSESocketFactory implements ServerSocketFactory, SSLUtil { private static final org.apache.juli.logging.Log log = org.apache.juli.logging.LogFactory.getLog(JSSESocketFactory.class); private static final StringManager sm = StringManager.getManager("org.apache.tomcat.util.net.jsse.res"); private static final boolean RFC_5746_SUPPORTED; // Defaults - made public where re-used private static final String defaultProtocol = "TLS"; private static final String defaultKeystoreType = "JKS"; private static final String defaultKeystoreFile = System.getProperty("user.home") + "/.keystore"; private static final int defaultSessionCacheSize = 0; private static final int defaultSessionTimeout = 86400; private static final String ALLOW_ALL_SUPPORTED_CIPHERS = "ALL"; public static final String DEFAULT_KEY_PASS = "changeit"; static { boolean result = false; SSLContext context; try { context = SSLContext.getInstance("TLS"); context.init(null, null, null); SSLServerSocketFactory ssf = context.getServerSocketFactory(); String ciphers[] = ssf.getSupportedCipherSuites(); for (String cipher : ciphers) { if ("TLS_EMPTY_RENEGOTIATION_INFO_SCSV".equals(cipher)) { result = true; break; } } } catch (NoSuchAlgorithmException e) { // Assume no RFC 5746 support } catch (KeyManagementException e) { // Assume no RFC 5746 support } RFC_5746_SUPPORTED = result; } private AbstractEndpoint endpoint; protected SSLServerSocketFactory sslProxy = null; protected String[] enabledCiphers; protected String[] enabledProtocols; protected boolean allowUnsafeLegacyRenegotiation = false; /** * Flag to state that we require client authentication. */ protected boolean requireClientAuth = false; /** * Flag to state that we would like client authentication. */ protected boolean wantClientAuth = false; public JSSESocketFactory (AbstractEndpoint endpoint) { this.endpoint = endpoint; } @Override public ServerSocket createSocket (int port) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port); initServerSocket(socket); return socket; } @Override public ServerSocket createSocket (int port, int backlog) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog); initServerSocket(socket); return socket; } @Override public ServerSocket createSocket (int port, int backlog, InetAddress ifAddress) throws IOException { init(); ServerSocket socket = sslProxy.createServerSocket(port, backlog, ifAddress); initServerSocket(socket); return socket; } @Override public Socket acceptSocket(ServerSocket socket) throws IOException { SSLSocket asock = null; try { asock = (SSLSocket)socket.accept(); } catch (SSLException e){ throw new SocketException("SSL handshake error" + e.toString()); } return asock; } @Override public void handshake(Socket sock) throws IOException { // We do getSession instead of startHandshake() so we can call this multiple times SSLSession session = ((SSLSocket)sock).getSession(); if (session.getCipherSuite().equals("SSL_NULL_WITH_NULL_NULL")) throw new IOException("SSL handshake failed. Ciper suite in SSL Session is SSL_NULL_WITH_NULL_NULL"); if (!allowUnsafeLegacyRenegotiation && !RFC_5746_SUPPORTED) { // Prevent further handshakes by removing all cipher suites ((SSLSocket) sock).setEnabledCipherSuites(new String[0]); } } @Override public String[] getEnableableCiphers(SSLContext context) { String requestedCiphersStr = endpoint.getCiphers(); if (ALLOW_ALL_SUPPORTED_CIPHERS.equals(requestedCiphersStr)) { return context.getSupportedSSLParameters().getCipherSuites(); } if ((requestedCiphersStr == null) || (requestedCiphersStr.trim().length() == 0)) { return context.getDefaultSSLParameters().getCipherSuites(); } List<String> requestedCiphers = new ArrayList<>(); for (String rc : requestedCiphersStr.split(",")) { final String cipher = rc.trim(); if (cipher.length() > 0) { requestedCiphers.add(cipher); } } if (requestedCiphers.isEmpty()) { return context.getDefaultSSLParameters().getCipherSuites(); } List<String> ciphers = new ArrayList<>(requestedCiphers); ciphers.retainAll(Arrays.asList(context.getSupportedSSLParameters() .getCipherSuites())); if (ciphers.isEmpty()) { log.warn(sm.getString("jsse.requested_ciphers_not_supported", requestedCiphersStr)); } if (log.isDebugEnabled()) { log.debug(sm.getString("jsse.enableable_ciphers", ciphers)); if (ciphers.size() != requestedCiphers.size()) { List<String> skipped = new ArrayList<>(requestedCiphers); skipped.removeAll(ciphers); log.debug(sm.getString("jsse.unsupported_ciphers", skipped)); } } return ciphers.toArray(new String[ciphers.size()]); } public String[] getEnabledCiphers() { return enabledCiphers; } /* * Gets the SSL server's keystore password. */ protected String getKeystorePassword() { String keystorePass = endpoint.getKeystorePass(); if (keystorePass == null) { keystorePass = endpoint.getKeyPass(); } if (keystorePass == null) { keystorePass = DEFAULT_KEY_PASS; } return keystorePass; } /* * Gets the SSL server's keystore. */ protected KeyStore getKeystore(String type, String provider, String pass) throws IOException { String keystoreFile = endpoint.getKeystoreFile(); if (keystoreFile == null) keystoreFile = defaultKeystoreFile; return getStore(type, provider, keystoreFile, pass); } /* * Gets the SSL server's truststore. */ protected KeyStore getTrustStore(String keystoreType, String keystoreProvider) throws IOException { KeyStore trustStore = null; String truststoreFile = endpoint.getTruststoreFile(); if(truststoreFile == null) { truststoreFile = System.getProperty("javax.net.ssl.trustStore"); } if(log.isDebugEnabled()) { log.debug("Truststore = " + truststoreFile); } String truststorePassword = endpoint.getTruststorePass(); if( truststorePassword == null) { truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword"); } if(log.isDebugEnabled()) { log.debug("TrustPass = " + truststorePassword); } String truststoreType = endpoint.getTruststoreType(); if( truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if(truststoreType == null) { truststoreType = keystoreType; } if(log.isDebugEnabled()) { log.debug("trustType = " + truststoreType); } String truststoreProvider = endpoint.getTruststoreProvider(); if( truststoreProvider == null) { truststoreProvider = System.getProperty("javax.net.ssl.trustStoreProvider"); } if (truststoreProvider == null) { truststoreProvider = keystoreProvider; } if(log.isDebugEnabled()) { log.debug("trustProvider = " + truststoreProvider); } if (truststoreFile != null){ try { trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, truststorePassword); } catch (IOException ioe) { Throwable cause = ioe.getCause(); if (cause instanceof UnrecoverableKeyException) { // Log a warning we had a password issue log.warn(sm.getString("jsse.invalid_truststore_password"), cause); // Re-try trustStore = getStore(truststoreType, truststoreProvider, truststoreFile, null); } else { // Something else went wrong - re-throw throw ioe; } } } return trustStore; } /* * Gets the key- or truststore with the specified type, path, and password. */ private KeyStore getStore(String type, String provider, String path, String pass) throws IOException { KeyStore ks = null; InputStream istream = null; try { if (provider == null) { ks = KeyStore.getInstance(type); } else { ks = KeyStore.getInstance(type, provider); } if(!("PKCS11".equalsIgnoreCase(type) || "".equalsIgnoreCase(path))) { File keyStoreFile = new File(path); if (!keyStoreFile.isAbsolute()) { keyStoreFile = new File(System.getProperty( Constants.CATALINA_BASE_PROP), path); } istream = new FileInputStream(keyStoreFile); } char[] storePass = null; if (pass != null && !"".equals(pass)) { storePass = pass.toCharArray(); } ks.load(istream, storePass); } catch (FileNotFoundException fnfe) { log.error(sm.getString("jsse.keystore_load_failed", type, path, fnfe.getMessage()), fnfe); throw fnfe; } catch (IOException ioe) { // May be expected when working with a trust store // Re-throw. Caller will catch and log as required throw ioe; } catch(Exception ex) { String msg = sm.getString("jsse.keystore_load_failed", type, path, ex.getMessage()); log.error(msg, ex); throw new IOException(msg); } finally { if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Do nothing } } } return ks; } /** * Reads the keystore and initializes the SSL socket factory. */ void init() throws IOException { try { String clientAuthStr = endpoint.getClientAuth(); if("true".equalsIgnoreCase(clientAuthStr) || "yes".equalsIgnoreCase(clientAuthStr)) { requireClientAuth = true; } else if("want".equalsIgnoreCase(clientAuthStr)) { wantClientAuth = true; } SSLContext context = createSSLContext(); context.init(getKeyManagers(), getTrustManagers(), null); // Configure SSL session cache SSLSessionContext sessionContext = context.getServerSessionContext(); if (sessionContext != null) { configureSessionContext(sessionContext); } // create proxy sslProxy = context.getServerSocketFactory(); // Determine which cipher suites to enable enabledCiphers = getEnableableCiphers(context); enabledProtocols = getEnableableProtocols(context); allowUnsafeLegacyRenegotiation = "true".equals( endpoint.getAllowUnsafeLegacyRenegotiation()); // Check the SSL config is OK checkConfig(); } catch(Exception e) { if( e instanceof IOException ) throw (IOException)e; throw new IOException(e.getMessage(), e); } } @Override public SSLContext createSSLContext() throws Exception { // SSL protocol variant (e.g., TLS, SSL v3, etc.) String protocol = endpoint.getSslProtocol(); if (protocol == null) { protocol = defaultProtocol; } SSLContext context = SSLContext.getInstance(protocol); return context; } @Override public KeyManager[] getKeyManagers() throws Exception { String keystoreType = endpoint.getKeystoreType(); if (keystoreType == null) { keystoreType = defaultKeystoreType; } String algorithm = endpoint.getAlgorithm(); if (algorithm == null) { algorithm = KeyManagerFactory.getDefaultAlgorithm(); } return getKeyManagers(keystoreType, endpoint.getKeystoreProvider(), algorithm, endpoint.getKeyAlias()); } @Override public TrustManager[] getTrustManagers() throws Exception { String truststoreType = endpoint.getTruststoreType(); if (truststoreType == null) { truststoreType = System.getProperty("javax.net.ssl.trustStoreType"); } if (truststoreType == null) { truststoreType = endpoint.getKeystoreType(); } if (truststoreType == null) { truststoreType = defaultKeystoreType; } String algorithm = endpoint.getTruststoreAlgorithm(); if (algorithm == null) { algorithm = TrustManagerFactory.getDefaultAlgorithm(); } return getTrustManagers(truststoreType, endpoint.getKeystoreProvider(), algorithm); } @Override public void configureSessionContext(SSLSessionContext sslSessionContext) { int sessionCacheSize; if (endpoint.getSessionCacheSize() != null) { sessionCacheSize = Integer.parseInt( endpoint.getSessionCacheSize()); } else { sessionCacheSize = defaultSessionCacheSize; } int sessionTimeout; if (endpoint.getSessionTimeout() != null) { sessionTimeout = Integer.parseInt(endpoint.getSessionTimeout()); } else { sessionTimeout = defaultSessionTimeout; } sslSessionContext.setSessionCacheSize(sessionCacheSize); sslSessionContext.setSessionTimeout(sessionTimeout); } /** * Gets the initialized key managers. */ protected KeyManager[] getKeyManagers(String keystoreType, String keystoreProvider, String algorithm, String keyAlias) throws Exception { KeyManager[] kms = null; String keystorePass = getKeystorePassword(); KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass); if (keyAlias != null && !ks.isKeyEntry(keyAlias)) { throw new IOException( sm.getString("jsse.alias_no_key_entry", keyAlias)); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); String keyPass = endpoint.getKeyPass(); if (keyPass == null) { keyPass = keystorePass; } kmf.init(ks, keyPass.toCharArray()); kms = kmf.getKeyManagers(); if (keyAlias != null) { String alias = keyAlias; if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) { alias = alias.toLowerCase(Locale.ENGLISH); } for(int i=0; i<kms.length; i++) { kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias); } } return kms; } /** * Gets the initialized trust managers. */ protected TrustManager[] getTrustManagers(String keystoreType, String keystoreProvider, String algorithm) throws Exception { String crlf = endpoint.getCrlFile(); String className = endpoint.getTrustManagerClassName(); if(className != null && className.length() > 0) { ClassLoader classLoader = getClass().getClassLoader(); Class<?> clazz = classLoader.loadClass(className); if(!(TrustManager.class.isAssignableFrom(clazz))){ throw new InstantiationException(sm.getString( "jsse.invalidTrustManagerClassName", className)); } Object trustManagerObject = clazz.newInstance(); TrustManager trustManager = (TrustManager) trustManagerObject; return new TrustManager[]{ trustManager }; } TrustManager[] tms = null; KeyStore trustStore = getTrustStore(keystoreType, keystoreProvider); if (trustStore != null || endpoint.getTrustManagerClassName() != null) { if (crlf == null) { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); tmf.init(trustStore); tms = tmf.getTrustManagers(); } else { TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm); CertPathParameters params = getParameters(algorithm, crlf, trustStore); ManagerFactoryParameters mfp = new CertPathTrustManagerParameters(params); tmf.init(mfp); tms = tmf.getTrustManagers(); } } return tms; } /** * Return the initialization parameters for the TrustManager. * Currently, only the default <code>PKIX</code> is supported. * * @param algorithm The algorithm to get parameters for. * @param crlf The path to the CRL file. * @param trustStore The configured TrustStore. * @return The parameters including the CRLs and TrustStore. */ protected CertPathParameters getParameters(String algorithm, String crlf, KeyStore trustStore) throws Exception { CertPathParameters params = null; if("PKIX".equalsIgnoreCase(algorithm)) { PKIXBuilderParameters xparams = new PKIXBuilderParameters(trustStore, new X509CertSelector()); Collection<? extends CRL> crls = getCRLs(crlf); CertStoreParameters csp = new CollectionCertStoreParameters(crls); CertStore store = CertStore.getInstance("Collection", csp); xparams.addCertStore(store); xparams.setRevocationEnabled(true); String trustLength = endpoint.getTrustMaxCertLength(); if(trustLength != null) { try { xparams.setMaxPathLength(Integer.parseInt(trustLength)); } catch(Exception ex) { log.warn("Bad maxCertLength: "+trustLength); } } params = xparams; } else { throw new CRLException("CRLs not supported for type: "+algorithm); } return params; } /** * Load the collection of CRLs. * */ protected Collection<? extends CRL> getCRLs(String crlf) throws IOException, CRLException, CertificateException { File crlFile = new File(crlf); if( !crlFile.isAbsolute() ) { crlFile = new File( System.getProperty(Constants.CATALINA_BASE_PROP), crlf); } Collection<? extends CRL> crls = null; InputStream is = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); is = new FileInputStream(crlFile); crls = cf.generateCRLs(is); } catch(IOException iex) { throw iex; } catch(CRLException crle) { throw crle; } catch(CertificateException ce) { throw ce; } finally { if(is != null) { try{ is.close(); } catch(Exception ex) { // Ignore } } } return crls; } @Override public String[] getEnableableProtocols(SSLContext context) { String[] requestedProtocols = endpoint.getSslEnabledProtocolsArray(); if ((requestedProtocols == null) || (requestedProtocols.length == 0)) { return context.getDefaultSSLParameters().getProtocols(); } List<String> protocols = new ArrayList<>( Arrays.asList(requestedProtocols)); protocols.retainAll(Arrays.asList(context.getSupportedSSLParameters() .getProtocols())); if (protocols.isEmpty()) { log.warn(sm.getString("jsse.requested_protocols_not_supported", Arrays.asList(requestedProtocols))); } if (log.isDebugEnabled()) { log.debug(sm.getString("jsse.enableable_protocols", protocols)); if (protocols.size() != requestedProtocols.length) { List<String> skipped = new ArrayList<>( Arrays.asList(requestedProtocols)); skipped.removeAll(protocols); log.debug(sm.getString("jsse.unsupported_protocols", skipped)); } } return protocols.toArray(new String[protocols.size()]); } /** * Configure Client authentication for this version of JSSE. The * JSSE included in Java 1.4 supports the 'want' value. Prior * versions of JSSE will treat 'want' as 'false'. * @param socket the SSLServerSocket */ protected void configureClientAuth(SSLServerSocket socket){ if (wantClientAuth){ socket.setWantClientAuth(wantClientAuth); } else { socket.setNeedClientAuth(requireClientAuth); } } /** * Configures the given SSL server socket with the requested cipher suites, * protocol versions, and need for client authentication */ private void initServerSocket(ServerSocket ssocket) { SSLServerSocket socket = (SSLServerSocket) ssocket; socket.setEnabledCipherSuites(enabledCiphers); socket.setEnabledProtocols(enabledProtocols); // we don't know if client auth is needed - // after parsing the request we may re-handshake configureClientAuth(socket); } /** * Checks that the certificate is compatible with the enabled cipher suites. * If we don't check now, the JIoEndpoint can enter a nasty logging loop. * See bug 45528. */ private void checkConfig() throws IOException { // Create an unbound server socket ServerSocket socket = sslProxy.createServerSocket(); initServerSocket(socket); try { // Set the timeout to 1ms as all we care about is if it throws an // SSLException on accept. socket.setSoTimeout(1); socket.accept(); // Will never get here - no client can connect to an unbound port } catch (SSLException ssle) { // SSL configuration is invalid. Possibly cert doesn't match ciphers IOException ioe = new IOException(sm.getString( "jsse.invalid_ssl_conf", ssle.getMessage())); ioe.initCause(ssle); throw ioe; } catch (Exception e) { /* * Possible ways of getting here * socket.accept() throws a SecurityException * socket.setSoTimeout() throws a SocketException * socket.accept() throws some other exception (after a JDK change) * In these cases the test won't work so carry on - essentially * the behaviour before this patch * socket.accept() throws a SocketTimeoutException * In this case all is well so carry on */ } finally { // Should be open here but just in case if (!socket.isClosed()) { socket.close(); } } } }
54,660
Bug 54660 AccessLogValve fileDateFormat can not be changed through JMX
When an AccessLogValve is added to a catalina host with the JMX addVale() operation on the Host object name, the valve will start with the default fileDateFormat. Changing the attribute on the valve through it's JMX object name has no effect because the valve is already started. Executing a rotate() operation on the valve does also have no effect. Steps to Reproduce: - Start tomcat server - Add Host using JMX - Add valve to Host using JMX - Set valve attribute fileDateFormat to something else than yyyy-MM-dd, for example yy-MM Actual Results: The access log file format will include the default fileDateFormat of yyyy-MM-dd Expected Results: The access log file format with yy-MM, as from the example.
resolved fixed
2a03ca6
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-14T15:47:24Z
2013-03-10T10:06:40Z
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) { this.fileDateFormat = fileDateFormat; } /** * 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); } } /** * 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) { 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(); } } } } } /* 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(); if (format == null) { format = ""; setFileDateFormat(format); } 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 + "???"); } } }
54,658
Bug 54658 Implement Part#getSubmittedFileName from SERVLET_SPEC-57
null
resolved fixed
ca205c1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-14T20:34:32Z
2013-03-10T01:46:40Z
java/javax/servlet/http/Part.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 javax.servlet.http; import java.io.IOException; import java.io.InputStream; import java.util.Collection; /** * This class represents a part as uploaded to the server as part of a * <code>multipart/form-data</code> request body. The part may represent either * an uploaded file or form data. * * @since Servlet 3.0 */ public interface Part { /** * Obtain an <code>InputStream</code> that can be used to retrieve the * contents of the file. */ public InputStream getInputStream() throws IOException; /** * Obtain the content type passed by the browser or <code>null</code> if not * defined. */ public String getContentType(); /** * Obtain the name of the field in the multipart form corresponding to this * part. */ public String getName(); /** * Obtain the size of this part. */ public long getSize(); /** * A convenience method to write an uploaded part to disk. The client code * is not concerned with whether or not the part is stored in memory, or on * disk in a temporary location. They just want to write the uploaded part * to a file. * * This method is not guaranteed to succeed if called more than once for * the same part. This allows a particular implementation to use, for * example, file renaming, where possible, rather than copying all of the * underlying data, thus gaining a significant performance benefit. * * @param fileName The location into which the uploaded part should be * stored. Relative locations are relative to {@link * javax.servlet.MultipartConfigElement#getLocation()} */ public void write(String fileName) throws IOException; /** * Deletes the underlying storage for a part, including deleting any * associated temporary disk file. Although the container will delete this * storage automatically this method can be used to ensure that this is done * at an earlier time, thus preserving system resources. * <p> * Containers are only required to delete the associated storage when the * Part instance is garbage collected. Apache Tomcat will delete the * associated storage when the associated request has finished processing. * Behaviour of other containers may be different. */ public void delete() throws IOException; /** * Obtains the value of the specified part header as a String. If there are * multiple headers with the same name, this method returns the first header * in the part. The header name is case insensitive. * * @param name Header name * @return The header value or <code>null</code> if the header is not * present */ public String getHeader(String name); /** * Obtain all the values of the specified part header. If the part did not * include any headers of the specified name, this method returns an empty * Collection. The header name is case insensitive. */ public Collection<String> getHeaders(String name); /** * Returns a Collection of all the header names provided for this part. */ public Collection<String> getHeaderNames(); }
54,658
Bug 54658 Implement Part#getSubmittedFileName from SERVLET_SPEC-57
null
resolved fixed
ca205c1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-14T20:34:32Z
2013-03-10T01:46:40Z
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.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.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.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(); } public boolean isAsyncOperation() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC_OPERATION, 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 void upgrade(HttpUpgradeHandler handler) throws IOException { 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 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); } /** * 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(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.getFilename() == 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,658
Bug 54658 Implement Part#getSubmittedFileName from SERVLET_SPEC-57
null
resolved fixed
ca205c1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-14T20:34:32Z
2013-03-10T01:46:40Z
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() */ public String getFilename() { 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,658
Bug 54658 Implement Part#getSubmittedFileName from SERVLET_SPEC-57
null
resolved fixed
ca205c1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-14T20:34:32Z
2013-03-10T01:46:40Z
java/org/apache/catalina/manager/HTMLManagerServlet.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.manager; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.net.InetAddress; import java.net.UnknownHostException; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.Part; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.DistributedManager; import org.apache.catalina.Manager; import org.apache.catalina.Session; import org.apache.catalina.manager.util.BaseSessionComparator; import org.apache.catalina.manager.util.ReverseComparator; import org.apache.catalina.manager.util.SessionUtils; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.RequestUtil; import org.apache.catalina.util.ServerInfo; import org.apache.catalina.util.URLEncoder; import org.apache.tomcat.util.http.fileupload.ParameterParser; import org.apache.tomcat.util.res.StringManager; /** * Servlet that enables remote management of the web applications deployed * within the same virtual host as this web application is. Normally, this * functionality will be protected by a security constraint in the web * application deployment descriptor. However, this requirement can be * relaxed during testing. * <p> * The difference between the <code>ManagerServlet</code> and this * Servlet is that this Servlet prints out a HTML interface which * makes it easier to administrate. * <p> * However if you use a software that parses the output of * <code>ManagerServlet</code> you won't be able to upgrade * to this Servlet since the output are not in the * same format ar from <code>ManagerServlet</code> * * @author Bip Thelin * @author Malcolm Edgar * @author Glenn L. Nielsen * @version $Id$ * @see ManagerServlet */ public final class HTMLManagerServlet extends ManagerServlet { private static final long serialVersionUID = 1L; protected static final URLEncoder URL_ENCODER; protected static final String APPLICATION_MESSAGE = "message"; protected static final String APPLICATION_ERROR = "error"; protected static final String sessionsListJspPath = "/WEB-INF/jsp/sessionsList.jsp"; protected static final String sessionDetailJspPath = "/WEB-INF/jsp/sessionDetail.jsp"; protected static final String connectorCiphersJspPath = "/WEB-INF/jsp/connectorCiphers.jsp"; static { URL_ENCODER = new URLEncoder(); // '/' should not be encoded in context paths URL_ENCODER.addSafeCharacter('/'); } private boolean showProxySessions = false; // --------------------------------------------------------- Public Methods /** * Process a GET request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; // Process the requested command if (command == null || command.equals("/")) { // No command == list } else if (command.equals("/list")) { // List always displayed - nothing to do here } else if (command.equals("/sessions")) { try { doSessions(cn, request, response, smClient); return; } catch (Exception e) { log("HTMLManagerServlet.sessions[" + cn + "]", e); message = smClient.getString("managerServlet.exception", e.toString()); } } else if (command.equals("/sslConnectorCiphers")) { sslConnectorCiphers(request, response); } else if (command.equals("/upload") || command.equals("/deploy") || command.equals("/reload") || command.equals("/undeploy") || command.equals("/expire") || command.equals("/start") || command.equals("/stop")) { message = smClient.getString("managerServlet.postCommand", command); } else { message = smClient.getString("managerServlet.unknownCommand", command); } list(request, response, message, smClient); } /** * Process a POST request for the specified resource. * * @param request The servlet request we are processing * @param response The servlet response we are creating * * @exception IOException if an input/output error occurs * @exception ServletException if a servlet-specified error occurs */ @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { StringManager smClient = getStringManager(request); // Identify the request parameters that we need // By obtaining the command from the pathInfo, per-command security can // be configured in web.xml String command = request.getPathInfo(); String path = request.getParameter("path"); ContextName cn = null; if (path != null) { cn = new ContextName(path, request.getParameter("version")); } String deployPath = request.getParameter("deployPath"); ContextName deployCn = null; if (deployPath != null) { deployCn = new ContextName(deployPath, request.getParameter("deployVersion")); } String deployConfig = request.getParameter("deployConfig"); String deployWar = request.getParameter("deployWar"); // Prepare our output writer to generate the response message response.setContentType("text/html; charset=" + Constants.CHARSET); String message = ""; if (command == null || command.length() == 0) { // No command == list // List always displayed -> do nothing } else if (command.equals("/upload")) { message = upload(request, smClient); } else if (command.equals("/deploy")) { message = deployInternal(deployConfig, deployCn, deployWar, smClient); } else if (command.equals("/reload")) { message = reload(cn, smClient); } else if (command.equals("/undeploy")) { message = undeploy(cn, smClient); } else if (command.equals("/expire")) { message = expireSessions(cn, request, smClient); } else if (command.equals("/start")) { message = start(cn, smClient); } else if (command.equals("/stop")) { message = stop(cn, smClient); } else if (command.equals("/findleaks")) { message = findleaks(smClient); } else { // Try GET doGet(request,response); return; } list(request, response, message, smClient); } protected String upload(HttpServletRequest request, StringManager smClient) throws IOException, ServletException { String message = ""; Part warPart = null; String filename = null; Collection<Part> parts = request.getParts(); Iterator<Part> iter = parts.iterator(); try { while (iter.hasNext()) { Part part = iter.next(); if (part.getName().equals("deployWar") && warPart == null) { warPart = part; } else { part.delete(); } } while (true) { if (warPart == null) { message = smClient.getString( "htmlManagerServlet.deployUploadNoFile"); break; } filename = extractFilename(warPart.getHeader("Content-Disposition")); if (!filename.toLowerCase(Locale.ENGLISH).endsWith(".war")) { message = smClient.getString( "htmlManagerServlet.deployUploadNotWar", filename); break; } // Get the filename if uploaded name includes a path if (filename.lastIndexOf('\\') >= 0) { filename = filename.substring(filename.lastIndexOf('\\') + 1); } if (filename.lastIndexOf('/') >= 0) { filename = filename.substring(filename.lastIndexOf('/') + 1); } // Identify the appBase of the owning Host of this Context // (if any) File file = new File(host.getAppBaseFile(), filename); if (file.exists()) { message = smClient.getString( "htmlManagerServlet.deployUploadWarExists", filename); break; } ContextName cn = new ContextName(filename); String name = cn.getName(); if ((host.findChild(name) != null) && !isDeployed(name)) { message = smClient.getString( "htmlManagerServlet.deployUploadInServerXml", filename); break; } if (!isServiced(name)) { addServiced(name); try { warPart.write(file.getAbsolutePath()); // Perform new deployment check(name); } finally { removeServiced(name); } } break; } } catch(Exception e) { message = smClient.getString ("htmlManagerServlet.deployUploadFail", e.getMessage()); log(message, e); } finally { if (warPart != null) { warPart.delete(); } warPart = null; } return message; } /* * Adapted from FileUploadBase.getFileName() */ private String extractFilename(String cd) { String fileName = null; if (cd != null) { String cdl = cd.toLowerCase(Locale.ENGLISH); if (cdl.startsWith("form-data") || cdl.startsWith("attachment")) { ParameterParser parser = new ParameterParser(); parser.setLowerCaseNames(true); // Parameter parser can handle null input Map<String,String> params = parser.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; } /** * Deploy an application for the specified path from the specified * web application archive. * * @param config URL of the context configuration file to be deployed * @param cn Name of the application to be deployed * @param war URL of the web application archive to be deployed * @return message String */ protected String deployInternal(String config, ContextName cn, String war, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.deploy(printWriter, config, cn, war, false, smClient); return stringWriter.toString(); } /** * Render a HTML list of the currently active Contexts in our virtual host, * and memory and server status information. * * @param request The request * @param response The response * @param message a message to display */ protected void list(HttpServletRequest request, HttpServletResponse response, String message, StringManager smClient) throws IOException { if (debug >= 1) log("list: Listing contexts for virtual host '" + host.getName() + "'"); PrintWriter writer = response.getWriter(); // HTML Header Section writer.print(Constants.HTML_HEADER_SECTION); // Body Header Section Object[] args = new Object[2]; args[0] = request.getContextPath(); args[1] = smClient.getString("htmlManagerServlet.title"); writer.print(MessageFormat.format (Constants.BODY_HEADER_SECTION, args)); // Message Section args = new Object[3]; args[0] = smClient.getString("htmlManagerServlet.messageLabel"); if (message == null || message.length() == 0) { args[1] = "OK"; } else { args[1] = RequestUtil.filter(message); } writer.print(MessageFormat.format(Constants.MESSAGE_SECTION, args)); // Manager Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.manager"); args[1] = response.encodeURL(request.getContextPath() + "/html/list"); args[2] = smClient.getString("htmlManagerServlet.list"); args[3] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpHtmlManagerFile")); args[4] = smClient.getString("htmlManagerServlet.helpHtmlManager"); args[5] = response.encodeURL (request.getContextPath() + "/" + smClient.getString("htmlManagerServlet.helpManagerFile")); args[6] = smClient.getString("htmlManagerServlet.helpManager"); args[7] = response.encodeURL (request.getContextPath() + "/status"); args[8] = smClient.getString("statusServlet.title"); writer.print(MessageFormat.format(Constants.MANAGER_SECTION, args)); // Apps Header Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.appsTitle"); args[1] = smClient.getString("htmlManagerServlet.appsPath"); args[2] = smClient.getString("htmlManagerServlet.appsVersion"); args[3] = smClient.getString("htmlManagerServlet.appsName"); args[4] = smClient.getString("htmlManagerServlet.appsAvailable"); args[5] = smClient.getString("htmlManagerServlet.appsSessions"); args[6] = smClient.getString("htmlManagerServlet.appsTasks"); writer.print(MessageFormat.format(APPS_HEADER_SECTION, args)); // Apps Row Section // Create sorted map of deployed applications by context name. Container children[] = host.findChildren(); String contextNames[] = new String[children.length]; for (int i = 0; i < children.length; i++) contextNames[i] = children[i].getName(); Arrays.sort(contextNames); String appsStart = smClient.getString("htmlManagerServlet.appsStart"); String appsStop = smClient.getString("htmlManagerServlet.appsStop"); String appsReload = smClient.getString("htmlManagerServlet.appsReload"); String appsUndeploy = smClient.getString("htmlManagerServlet.appsUndeploy"); String appsExpire = smClient.getString("htmlManagerServlet.appsExpire"); String noVersion = "<i>" + smClient.getString("htmlManagerServlet.noVersion") + "</i>"; boolean isHighlighted = true; boolean isDeployed = true; String highlightColor = null; for (String contextName : contextNames) { Context ctxt = (Context) host.findChild(contextName); if (ctxt != null) { // Bugzilla 34818, alternating row colors isHighlighted = !isHighlighted; if(isHighlighted) { highlightColor = "#C3F3C3"; } else { highlightColor = "#FFFFFF"; } String contextPath = ctxt.getPath(); String displayPath = contextPath; if (displayPath.equals("")) { displayPath = "/"; } StringBuilder tmp = new StringBuilder(); tmp.append("path="); tmp.append(URL_ENCODER.encode(displayPath)); if (ctxt.getWebappVersion().length() > 0) { tmp.append("&version="); tmp.append(URL_ENCODER.encode(ctxt.getWebappVersion())); } String pathVersion = tmp.toString(); try { isDeployed = isDeployed(contextName); } catch (Exception e) { // Assume false on failure for safety isDeployed = false; } args = new Object[7]; args[0] = "<a href=\"" + URL_ENCODER.encode(contextPath + "/") + "\">" + RequestUtil.filter(displayPath) + "</a>"; if ("".equals(ctxt.getWebappVersion())) { args[1] = noVersion; } else { args[1] = RequestUtil.filter(ctxt.getWebappVersion()); } if (ctxt.getDisplayName() == null) { args[2] = "&nbsp;"; } else { args[2] = RequestUtil.filter(ctxt.getDisplayName()); } args[3] = Boolean.valueOf(ctxt.getState().isAvailable()); args[4] = RequestUtil.filter(response.encodeURL(request.getContextPath() + "/html/sessions?" + pathVersion)); Manager manager = ctxt.getManager(); if (manager instanceof DistributedManager && showProxySessions) { args[5] = Integer.valueOf( ((DistributedManager)manager).getActiveSessionsFull()); } else if (ctxt.getManager() != null){ args[5] = Integer.valueOf(manager.getActiveSessions()); } else { args[5] = Integer.valueOf(0); } args[6] = highlightColor; writer.print (MessageFormat.format(APPS_ROW_DETAILS_SECTION, args)); args = new Object[14]; args[0] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/start?" + pathVersion)); args[1] = appsStart; args[2] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/stop?" + pathVersion)); args[3] = appsStop; args[4] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/reload?" + pathVersion)); args[5] = appsReload; args[6] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/undeploy?" + pathVersion)); args[7] = appsUndeploy; args[8] = RequestUtil.filter(response.encodeURL(request .getContextPath() + "/html/expire?" + pathVersion)); args[9] = appsExpire; args[10] = smClient.getString( "htmlManagerServlet.expire.explain"); if (manager == null) { args[11] = smClient.getString( "htmlManagerServlet.noManager"); } else { args[11] = Integer.valueOf( ctxt.getManager().getMaxInactiveInterval()/60); } args[12] = smClient.getString("htmlManagerServlet.expire.unit"); args[13] = highlightColor; if (ctxt.getName().equals(this.context.getName())) { writer.print(MessageFormat.format( MANAGER_APP_ROW_BUTTON_SECTION, args)); } else if (ctxt.getState().isAvailable() && isDeployed) { writer.print(MessageFormat.format( STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (ctxt.getState().isAvailable() && !isDeployed) { writer.print(MessageFormat.format( STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else if (!ctxt.getState().isAvailable() && isDeployed) { writer.print(MessageFormat.format( STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } else { writer.print(MessageFormat.format( STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION, args)); } } } // Deploy Section args = new Object[7]; args[0] = smClient.getString("htmlManagerServlet.deployTitle"); args[1] = smClient.getString("htmlManagerServlet.deployServer"); args[2] = response.encodeURL(request.getContextPath() + "/html/deploy"); args[3] = smClient.getString("htmlManagerServlet.deployPath"); args[4] = smClient.getString("htmlManagerServlet.deployConfig"); args[5] = smClient.getString("htmlManagerServlet.deployWar"); args[6] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(DEPLOY_SECTION, args)); args = new Object[4]; args[0] = smClient.getString("htmlManagerServlet.deployUpload"); args[1] = response.encodeURL(request.getContextPath() + "/html/upload"); args[2] = smClient.getString("htmlManagerServlet.deployUploadFile"); args[3] = smClient.getString("htmlManagerServlet.deployButton"); writer.print(MessageFormat.format(UPLOAD_SECTION, args)); // Diagnostics section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.diagnosticsTitle"); args[1] = smClient.getString("htmlManagerServlet.diagnosticsLeak"); args[2] = response.encodeURL( request.getContextPath() + "/html/findleaks"); args[3] = smClient.getString("htmlManagerServlet.diagnosticsLeakWarning"); args[4] = smClient.getString("htmlManagerServlet.diagnosticsLeakButton"); args[5] = smClient.getString("htmlManagerServlet.diagnosticsSsl"); args[6] = response.encodeURL( request.getContextPath() + "/html/sslConnectorCiphers"); args[7] = smClient.getString("htmlManagerServlet.diagnosticsSslConnectorCipherButton"); args[8] = smClient.getString("htmlManagerServlet.diagnosticsSslConnectorCipherText"); writer.print(MessageFormat.format(DIAGNOSTICS_SECTION, args)); // Server Header Section args = new Object[9]; args[0] = smClient.getString("htmlManagerServlet.serverTitle"); args[1] = smClient.getString("htmlManagerServlet.serverVersion"); args[2] = smClient.getString("htmlManagerServlet.serverJVMVersion"); args[3] = smClient.getString("htmlManagerServlet.serverJVMVendor"); args[4] = smClient.getString("htmlManagerServlet.serverOSName"); args[5] = smClient.getString("htmlManagerServlet.serverOSVersion"); args[6] = smClient.getString("htmlManagerServlet.serverOSArch"); args[7] = sm.getString("htmlManagerServlet.serverHostname"); args[8] = sm.getString("htmlManagerServlet.serverIPAddress"); writer.print(MessageFormat.format (Constants.SERVER_HEADER_SECTION, args)); // Server Row Section args = new Object[8]; args[0] = ServerInfo.getServerInfo(); args[1] = System.getProperty("java.runtime.version"); args[2] = System.getProperty("java.vm.vendor"); args[3] = System.getProperty("os.name"); args[4] = System.getProperty("os.version"); args[5] = System.getProperty("os.arch"); try { InetAddress address = InetAddress.getLocalHost(); args[6] = address.getHostName(); args[7] = address.getHostAddress(); } catch (UnknownHostException e) { args[6] = "-"; args[7] = "-"; } writer.print(MessageFormat.format(Constants.SERVER_ROW_SECTION, args)); // HTML Tail Section writer.print(Constants.HTML_TAIL_SECTION); // Finish up the response writer.flush(); writer.close(); } /** * Reload the web application at the specified context path. * * @see ManagerServlet#reload(PrintWriter, ContextName, StringManager) * * @param cn Name of the application to be restarted * @param smClient StringManager for the client's locale * @return message String */ protected String reload(ContextName cn, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.reload(printWriter, cn, smClient); return stringWriter.toString(); } /** * Undeploy the web application at the specified context path. * * @see ManagerServlet#undeploy(PrintWriter, ContextName, StringManager) * * @param cn Name of the application to be undeployed * @param smClient StringManager for the client's locale * @return message String */ protected String undeploy(ContextName cn, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.undeploy(printWriter, cn, smClient); return stringWriter.toString(); } /** * Display session information and invoke list. * * @see ManagerServlet#sessions(PrintWriter, ContextName, int, * StringManager) * * @param cn Name of the application to list session information * @param idle Expire all sessions with idle time &ge; idle for this context * @param smClient StringManager for the client's locale * @return message String */ protected String sessions(ContextName cn, int idle, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.sessions(printWriter, cn, idle, smClient); return stringWriter.toString(); } /** * Start the web application at the specified context path. * * @see ManagerServlet#start(PrintWriter, ContextName, StringManager) * * @param cn Name of the application to be started * @param smClient StringManager for the client's locale * @return message String */ protected String start(ContextName cn, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.start(printWriter, cn, smClient); return stringWriter.toString(); } /** * Stop the web application at the specified context path. * * @see ManagerServlet#stop(PrintWriter, ContextName, StringManager) * * @param cn Name of the application to be stopped * @param smClient StringManager for the client's locale * @return message String */ protected String stop(ContextName cn, StringManager smClient) { StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.stop(printWriter, cn, smClient); return stringWriter.toString(); } /** * Find potential memory leaks caused by web application reload. * * @see ManagerServlet#findleaks(boolean, PrintWriter, StringManager) * * @param smClient StringManager for the client's locale * * @return message String */ protected String findleaks(StringManager smClient) { StringBuilder msg = new StringBuilder(); StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); super.findleaks(false, printWriter, smClient); String writerText = stringWriter.toString(); if (writerText.length() > 0) { if (!writerText.startsWith("FAIL -")) { msg.append(smClient.getString( "htmlManagerServlet.findleaksList")); } msg.append(writerText); } else { msg.append(smClient.getString("htmlManagerServlet.findleaksNone")); } return msg.toString(); } protected void sslConnectorCiphers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("cipherList", getConnectorCiphers()); getServletContext().getRequestDispatcher( connectorCiphersJspPath).forward(request, response); } /** * @see javax.servlet.Servlet#getServletInfo() */ @Override public String getServletInfo() { return "HTMLManagerServlet, Copyright (c) 1999-2013, The Apache Software Foundation"; } /** * @see javax.servlet.GenericServlet#init() */ @Override public void init() throws ServletException { super.init(); // Set our properties from the initialization parameters String value = null; value = getServletConfig().getInitParameter("showProxySessions"); showProxySessions = Boolean.parseBoolean(value); } // ------------------------------------------------ Sessions administration /** * * Extract the expiration request parameter * * @param cn Name of the application from which to expire sessions * @param req * @param smClient StringManager for the client's locale */ protected String expireSessions(ContextName cn, HttpServletRequest req, StringManager smClient) { int idle = -1; String idleParam = req.getParameter("idle"); if (idleParam != null) { try { idle = Integer.parseInt(idleParam); } catch (NumberFormatException e) { log("Could not parse idle parameter to an int: " + idleParam); } } return sessions(cn, idle, smClient); } /** * * @param req * @param resp * @param smClient StringManager for the client's locale * @throws ServletException * @throws IOException */ protected void doSessions(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { req.setAttribute("path", cn.getPath()); req.setAttribute("version", cn.getVersion()); String action = req.getParameter("action"); if (debug >= 1) { log("sessions: Session action '" + action + "' for web application '" + cn.getDisplayName() + "'"); } if ("sessionDetail".equals(action)) { String sessionId = req.getParameter("sessionId"); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } else if ("invalidateSessions".equals(action)) { String[] sessionIds = req.getParameterValues("sessionIds"); int i = invalidateSessions(cn, sessionIds, smClient); req.setAttribute(APPLICATION_MESSAGE, "" + i + " sessions invalidated."); } else if ("removeSessionAttribute".equals(action)) { String sessionId = req.getParameter("sessionId"); String name = req.getParameter("attributeName"); boolean removed = removeSessionAttribute(cn, sessionId, name, smClient); String outMessage = removed ? "Session attribute '" + name + "' removed." : "Session did not contain any attribute named '" + name + "'"; req.setAttribute(APPLICATION_MESSAGE, outMessage); displaySessionDetailPage(req, resp, cn, sessionId, smClient); return; } // else displaySessionsListPage(cn, req, resp, smClient); } protected List<Session> getSessionsForName(ContextName cn, StringManager smClient) { if ((cn == null) || !(cn.getPath().startsWith("/") || cn.getPath().equals(""))) { String path = null; if (cn != null) { path = cn.getPath(); } throw new IllegalArgumentException(smClient.getString( "managerServlet.invalidPath", RequestUtil.filter(path))); } Context ctxt = (Context) host.findChild(cn.getName()); if (null == ctxt) { throw new IllegalArgumentException(smClient.getString( "managerServlet.noContext", RequestUtil.filter(cn.getDisplayName()))); } Manager manager = ctxt.getManager(); List<Session> sessions = new ArrayList<>(); sessions.addAll(Arrays.asList(manager.findSessions())); if (manager instanceof DistributedManager && showProxySessions) { // Add dummy proxy sessions Set<String> sessionIds = ((DistributedManager) manager).getSessionIdsFull(); // Remove active (primary and backup) session IDs from full list for (Session session : sessions) { sessionIds.remove(session.getId()); } // Left with just proxy sessions - add them for (String sessionId : sessionIds) { sessions.add(new DummyProxySession(sessionId)); } } return sessions; } protected Session getSessionForNameAndId(ContextName cn, String id, StringManager smClient) { List<Session> sessions = getSessionsForName(cn, smClient); if (sessions == null || sessions.isEmpty()) return null; for(Session session : sessions) { if (session.getId().equals(id)) { return session; } } return null; } /** * * @param cn Name of the application for which the sessions will be listed * @param req * @param resp * @param smClient StringManager for the client's locale * @throws ServletException * @throws IOException */ protected void displaySessionsListPage(ContextName cn, HttpServletRequest req, HttpServletResponse resp, StringManager smClient) throws ServletException, IOException { List<Session> sessions = getSessionsForName(cn, smClient); String sortBy = req.getParameter("sort"); String orderBy = null; if (null != sortBy && !"".equals(sortBy.trim())) { Comparator<Session> comparator = getComparator(sortBy); if (comparator != null) { orderBy = req.getParameter("order"); if ("DESC".equalsIgnoreCase(orderBy)) { comparator = new ReverseComparator(comparator); orderBy = "ASC"; } else { orderBy = "DESC"; } try { Collections.sort(sessions, comparator); } catch (IllegalStateException ise) { // at least 1 of the sessions is invalidated req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated"); } } else { log("WARNING: unknown sort order: " + sortBy); } } // keep sort order req.setAttribute("sort", sortBy); req.setAttribute("order", orderBy); req.setAttribute("activeSessions", sessions); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp); } /** * * @param req * @param resp * @param smClient StringManager for the client's locale * @throws ServletException * @throws IOException */ protected void displaySessionDetailPage(HttpServletRequest req, HttpServletResponse resp, ContextName cn, String sessionId, StringManager smClient) throws ServletException, IOException { Session session = getSessionForNameAndId(cn, sessionId, smClient); //strong>NOTE</strong> - This header will be overridden // automatically if a <code>RequestDispatcher.forward()</code> call is // ultimately invoked. resp.setHeader("Pragma", "No-cache"); // HTTP 1.0 resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1 resp.setDateHeader("Expires", 0); // 0 means now req.setAttribute("currentSession", session); getServletContext().getRequestDispatcher(resp.encodeURL(sessionDetailJspPath)).include(req, resp); } /** * Invalidate HttpSessions * @param cn Name of the application for which sessions are to be * invalidated * @param sessionIds * @param smClient StringManager for the client's locale * @return number of invalidated sessions * @throws IOException */ protected int invalidateSessions(ContextName cn, String[] sessionIds, StringManager smClient) throws IOException { if (null == sessionIds) { return 0; } int nbAffectedSessions = 0; for (int i = 0; i < sessionIds.length; ++i) { String sessionId = sessionIds[i]; HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't invalidate null session " + sessionId); } continue; } try { session.invalidate(); ++nbAffectedSessions; if (debug >= 1) { log("Invalidating session id " + sessionId); } } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't invalidate already invalidated session id " + sessionId); } } } return nbAffectedSessions; } /** * Removes an attribute from an HttpSession * @param cn Name of the application hosting the session from which the * attribute is to be removed * @param sessionId * @param attributeName * @param smClient StringManager for the client's locale * @return true if there was an attribute removed, false otherwise * @throws IOException */ protected boolean removeSessionAttribute(ContextName cn, String sessionId, String attributeName, StringManager smClient) throws IOException { HttpSession session = getSessionForNameAndId(cn, sessionId, smClient).getSession(); if (null == session) { // Shouldn't happen, but let's play nice... if (debug >= 1) { log("WARNING: can't remove attribute '" + attributeName + "' for null session " + sessionId); } return false; } boolean wasPresent = (null != session.getAttribute(attributeName)); try { session.removeAttribute(attributeName); } catch (IllegalStateException ise) { if (debug >= 1) { log("Can't remote attribute '" + attributeName + "' for invalidated session id " + sessionId); } } return wasPresent; } protected Comparator<Session> getComparator(String sortBy) { Comparator<Session> comparator = null; if ("CreationTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getCreationTime()); } }; } else if ("id".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return session.getId(); } }; } else if ("LastAccessedTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(session.getLastAccessedTime()); } }; } else if ("MaxInactiveInterval".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Integer>() { @Override public Comparable<Integer> getComparableObject(Session session) { return Integer.valueOf(session.getMaxInactiveInterval()); } }; } else if ("new".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Boolean>() { @Override public Comparable<Boolean> getComparableObject(Session session) { return Boolean.valueOf(session.getSession().isNew()); } }; } else if ("locale".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return JspHelper.guessDisplayLocaleFromSession(session); } }; } else if ("user".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<String>() { @Override public Comparable<String> getComparableObject(Session session) { return JspHelper.guessDisplayUserFromSession(session); } }; } else if ("UsedTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getUsedTimeForSession(session)); } }; } else if ("InactiveTime".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getInactiveTimeForSession(session)); } }; } else if ("TTL".equalsIgnoreCase(sortBy)) { comparator = new BaseSessionComparator<Date>() { @Override public Comparable<Date> getComparableObject(Session session) { return new Date(SessionUtils.getTTLForSession(session)); } }; } //TODO: complete this to TTL, etc. return comparator; } // ------------------------------------------------------ Private Constants // These HTML sections are broken in relatively small sections, because of // limited number of substitutions MessageFormat can process // (maximum of 10). private static final String APPS_HEADER_SECTION = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"6\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"header-left\"><small>{1}</small></td>\n" + " <td class=\"header-left\"><small>{2}</small></td>\n" + " <td class=\"header-center\"><small>{3}</small></td>\n" + " <td class=\"header-center\"><small>{4}</small></td>\n" + " <td class=\"header-left\"><small>{5}</small></td>\n" + " <td class=\"header-left\"><small>{6}</small></td>\n" + "</tr>\n"; private static final String APPS_ROW_DETAILS_SECTION = "<tr>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{0}</small></td>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{1}</small></td>\n" + " <td class=\"row-left\" bgcolor=\"{6}\" rowspan=\"2\"><small>{2}</small></td>\n" + " <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\"><small>{3}</small></td>\n" + " <td class=\"row-center\" bgcolor=\"{6}\" rowspan=\"2\">" + "<small><a href=\"{4}\">{5}</a></small></td>\n"; private static final String MANAGER_APP_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <small>\n" + " &nbsp;{1}&nbsp;\n" + " &nbsp;{3}&nbsp;\n" + " &nbsp;{5}&nbsp;\n" + " &nbsp;{7}&nbsp;\n" + " </small>\n" + " </td>\n" + "</tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STARTED_DEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " &nbsp;<small>{1}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{2}\">" + " <small><input type=\"submit\" value=\"{3}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{4}\">" + " <small><input type=\"submit\" value=\"{5}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{6}\">" + " <small><input type=\"submit\" value=\"{7}\"></small>" + " </form>\n" + " </td>\n" + " </tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STOPPED_DEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " <form class=\"inline\" method=\"POST\" action=\"{0}\">" + " <small><input type=\"submit\" value=\"{1}\"></small>" + " </form>\n" + " &nbsp;<small>{3}</small>&nbsp;\n" + " &nbsp;<small>{5}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{6}\">" + " <small><input type=\"submit\" value=\"{7}\"></small>" + " </form>\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String STARTED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " &nbsp;<small>{1}</small>&nbsp;\n" + " <form class=\"inline\" method=\"POST\" action=\"{2}\">" + " <small><input type=\"submit\" value=\"{3}\"></small>" + " </form>\n" + " <form class=\"inline\" method=\"POST\" action=\"{4}\">" + " <small><input type=\"submit\" value=\"{5}\"></small>" + " </form>\n" + " &nbsp;<small>{7}</small>&nbsp;\n" + " </td>\n" + " </tr><tr>\n" + " <td class=\"row-left\" bgcolor=\"{13}\">\n" + " <form method=\"POST\" action=\"{8}\">\n" + " <small>\n" + " &nbsp;<input type=\"submit\" value=\"{9}\">&nbsp;{10}&nbsp;<input type=\"text\" name=\"idle\" size=\"5\" value=\"{11}\">&nbsp;{12}&nbsp;\n" + " </small>\n" + " </form>\n" + " </td>\n" + "</tr>\n"; private static final String STOPPED_NONDEPLOYED_APPS_ROW_BUTTON_SECTION = " <td class=\"row-left\" bgcolor=\"{13}\" rowspan=\"2\">\n" + " <form class=\"inline\" method=\"POST\" action=\"{0}\">" + " <small><input type=\"submit\" value=\"{1}\"></small>" + " </form>\n" + " &nbsp;<small>{3}</small>&nbsp;\n" + " &nbsp;<small>{5}</small>&nbsp;\n" + " &nbsp;<small>{7}</small>&nbsp;\n" + " </td>\n" + "</tr>\n<tr></tr>\n"; private static final String DEPLOY_SECTION = "</table>\n" + "<br>\n" + "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"2\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{2}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{3}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployPath\" size=\"20\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{4}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployConfig\" size=\"20\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{5}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"text\" name=\"deployWar\" size=\"40\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " &nbsp;\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{6}\">\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n"; private static final String UPLOAD_SECTION = "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{0}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{1}\" " + "enctype=\"multipart/form-data\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " <small>{2}</small>\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"file\" name=\"deployWar\" size=\"40\">\n" + " </td>\n" + "</tr>\n" + "<tr>\n" + " <td class=\"row-right\">\n" + " &nbsp;\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{3}\">\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</table>\n" + "<br>\n" + "\n"; private static final String DIAGNOSTICS_SECTION = "<table border=\"1\" cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td colspan=\"2\" class=\"title\">{0}</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{1}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{2}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{4}\">\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <small>{3}</small>\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\" class=\"header-left\"><small>{5}</small></td>\n" + "</tr>\n" + "<tr>\n" + " <td colspan=\"2\">\n" + "<form method=\"post\" action=\"{6}\">\n" + "<table cellspacing=\"0\" cellpadding=\"3\">\n" + "<tr>\n" + " <td class=\"row-left\">\n" + " <input type=\"submit\" value=\"{7}\">\n" + " </td>\n" + " <td class=\"row-left\">\n" + " <small>{8}</small>\n" + " </td>\n" + "</tr>\n" + "</table>\n" + "</form>\n" + "</td>\n" + "</tr>\n" + "</table>\n" + "<br>"; }
54,702
Bug 54702 File descriptor leak at web.xml loading
Hello I think I've found a file descriptor leak in file /tomcat/trunk/java/org/apache/catalina/startup/ContextConfig.java (method getGlobalWebXmlSource). A stream is from file "web.xml" is not closed. private WebXml getDefaultWebXmlFragment() { ... 1284 InputSource globalWebXml = getGlobalWebXmlSource(); ... 1337 // Parse global web.xml if present 1338 if (globalWebXml == null) { 1339 // This is unusual enough to log 1340 log.info(sm.getString("contextConfig.defaultMissing")); 1341 } else { 1342 parseWebXml(globalWebXml, webXmlDefaultFragment, false); 1343 } Here is the full stack trace [java.io.FileInputStream.<init>(FileInputStream.java:109)] [org.apache.catalina.startup.ContextConfig.getWebXmlSource(ContextConfig.java:1837)] [org.apache.catalina.startup.ContextConfig.getGlobalWebXmlSource(ContextConfig.java:1744)] [org.apache.catalina.startup.ContextConfig.getDefaultWebXmlFragment(ContextConfig.java:1417)] [org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1253)] [org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)] [org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:369)] [org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)] [org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)] [org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5173)] [org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)] [org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:901)] [org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:877)] [org.apache.catalina.core.StandardHost.addChild(StandardHost.java:633)] [org.apache.catalina.startup.HostConfig.deployWAR(HostConfig.java:977)] [org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:542)] [org.apache.catalina.startup.HostConfig.check(HostConfig.java:1462)] [sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)] [sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)] [sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)] [java.lang.reflect.Method.invoke(Method.java:597)] [org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:301)] [com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:836)] [com.sun.jmx.mbeanserver.JmxMBeanServer.invoke(JmxMBeanServer.java:761)] [org.apache.catalina.manager.ManagerServlet.check(ManagerServlet.java:1445)] [org.apache.catalina.manager.HTMLManagerServlet.upload(HTMLManagerServlet.java:301)] [org.apache.catalina.manager.HTMLManagerServlet.doPost(HTMLManagerServlet.java:208)] [javax.servlet.http.HttpServlet.service(HttpServlet.java:647)] [javax.servlet.http.HttpServlet.service(HttpServlet.java:728)] [org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)] [org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)] [org.apache.catalina.filters.CsrfPreventionFilter.doFilter(CsrfPreventionFilter.java:213)] [org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)] [org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)] [org.apache.catalina.filters.SetCharacterEncodingFilter.doFilter(SetCharacterEncodingFilter.java:108)] [org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)] [org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)] [org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)] [org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)] [org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:581)] [org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)] [org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)] [org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:931)] [org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)] [org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)] [org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)] [org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)] [org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1822)] [java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)] [java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)] [java.lang.Thread.run(Thread.java:662)]
resolved fixed
7c88af9
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-15T13:57:19Z
2013-03-15T12: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.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.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; 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.StandardContext; import org.apache.catalina.core.StandardHost; import org.apache.catalina.deploy.ErrorPage; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.deploy.FilterMap; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.deploy.ServletDef; 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.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; /** * The list of JARs that will be skipped when scanning a web application * for JARs. This means the JAR will not be scanned for web fragments, SCIs, * annotations or classes that match @HandlesTypes. */ private static final Set<String> pluggabilityJarsToSkip = new HashSet<>(); 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; // Load the list of JARS to skip addJarsToSkip(Constants.DEFAULT_JARS_TO_SKIP); addJarsToSkip(Constants.PLUGGABILITY_JARS_TO_SKIP); } private static void addJarsToSkip(String systemPropertyName) { String jarList = System.getProperty(systemPropertyName); if (jarList != null) { StringTokenizer tokenizer = new StringTokenizer(jarList, ","); while (tokenizer.hasMoreElements()) { pluggabilityJarsToSkip.add(tokenizer.nextToken()); } } } /** * 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; /** * 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) { String docBase = context.getDocBase(); context.setDocBase(originalDocBase); originalDocBase = docBase; } } else if (event.getType().equals(Lifecycle.CONFIGURE_STOP_EVENT)) { if (originalDocBase != null) { String docBase = context.getDocBase(); context.setDocBase(originalDocBase); originalDocBase = docBase; } 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()); stream = contextXml.openStream(); } 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() && (docBase.startsWith(host.getAppBaseFile().getPath())); } 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; } if (originalDocBase == null) { originalDocBase = docBase; } else { docBase = originalDocBase; } 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(); File file = null; if (originalDocBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) { file = new File(System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase + ".war"); } else { file = new File(System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase); } if (log.isDebugEnabled()) { log.debug("Anti locking context[" + context.getName() + "] setting docBase to " + file); } // Cleanup just in case an old deployment is lying around ExpandWar.delete(file); if (ExpandWar.copy(docBaseFile, file)) { context.setDocBase(file.getAbsolutePath()); } } } /** * 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()); try { fixDocBase(); } catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); } } /** * Process a "before start" event for this Context. */ protected synchronized void beforeStart() { 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 Host host = (Host) context.getParent(); String docBase = context.getDocBase(); if ((docBase != null) && (originalDocBase != null)) { File docBaseFile = new File(docBase); if (!docBaseFile.isAbsolute()) { docBaseFile = new File(host.getAppBaseFile(), docBase); } // No need to log failure - it is expected in this case ExpandWar.delete(docBaseFile, 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 // If the JARs have a web-fragment.xml it will be parsed at this // point. 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) { webXml.configureContext(context); } } else { webXml.merge(defaults); convertJsps(webXml); webXml.configureContext(context); } // 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 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; } 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(); } } /** * 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(context.getServletContext(), context.getLoader().getClassLoader(), callback, pluggabilityJarsToSkip); return callback.getFragments(); } protected void processAnnotations(Set<WebXml> fragments, boolean handlesTypesOnly) { for(WebXml fragment : fragments) { 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) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); try { 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 (is != null) { try { is.close(); } catch (IOException ioe) { // Ignore } } 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) 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); } } finally { if (stream != null) { try { stream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } 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; } } }
54,631
Bug 54631 @PathParam is not working with @OnMessage
I have defined server end-point as: @ServerEndpoint(value = "/ws/{mid}/{rid}/{uid}") When using @PathParam with @OnMessage, values are null. Other annotations like @OnOpen and @OnClose print values specified in URL. @OnMessage public void onTextMessage(@PathParam("mid") Long mid, @PathParam("rid") Integer rid, @PathParam("uid") Long uid, Session session, String message, boolean pair) { log.debug("[TEXT]" + " : " + mid + " : " + rid + " : " + uid + message + " : " + session.getRequestURI()); }
resolved fixed
7fd7279
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-15T20:41:58Z
2013-03-04T09:40:00Z
test/org/apache/tomcat/websocket/pojo/TestPojoMethodMapping.java
54,712
Bug 54712 Prefer Locale.ENGLISH over Locale.US for case conversion
null
resolved fixed
dc16474
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T14:07:25Z
2013-03-17T17:06:40Z
java/org/apache/catalina/connector/Connector.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.net.InetAddress; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Locale; import javax.management.ObjectName; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Service; import org.apache.catalina.core.AprLifecycleListener; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.coyote.Adapter; import org.apache.coyote.ProtocolHandler; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.IntrospectionUtils; import org.apache.tomcat.util.res.StringManager; /** * Implementation of a Coyote connector. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class Connector extends LifecycleMBeanBase { private static final Log log = LogFactory.getLog(Connector.class); /** * Alternate flag to enable recycling of facades. */ public static final boolean RECYCLE_FACADES = Boolean.valueOf(System.getProperty("org.apache.catalina.connector.RECYCLE_FACADES", "false")).booleanValue(); // ------------------------------------------------------------ Constructor public Connector() { this(null); } public Connector(String protocol) { setProtocol(protocol); // Instantiate protocol handler ProtocolHandler p = null; try { Class<?> clazz = Class.forName(protocolHandlerClassName); p = (ProtocolHandler) clazz.newInstance(); } catch (Exception e) { log.error(sm.getString( "coyoteConnector.protocolHandlerInstantiationFailed"), e); } finally { this.protocolHandler = p; } } // ----------------------------------------------------- Instance Variables /** * The <code>Service</code> we are associated with (if any). */ protected Service service = null; /** * Do we allow TRACE ? */ protected boolean allowTrace = false; /** * Default timeout for asynchronous requests (ms). */ protected long asyncTimeout = 10000; /** * The "enable DNS lookups" flag for this Connector. */ protected boolean enableLookups = false; /* * Is generation of X-Powered-By response header enabled/disabled? */ protected boolean xpoweredBy = false; /** * The port number on which we listen for requests. */ protected int port = -1; /** * The server name to which we should pretend requests to this Connector * were directed. This is useful when operating Tomcat behind a proxy * server, so that redirects get constructed accurately. If not specified, * the server name included in the <code>Host</code> header is used. */ protected String proxyName = null; /** * The server port to which we should pretend requests to this Connector * were directed. This is useful when operating Tomcat behind a proxy * server, so that redirects get constructed accurately. If not specified, * the port number specified by the <code>port</code> property is used. */ protected int proxyPort = 0; /** * The redirect port for non-SSL to SSL redirects. */ protected int redirectPort = 443; /** * The request scheme that will be set on all requests received * through this connector. */ protected String scheme = "http"; /** * The secure connection flag that will be set on all requests received * through this connector. */ protected boolean secure = false; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The maximum number of parameters (GET plus POST) which will be * automatically parsed by the container. 10000 by default. A value of less * than 0 means no limit. */ protected int maxParameterCount = 10000; /** * Maximum size of a POST which will be automatically parsed by the * container. 2MB by default. */ protected int maxPostSize = 2 * 1024 * 1024; /** * Maximum size of a POST which will be saved by the container * during authentication. 4kB by default */ protected int maxSavePostSize = 4 * 1024; /** * Comma-separated list of HTTP methods that will be parsed according * to POST-style rules for application/x-www-form-urlencoded request bodies. */ protected String parseBodyMethods = "POST"; /** * A Set of methods determined by {@link #parseBodyMethods}. */ protected HashSet<String> parseBodyMethodsSet; /** * Flag to use IP-based virtual hosting. */ protected boolean useIPVHosts = false; /** * Coyote Protocol handler class name. * Defaults to the Coyote HTTP/1.1 protocolHandler. */ protected String protocolHandlerClassName = "org.apache.coyote.http11.Http11NioProtocol"; /** * Coyote protocol handler. */ protected final ProtocolHandler protocolHandler; /** * Coyote adapter. */ protected Adapter adapter = null; /** * URI encoding. */ protected String URIEncoding = null; protected String URIEncodingLower = null; /** * URI encoding as body. */ protected boolean useBodyEncodingForURI = false; protected static final HashMap<String,String> replacements = new HashMap<>(); static { replacements.put("acceptCount", "backlog"); replacements.put("connectionLinger", "soLinger"); replacements.put("connectionTimeout", "soTimeout"); replacements.put("rootFile", "rootfile"); } // ------------------------------------------------------------- Properties /** * Return a configured property. */ public Object getProperty(String name) { String repl = name; if (replacements.get(name) != null) { repl = replacements.get(name); } return IntrospectionUtils.getProperty(protocolHandler, repl); } /** * Set a configured property. */ public boolean setProperty(String name, String value) { String repl = name; if (replacements.get(name) != null) { repl = replacements.get(name); } return IntrospectionUtils.setProperty(protocolHandler, repl, value); } /** * Return a configured property. */ public Object getAttribute(String name) { return getProperty(name); } /** * Set a configured property. */ public void setAttribute(String name, Object value) { setProperty(name, String.valueOf(value)); } /** * Return the <code>Service</code> with which we are associated (if any). */ public Service getService() { return (this.service); } /** * Set the <code>Service</code> with which we are associated (if any). * * @param service The service that owns this Engine */ public void setService(Service service) { this.service = service; } /** * True if the TRACE method is allowed. Default value is "false". */ public boolean getAllowTrace() { return (this.allowTrace); } /** * Set the allowTrace flag, to disable or enable the TRACE HTTP method. * * @param allowTrace The new allowTrace flag */ public void setAllowTrace(boolean allowTrace) { this.allowTrace = allowTrace; setProperty("allowTrace", String.valueOf(allowTrace)); } /** * Return the default timeout for async requests in ms. */ public long getAsyncTimeout() { return asyncTimeout; } /** * Set the default timeout for async requests. * * @param asyncTimeout The new timeout in ms. */ public void setAsyncTimeout(long asyncTimeout) { this.asyncTimeout= asyncTimeout; setProperty("asyncTimeout", String.valueOf(asyncTimeout)); } /** * Return the "enable DNS lookups" flag. */ public boolean getEnableLookups() { return (this.enableLookups); } /** * Set the "enable DNS lookups" flag. * * @param enableLookups The new "enable DNS lookups" flag value */ public void setEnableLookups(boolean enableLookups) { this.enableLookups = enableLookups; setProperty("enableLookups", String.valueOf(enableLookups)); } /** * Return the maximum number of headers that are allowed by the container. A * value of less than 0 means no limit. */ public int getMaxHeaderCount() { return ((Integer) getProperty("maxHeaderCount")).intValue(); } /** * Set the maximum number of headers in a request that are allowed by the * container. A value of less than 0 means no limit. * * @param maxHeaderCount The new setting */ public void setMaxHeaderCount(int maxHeaderCount) { setProperty("maxHeaderCount", String.valueOf(maxHeaderCount)); } /** * Return the maximum number of parameters (GET plus POST) that will be * automatically parsed by the container. A value of less than 0 means no * limit. */ public int getMaxParameterCount() { return maxParameterCount; } /** * Set the maximum number of parameters (GET plus POST) that will be * automatically parsed by the container. A value of less than 0 means no * limit. * * @param maxParameterCount The new setting */ public void setMaxParameterCount(int maxParameterCount) { this.maxParameterCount = maxParameterCount; } /** * Return the maximum size of a POST which will be automatically * parsed by the container. */ public int getMaxPostSize() { return (maxPostSize); } /** * Set the maximum size of a POST which will be automatically * parsed by the container. * * @param maxPostSize The new maximum size in bytes of a POST which will * be automatically parsed by the container */ public void setMaxPostSize(int maxPostSize) { this.maxPostSize = maxPostSize; } /** * Return the maximum size of a POST which will be saved by the container * during authentication. */ public int getMaxSavePostSize() { return (maxSavePostSize); } /** * Set the maximum size of a POST which will be saved by the container * during authentication. * * @param maxSavePostSize The new maximum size in bytes of a POST which will * be saved by the container during authentication. */ public void setMaxSavePostSize(int maxSavePostSize) { this.maxSavePostSize = maxSavePostSize; setProperty("maxSavePostSize", String.valueOf(maxSavePostSize)); } public String getParseBodyMethods() { return this.parseBodyMethods; } public void setParseBodyMethods(String methods) { HashSet<String> methodSet = new HashSet<>(); if( null != methods ) { methodSet.addAll(Arrays.asList(methods.split("\\s*,\\s*"))); } if( methodSet.contains("TRACE") ) { throw new IllegalArgumentException(sm.getString("coyoteConnector.parseBodyMethodNoTrace")); } this.parseBodyMethods = methods; this.parseBodyMethodsSet = methodSet; } protected boolean isParseBodyMethod(String method) { return parseBodyMethodsSet.contains(method); } /** * Return the port number on which this connector is configured to listen * for requests. The special value of 0 means select a random free port * when the socket is bound. */ public int getPort() { return (this.port); } /** * Set the port number on which we listen for requests. * * @param port The new port number */ public void setPort(int port) { this.port = port; setProperty("port", String.valueOf(port)); } /** * Return the port number on which this connector is listening to requests. * If the special value for {@link #getPort} of zero is used then this method * will report the actual port bound. */ public int getLocalPort() { return ((Integer) getProperty("localPort")).intValue(); } /** * Return the Coyote protocol handler in use. */ public String getProtocol() { if ("org.apache.coyote.http11.Http11NioProtocol".equals (getProtocolHandlerClassName()) || "org.apache.coyote.http11.Http11AprProtocol".equals (getProtocolHandlerClassName())) { return "HTTP/1.1"; } else if ("org.apache.coyote.ajp.AjpNioProtocol".equals (getProtocolHandlerClassName()) || "org.apache.coyote.ajp.AjpAprProtocol".equals (getProtocolHandlerClassName())) { return "AJP/1.3"; } return getProtocolHandlerClassName(); } /** * Set the Coyote protocol which will be used by the connector. * * @param protocol The Coyote protocol name */ public void setProtocol(String protocol) { if (AprLifecycleListener.isAprAvailable()) { if ("HTTP/1.1".equals(protocol)) { setProtocolHandlerClassName ("org.apache.coyote.http11.Http11AprProtocol"); } else if ("AJP/1.3".equals(protocol)) { setProtocolHandlerClassName ("org.apache.coyote.ajp.AjpAprProtocol"); } else if (protocol != null) { setProtocolHandlerClassName(protocol); } else { setProtocolHandlerClassName ("org.apache.coyote.http11.Http11AprProtocol"); } } else { if ("HTTP/1.1".equals(protocol)) { setProtocolHandlerClassName ("org.apache.coyote.http11.Http11NioProtocol"); } else if ("AJP/1.3".equals(protocol)) { setProtocolHandlerClassName ("org.apache.coyote.ajp.AjpNioProtocol"); } else if (protocol != null) { setProtocolHandlerClassName(protocol); } } } /** * Return the class name of the Coyote protocol handler in use. */ public String getProtocolHandlerClassName() { return (this.protocolHandlerClassName); } /** * Set the class name of the Coyote protocol handler which will be used * by the connector. * * @param protocolHandlerClassName The new class name */ public void setProtocolHandlerClassName(String protocolHandlerClassName) { this.protocolHandlerClassName = protocolHandlerClassName; } /** * Return the protocol handler associated with the connector. */ public ProtocolHandler getProtocolHandler() { return (this.protocolHandler); } /** * Return the proxy server name for this Connector. */ public String getProxyName() { return (this.proxyName); } /** * Set the proxy server name for this Connector. * * @param proxyName The new proxy server name */ public void setProxyName(String proxyName) { if(proxyName != null && proxyName.length() > 0) { this.proxyName = proxyName; setProperty("proxyName", proxyName); } else { this.proxyName = null; } } /** * Return the proxy server port for this Connector. */ public int getProxyPort() { return (this.proxyPort); } /** * Set the proxy server port for this Connector. * * @param proxyPort The new proxy server port */ public void setProxyPort(int proxyPort) { this.proxyPort = proxyPort; setProperty("proxyPort", String.valueOf(proxyPort)); } /** * Return the port number to which a request should be redirected if * it comes in on a non-SSL port and is subject to a security constraint * with a transport guarantee that requires SSL. */ public int getRedirectPort() { return (this.redirectPort); } /** * Set the redirect port number. * * @param redirectPort The redirect port number (non-SSL to SSL) */ public void setRedirectPort(int redirectPort) { this.redirectPort = redirectPort; setProperty("redirectPort", String.valueOf(redirectPort)); } /** * Return the scheme that will be assigned to requests received * through this connector. Default value is "http". */ public String getScheme() { return (this.scheme); } /** * Set the scheme that will be assigned to requests received through * this connector. * * @param scheme The new scheme */ public void setScheme(String scheme) { this.scheme = scheme; } /** * Return the secure connection flag that will be assigned to requests * received through this connector. Default value is "false". */ public boolean getSecure() { return (this.secure); } /** * Set the secure connection flag that will be assigned to requests * received through this connector. * * @param secure The new secure connection flag */ public void setSecure(boolean secure) { this.secure = secure; setProperty("secure", Boolean.toString(secure)); } /** * Return the character encoding to be used for the URI using the original * case. */ public String getURIEncoding() { return this.URIEncoding; } /** * Return the character encoding to be used for the URI using lower case. */ public String getURIEncodingLower() { return this.URIEncodingLower; } /** * Set the URI encoding to be used for the URI. * * @param URIEncoding The new URI character encoding. */ public void setURIEncoding(String URIEncoding) { this.URIEncoding = URIEncoding; if (URIEncoding == null) { URIEncodingLower = null; } else { this.URIEncodingLower = URIEncoding.toLowerCase(Locale.US); } setProperty("uRIEncoding", URIEncoding); } /** * Return the true if the entity body encoding should be used for the URI. */ public boolean getUseBodyEncodingForURI() { return (this.useBodyEncodingForURI); } /** * Set if the entity body encoding should be used for the URI. * * @param useBodyEncodingForURI The new value for the flag. */ public void setUseBodyEncodingForURI(boolean useBodyEncodingForURI) { this.useBodyEncodingForURI = useBodyEncodingForURI; setProperty ("useBodyEncodingForURI", String.valueOf(useBodyEncodingForURI)); } /** * Indicates whether the generation of an X-Powered-By response header for * servlet-generated responses is enabled or disabled for this Connector. * * @return true if generation of X-Powered-By response header is enabled, * false otherwise */ public boolean getXpoweredBy() { return xpoweredBy; } /** * Enables or disables the generation of an X-Powered-By header (with value * Servlet/2.5) for all servlet-generated responses returned by this * Connector. * * @param xpoweredBy true if generation of X-Powered-By response header is * to be enabled, false otherwise */ public void setXpoweredBy(boolean xpoweredBy) { this.xpoweredBy = xpoweredBy; setProperty("xpoweredBy", String.valueOf(xpoweredBy)); } /** * Enable the use of IP-based virtual hosting. * * @param useIPVHosts <code>true</code> if Hosts are identified by IP, * <code>false/code> if Hosts are identified by name. */ public void setUseIPVHosts(boolean useIPVHosts) { this.useIPVHosts = useIPVHosts; setProperty("useIPVHosts", String.valueOf(useIPVHosts)); } /** * Test if IP-based virtual hosting is enabled. */ public boolean getUseIPVHosts() { return useIPVHosts; } public String getExecutorName() { Object obj = protocolHandler.getExecutor(); if (obj instanceof org.apache.catalina.Executor) { return ((org.apache.catalina.Executor) obj).getName(); } return "Internal"; } // --------------------------------------------------------- Public Methods /** * Create (or allocate) and return a Request object suitable for * specifying the contents of a Request to the responsible Container. */ public Request createRequest() { Request request = new Request(); request.setConnector(this); return (request); } /** * Create (or allocate) and return a Response object suitable for * receiving the contents of a Response from the responsible Container. */ public Response createResponse() { Response response = new Response(); response.setConnector(this); return (response); } protected String createObjectNameKeyProperties(String type) { Object addressObj = getProperty("address"); StringBuilder sb = new StringBuilder("type="); sb.append(type); sb.append(",port="); int port = getPort(); if (port > 0) { sb.append(getPort()); } else { sb.append("auto-"); sb.append(getProperty("nameIndex")); } String address = ""; if (addressObj instanceof InetAddress) { address = ((InetAddress) addressObj).getHostAddress(); } else if (addressObj != null) { address = addressObj.toString(); } if (address.length() > 0) { sb.append(",address="); sb.append(ObjectName.quote(address)); } return sb.toString(); } /** * Pause the connector. */ public void pause() { try { protocolHandler.pause(); } catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerPauseFailed"), e); } } /** * Pause the connector. */ public void resume() { try { protocolHandler.resume(); } catch (Exception e) { log.error(sm.getString ("coyoteConnector.protocolHandlerResumeFailed"), e); } } @Override protected void initInternal() throws LifecycleException { super.initInternal(); // Initialize adapter adapter = new CoyoteAdapter(this); protocolHandler.setAdapter(adapter); // Make sure parseBodyMethodsSet has a default if( null == parseBodyMethodsSet ) { setParseBodyMethods(getParseBodyMethods()); } if (protocolHandler.isAprRequired() && !AprLifecycleListener.isAprAvailable()) { throw new LifecycleException( sm.getString("coyoteConnector.protocolHandlerNoApr", getProtocolHandlerClassName())); } try { protocolHandler.init(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerInitializationFailed"), e); } } /** * Begin processing requests via this Connector. * * @exception LifecycleException if a fatal startup error occurs */ @Override protected void startInternal() throws LifecycleException { // Validate settings before starting if (getPort() < 0) { throw new LifecycleException(sm.getString( "coyoteConnector.invalidPort", Integer.valueOf(getPort()))); } setState(LifecycleState.STARTING); try { protocolHandler.start(); } catch (Exception e) { String errPrefix = ""; if(this.service != null) { errPrefix += "service.getName(): \"" + this.service.getName() + "\"; "; } throw new LifecycleException (errPrefix + " " + sm.getString ("coyoteConnector.protocolHandlerStartFailed"), e); } } /** * Terminate processing requests via this Connector. * * @exception LifecycleException if a fatal shutdown error occurs */ @Override protected void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); try { protocolHandler.stop(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerStopFailed"), e); } } @Override protected void destroyInternal() throws LifecycleException { try { protocolHandler.destroy(); } catch (Exception e) { throw new LifecycleException (sm.getString ("coyoteConnector.protocolHandlerDestroyFailed"), e); } if (getService() != null) { getService().removeConnector(this); } super.destroyInternal(); } /** * Provide a useful toString() implementation as it may be used when logging * Lifecycle errors to identify the component. */ @Override public String toString() { // Not worth caching this right now StringBuilder sb = new StringBuilder("Connector["); sb.append(getProtocol()); sb.append('-'); int port = getPort(); if (port > 0) { sb.append(getPort()); } else { sb.append("auto-"); sb.append(getProperty("nameIndex")); } sb.append(']'); return sb.toString(); } // -------------------- JMX registration -------------------- @Override protected String getDomainInternal() { Service s = getService(); if (s == null) { return null; } else { return service.getDomain(); } } @Override protected String getObjectNameKeyProperties() { return createObjectNameKeyProperties("Connector"); } }
54,712
Bug 54712 Prefer Locale.ENGLISH over Locale.US for case conversion
null
resolved fixed
dc16474
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T14:07:25Z
2013-03-17T17:06:40Z
java/org/apache/tomcat/util/buf/B2CConverter.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.buf; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CoderResult; import java.nio.charset.CodingErrorAction; import java.util.HashMap; import java.util.Locale; import java.util.Map; import org.apache.tomcat.util.res.StringManager; /** * NIO based character decoder. */ public class B2CConverter { private static final StringManager sm = StringManager.getManager(Constants.Package); private static final Map<String, Charset> encodingToCharsetCache = new HashMap<>(); public static final Charset ISO_8859_1; public static final Charset UTF_8; // Protected so unit tests can use it protected static final int LEFTOVER_SIZE = 9; static { for (Charset charset: Charset.availableCharsets().values()) { encodingToCharsetCache.put( charset.name().toLowerCase(Locale.US), charset); for (String alias : charset.aliases()) { encodingToCharsetCache.put( alias.toLowerCase(Locale.US), charset); } } Charset iso88591 = null; Charset utf8 = null; try { iso88591 = getCharset("ISO-8859-1"); utf8 = getCharset("UTF-8"); } catch (UnsupportedEncodingException e) { // Impossible. All JVMs must support these. e.printStackTrace(); } ISO_8859_1 = iso88591; UTF_8 = utf8; } public static Charset getCharset(String enc) throws UnsupportedEncodingException { // Encoding names should all be ASCII String lowerCaseEnc = enc.toLowerCase(Locale.US); return getCharsetLower(lowerCaseEnc); } /** * Only to be used when it is known that the encoding name is in lower case. */ public static Charset getCharsetLower(String lowerCaseEnc) throws UnsupportedEncodingException { Charset charset = encodingToCharsetCache.get(lowerCaseEnc); if (charset == null) { // Pre-population of the cache means this must be invalid throw new UnsupportedEncodingException( sm.getString("b2cConverter.unknownEncoding", lowerCaseEnc)); } return charset; } private final CharsetDecoder decoder; private ByteBuffer bb = null; private CharBuffer cb = null; /** * Leftover buffer used for incomplete characters. */ private final ByteBuffer leftovers; public B2CConverter(String encoding) throws IOException { this(encoding, false); } public B2CConverter(String encoding, boolean replaceOnError) throws IOException { byte[] left = new byte[LEFTOVER_SIZE]; leftovers = ByteBuffer.wrap(left); CodingErrorAction action; if (replaceOnError) { action = CodingErrorAction.REPLACE; } else { action = CodingErrorAction.REPORT; } Charset charset = getCharset(encoding); // Special case. Use the Apache Harmony based UTF-8 decoder because it // - a) rejects invalid sequences that the JVM decoder does not // - b) fails faster for some invalid sequences if (charset.equals(UTF_8)) { decoder = new Utf8Decoder(); } else { decoder = charset.newDecoder(); } decoder.onMalformedInput(action); decoder.onUnmappableCharacter(action); } /** * Reset the decoder state. */ public void recycle() { decoder.reset(); leftovers.position(0); } /** * Convert the given bytes to characters. * * @param bc byte input * @param cc char output * @param endOfInput Is this all of the available data */ public void convert(ByteChunk bc, CharChunk cc, boolean endOfInput) throws IOException { if ((bb == null) || (bb.array() != bc.getBuffer())) { // Create a new byte buffer if anything changed bb = ByteBuffer.wrap(bc.getBuffer(), bc.getStart(), bc.getLength()); } else { // Initialize the byte buffer bb.limit(bc.getEnd()); bb.position(bc.getStart()); } if ((cb == null) || (cb.array() != cc.getBuffer())) { // Create a new char buffer if anything changed cb = CharBuffer.wrap(cc.getBuffer(), cc.getEnd(), cc.getBuffer().length - cc.getEnd()); } else { // Initialize the char buffer cb.limit(cc.getBuffer().length); cb.position(cc.getEnd()); } CoderResult result = null; // Parse leftover if any are present if (leftovers.position() > 0) { int pos = cb.position(); // Loop until one char is decoded or there is a decoder error do { leftovers.put(bc.substractB()); leftovers.flip(); result = decoder.decode(leftovers, cb, endOfInput); leftovers.position(leftovers.limit()); leftovers.limit(leftovers.array().length); } while (result.isUnderflow() && (cb.position() == pos)); if (result.isError() || result.isMalformed()) { result.throwException(); } bb.position(bc.getStart()); leftovers.position(0); } // Do the decoding and get the results into the byte chunk and the char // chunk result = decoder.decode(bb, cb, endOfInput); if (result.isError() || result.isMalformed()) { result.throwException(); } else if (result.isOverflow()) { // Propagate current positions to the byte chunk and char chunk, if // this continues the char buffer will get resized bc.setOffset(bb.position()); cc.setEnd(cb.position()); } else if (result.isUnderflow()) { // Propagate current positions to the byte chunk and char chunk bc.setOffset(bb.position()); cc.setEnd(cb.position()); // Put leftovers in the leftovers byte buffer if (bc.getLength() > 0) { leftovers.limit(leftovers.array().length); leftovers.position(bc.getLength()); bc.substract(leftovers.array(), 0, bc.getLength()); } } } }
54,712
Bug 54712 Prefer Locale.ENGLISH over Locale.US for case conversion
null
resolved fixed
dc16474
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T14:07:25Z
2013-03-17T17:06:40Z
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.US)); 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.US), value); } else { parameters.put(attribute.toLowerCase(Locale.US), ""); } 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,712
Bug 54712 Prefer Locale.ENGLISH over Locale.US for case conversion
null
resolved fixed
dc16474
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T14:07:25Z
2013-03-17T17:06:40Z
java/org/apache/tomcat/util/http/parser/MediaType.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.util.LinkedHashMap; import java.util.Locale; import java.util.Map; public class MediaType { private final String type; private final String subtype; private final LinkedHashMap<String,String> parameters; private final String charset; private volatile String noCharset; private volatile String withCharset; protected MediaType(String type, String subtype, LinkedHashMap<String,String> parameters) { this.type = type; this.subtype = subtype; this.parameters = parameters; String cs = parameters.get("charset"); if (cs != null && cs.length() > 0 && cs.charAt(0) == '"') { cs = HttpParser.unquote(cs); } this.charset = cs; } public String getType() { return type; } public String getSubtype() { return subtype; } public String getCharset() { return charset; } public int getParameterCount() { return parameters.size(); } public String getParameterValue(String parameter) { return parameters.get(parameter.toLowerCase(Locale.US)); } @Override public String toString() { if (withCharset == null) { synchronized (this) { if (withCharset == null) { StringBuilder result = new StringBuilder(); result.append(type); result.append('/'); result.append(subtype); for (Map.Entry<String, String> entry : parameters.entrySet()) { String value = entry.getValue(); if (value == null || value.length() == 0) { continue; } result.append(';'); // Workaround for Adobe Read 9 plug-in on IE bug // Can be removed after 26 June 2013 (EOL of Reader 9) // See BZ 53814 result.append(' '); result.append(entry.getKey()); result.append('='); result.append(value); } withCharset = result.toString(); } } } return withCharset; } public String toStringNoCharset() { if (noCharset == null) { synchronized (this) { if (noCharset == null) { StringBuilder result = new StringBuilder(); result.append(type); result.append('/'); result.append(subtype); for (Map.Entry<String, String> entry : parameters.entrySet()) { if (entry.getKey().equalsIgnoreCase("charset")) { continue; } result.append(';'); // Workaround for Adobe Read 9 plug-in on IE bug // Can be removed after 26 June 2013 (EOL of Reader 9) // See BZ 53814 result.append(' '); result.append(entry.getKey()); result.append('='); result.append(entry.getValue()); } noCharset = result.toString(); } } } return noCharset; } }
54,712
Bug 54712 Prefer Locale.ENGLISH over Locale.US for case conversion
null
resolved fixed
dc16474
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T14:07:25Z
2013-03-17T17:06:40Z
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.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.jdbc.pool; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * @author Filip Hanik * */ public class PoolProperties implements PoolConfiguration, Cloneable, Serializable { private static final long serialVersionUID = -8519283440854213745L; private static final Log log = LogFactory.getLog(PoolProperties.class); public static final int DEFAULT_MAX_ACTIVE = 100; protected static AtomicInteger poolCounter = new AtomicInteger(0); private volatile Properties dbProperties = new Properties(); private volatile String url = null; private volatile String driverClassName = null; private volatile Boolean defaultAutoCommit = null; private volatile Boolean defaultReadOnly = null; private volatile int defaultTransactionIsolation = DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION; private volatile String defaultCatalog = null; private volatile String connectionProperties; private volatile int initialSize = 10; private volatile int maxActive = DEFAULT_MAX_ACTIVE; private volatile int maxIdle = maxActive; private volatile int minIdle = initialSize; private volatile int maxWait = 30000; private volatile String validationQuery; private volatile String validatorClassName; private volatile Validator validator; private volatile boolean testOnBorrow = false; private volatile boolean testOnReturn = false; private volatile boolean testWhileIdle = false; private volatile int timeBetweenEvictionRunsMillis = 5000; private volatile int numTestsPerEvictionRun; private volatile int minEvictableIdleTimeMillis = 60000; private volatile boolean accessToUnderlyingConnectionAllowed = true; private volatile boolean removeAbandoned = false; private volatile int removeAbandonedTimeout = 60; private volatile boolean logAbandoned = false; private volatile String name = "Tomcat Connection Pool["+(poolCounter.addAndGet(1))+"-"+System.identityHashCode(PoolProperties.class)+"]"; private volatile String password; private volatile String username; private volatile long validationInterval = 30000; private volatile boolean jmxEnabled = true; private volatile String initSQL; private volatile boolean testOnConnect =false; private volatile String jdbcInterceptors=null; private volatile boolean fairQueue = true; private volatile boolean useEquals = true; private volatile int abandonWhenPercentageFull = 0; private volatile long maxAge = 0; private volatile boolean useLock = false; private volatile InterceptorDefinition[] interceptors = null; private volatile int suspectTimeout = 0; private volatile Object dataSource = null; private volatile String dataSourceJNDI = null; private volatile boolean alternateUsernameAllowed = false; private volatile boolean commitOnReturn = false; private volatile boolean rollbackOnReturn = false; private volatile boolean useDisposableConnectionFacade = true; private volatile boolean logValidationErrors = false; private volatile boolean propagateInterruptState = false; /** * {@inheritDoc} */ @Override public void setAbandonWhenPercentageFull(int percentage) { if (percentage<0) abandonWhenPercentageFull = 0; else if (percentage>100) abandonWhenPercentageFull = 100; else abandonWhenPercentageFull = percentage; } /** * {@inheritDoc} */ @Override public int getAbandonWhenPercentageFull() { return abandonWhenPercentageFull; } /** * {@inheritDoc} */ @Override public boolean isFairQueue() { return fairQueue; } /** * {@inheritDoc} */ @Override public void setFairQueue(boolean fairQueue) { this.fairQueue = fairQueue; } /** * {@inheritDoc} */ @Override public boolean isAccessToUnderlyingConnectionAllowed() { return accessToUnderlyingConnectionAllowed; } /** * {@inheritDoc} */ @Override public String getConnectionProperties() { return connectionProperties; } /** * {@inheritDoc} */ @Override public Properties getDbProperties() { return dbProperties; } /** * {@inheritDoc} */ @Override public Boolean isDefaultAutoCommit() { return defaultAutoCommit; } /** * {@inheritDoc} */ @Override public String getDefaultCatalog() { return defaultCatalog; } /** * {@inheritDoc} */ @Override public Boolean isDefaultReadOnly() { return defaultReadOnly; } /** * {@inheritDoc} */ @Override public int getDefaultTransactionIsolation() { return defaultTransactionIsolation; } /** * {@inheritDoc} */ @Override public String getDriverClassName() { return driverClassName; } /** * {@inheritDoc} */ @Override public int getInitialSize() { return initialSize; } /** * {@inheritDoc} */ @Override public boolean isLogAbandoned() { return logAbandoned; } /** * {@inheritDoc} */ @Override public int getMaxActive() { return maxActive; } /** * {@inheritDoc} */ @Override public int getMaxIdle() { return maxIdle; } /** * {@inheritDoc} */ @Override public int getMaxWait() { return maxWait; } /** * {@inheritDoc} */ @Override public int getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } /** * {@inheritDoc} */ @Override public int getMinIdle() { return minIdle; } /** * {@inheritDoc} */ @Override public String getName() { return name; } /** * {@inheritDoc} */ @Override public int getNumTestsPerEvictionRun() { return numTestsPerEvictionRun; } /** * {@inheritDoc} */ @Override public String getPassword() { return password; } /** * {@inheritDoc} */ @Override public String getPoolName() { return getName(); } /** * {@inheritDoc} */ @Override public boolean isRemoveAbandoned() { return removeAbandoned; } /** * {@inheritDoc} */ @Override public int getRemoveAbandonedTimeout() { return removeAbandonedTimeout; } /** * {@inheritDoc} */ @Override public boolean isTestOnBorrow() { return testOnBorrow; } /** * {@inheritDoc} */ @Override public boolean isTestOnReturn() { return testOnReturn; } /** * {@inheritDoc} */ @Override public boolean isTestWhileIdle() { return testWhileIdle; } /** * {@inheritDoc} */ @Override public int getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } /** * {@inheritDoc} */ @Override public String getUrl() { return url; } /** * {@inheritDoc} */ @Override public String getUsername() { return username; } /** * {@inheritDoc} */ @Override public String getValidationQuery() { return validationQuery; } /** * {@inheritDoc} */ @Override public String getValidatorClassName() { return validatorClassName; } /** * {@inheritDoc} */ @Override public Validator getValidator() { return validator; } /** * {@inheritDoc} */ @Override public void setValidator(Validator validator) { this.validator = validator; if (validator!=null) { this.validatorClassName = validator.getClass().getName(); } else { this.validatorClassName = null; } } /** * {@inheritDoc} */ @Override public long getValidationInterval() { return validationInterval; } /** * {@inheritDoc} */ @Override public String getInitSQL() { return initSQL; } /** * {@inheritDoc} */ @Override public boolean isTestOnConnect() { return testOnConnect; } /** * {@inheritDoc} */ @Override public String getJdbcInterceptors() { return jdbcInterceptors; } /** * {@inheritDoc} */ @Override public InterceptorDefinition[] getJdbcInterceptorsAsArray() { if (interceptors == null) { if (jdbcInterceptors==null) { interceptors = new InterceptorDefinition[0]; } else { String[] interceptorValues = jdbcInterceptors.split(";"); InterceptorDefinition[] definitions = new InterceptorDefinition[interceptorValues.length+1]; //always add the trap interceptor to the mix definitions[0] = new InterceptorDefinition(TrapException.class); for (int i=0; i<interceptorValues.length; i++) { int propIndex = interceptorValues[i].indexOf("("); int endIndex = interceptorValues[i].indexOf(")"); if (propIndex<0 || endIndex<0 || endIndex <= propIndex) { definitions[i+1] = new InterceptorDefinition(interceptorValues[i].trim()); } else { String name = interceptorValues[i].substring(0,propIndex).trim(); definitions[i+1] = new InterceptorDefinition(name); String propsAsString = interceptorValues[i].substring(propIndex+1, interceptorValues[i].length()-1); String[] props = propsAsString.split(","); for (int j=0; j<props.length; j++) { int pidx = props[j].indexOf("="); String propName = props[j].substring(0,pidx).trim(); String propValue = props[j].substring(pidx+1).trim(); definitions[i+1].addProperty(new InterceptorProperty(propName,propValue)); } } } interceptors = definitions; } } return interceptors; } /** * {@inheritDoc} */ @Override public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) { // NOOP } /** * {@inheritDoc} */ @Override public void setConnectionProperties(String connectionProperties) { this.connectionProperties = connectionProperties; getProperties(connectionProperties, getDbProperties()); } /** * {@inheritDoc} */ @Override public void setDbProperties(Properties dbProperties) { this.dbProperties = dbProperties; } /** * {@inheritDoc} */ @Override public void setDefaultAutoCommit(Boolean defaultAutoCommit) { this.defaultAutoCommit = defaultAutoCommit; } /** * {@inheritDoc} */ @Override public void setDefaultCatalog(String defaultCatalog) { this.defaultCatalog = defaultCatalog; } /** * {@inheritDoc} */ @Override public void setDefaultReadOnly(Boolean defaultReadOnly) { this.defaultReadOnly = defaultReadOnly; } /** * {@inheritDoc} */ @Override public void setDefaultTransactionIsolation(int defaultTransactionIsolation) { this.defaultTransactionIsolation = defaultTransactionIsolation; } /** * {@inheritDoc} */ @Override public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /** * {@inheritDoc} */ @Override public void setInitialSize(int initialSize) { this.initialSize = initialSize; } /** * {@inheritDoc} */ @Override public void setLogAbandoned(boolean logAbandoned) { this.logAbandoned = logAbandoned; } /** * {@inheritDoc} */ @Override public void setMaxActive(int maxActive) { this.maxActive = maxActive; } /** * {@inheritDoc} */ @Override public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } /** * {@inheritDoc} */ @Override public void setMaxWait(int maxWait) { this.maxWait = maxWait; } /** * {@inheritDoc} */ @Override public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } /** * {@inheritDoc} */ @Override public void setMinIdle(int minIdle) { this.minIdle = minIdle; } /** * {@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** * {@inheritDoc} */ @Override public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { this.numTestsPerEvictionRun = numTestsPerEvictionRun; } /** * {@inheritDoc} */ @Override public void setPassword(String password) { this.password = password; } /** * {@inheritDoc} */ @Override public void setRemoveAbandoned(boolean removeAbandoned) { this.removeAbandoned = removeAbandoned; } /** * {@inheritDoc} */ @Override public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) { this.removeAbandonedTimeout = removeAbandonedTimeout; } /** * {@inheritDoc} */ @Override public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } /** * {@inheritDoc} */ @Override public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } /** * {@inheritDoc} */ @Override public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } /** * {@inheritDoc} */ @Override public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } /** * {@inheritDoc} */ @Override public void setUrl(String url) { this.url = url; } /** * {@inheritDoc} */ @Override public void setUsername(String username) { this.username = username; } /** * {@inheritDoc} */ @Override public void setValidationInterval(long validationInterval) { this.validationInterval = validationInterval; } /** * {@inheritDoc} */ @Override public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } /** * {@inheritDoc} */ @Override public void setValidatorClassName(String className) { this.validatorClassName = className; validator = null; if (className == null) { return; } try { Class<Validator> validatorClass = (Class<Validator>)Class.forName(className); validator = validatorClass.newInstance(); } catch (ClassNotFoundException e) { log.warn("The class "+className+" cannot be found.", e); } catch (ClassCastException e) { log.warn("The class "+className+" does not implement the Validator interface.", e); } catch (InstantiationException e) { log.warn("An object of class "+className+" cannot be instantiated. Make sure that "+ "it includes an implicit or explicit no-arg constructor.", e); } catch (IllegalAccessException e) { log.warn("The class "+className+" or its no-arg constructor are inaccessible.", e); } } /** * {@inheritDoc} */ @Override public void setInitSQL(String initSQL) { this.initSQL = initSQL; } /** * {@inheritDoc} */ @Override public void setTestOnConnect(boolean testOnConnect) { this.testOnConnect = testOnConnect; } /** * {@inheritDoc} */ @Override public void setJdbcInterceptors(String jdbcInterceptors) { this.jdbcInterceptors = jdbcInterceptors; this.interceptors = null; } @Override public String toString() { StringBuilder buf = new StringBuilder("ConnectionPool["); try { String[] fields = DataSourceFactory.ALL_PROPERTIES; for (int i=0; i<fields.length; i++) { final String[] prefix = new String[] {"get","is"}; for (int j=0; j<prefix.length; j++) { String name = prefix[j] + fields[i].substring(0, 1).toUpperCase(Locale.US) + fields[i].substring(1); Method m = null; try { m = getClass().getMethod(name); }catch (NoSuchMethodException nm) { continue; } buf.append(fields[i]); buf.append("="); buf.append(m.invoke(this, new Object[0])); buf.append("; "); break; } } }catch (Exception x) { //shouldn;t happen x.printStackTrace(); } return buf.toString(); } public static int getPoolCounter() { return poolCounter.get(); } /** * {@inheritDoc} */ @Override public boolean isJmxEnabled() { return jmxEnabled; } /** * {@inheritDoc} */ @Override public void setJmxEnabled(boolean jmxEnabled) { this.jmxEnabled = jmxEnabled; } /** * {@inheritDoc} */ @Override public Boolean getDefaultAutoCommit() { return defaultAutoCommit; } /** * {@inheritDoc} */ @Override public Boolean getDefaultReadOnly() { return defaultReadOnly; } /** * {@inheritDoc} */ @Override public int getSuspectTimeout() { return this.suspectTimeout; } /** * {@inheritDoc} */ @Override public void setSuspectTimeout(int seconds) { this.suspectTimeout = seconds; } /** * {@inheritDoc} */ @Override public boolean isPoolSweeperEnabled() { boolean timer = getTimeBetweenEvictionRunsMillis()>0; boolean result = timer && (isRemoveAbandoned() && getRemoveAbandonedTimeout()>0); result = result || (timer && getSuspectTimeout()>0); result = result || (timer && isTestWhileIdle() && getValidationQuery()!=null); result = result || (timer && getMinEvictableIdleTimeMillis()>0); return result; } public static class InterceptorDefinition implements Serializable { private static final long serialVersionUID = 1L; protected String className; protected Map<String,InterceptorProperty> properties = new HashMap<>(); protected volatile Class<?> clazz = null; public InterceptorDefinition(String className) { this.className = className; } public InterceptorDefinition(Class<?> cl) { this(cl.getName()); clazz = cl; } public String getClassName() { return className; } public void addProperty(String name, String value) { InterceptorProperty p = new InterceptorProperty(name,value); addProperty(p); } public void addProperty(InterceptorProperty p) { properties.put(p.getName(), p); } public Map<String,InterceptorProperty> getProperties() { return properties; } @SuppressWarnings("unchecked") public Class<? extends JdbcInterceptor> getInterceptorClass() throws ClassNotFoundException { if (clazz==null) { if (getClassName().indexOf(".")<0) { if (log.isDebugEnabled()) { log.debug("Loading interceptor class:"+PoolConfiguration.PKG_PREFIX+getClassName()); } clazz = Class.forName(PoolConfiguration.PKG_PREFIX+getClassName(), true, this.getClass().getClassLoader()); } else { if (log.isDebugEnabled()) { log.debug("Loading interceptor class:"+getClassName()); } clazz = Class.forName(getClassName(), true, this.getClass().getClassLoader()); } } return (Class<? extends JdbcInterceptor>)clazz; } } public static class InterceptorProperty implements Serializable { private static final long serialVersionUID = 1L; String name; String value; public InterceptorProperty(String name, String value) { assert(name!=null); this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } public boolean getValueAsBoolean(boolean def) { if (value==null) return def; if ("true".equals(value)) return true; if ("false".equals(value)) return false; return def; } public int getValueAsInt(int def) { if (value==null) return def; try { int v = Integer.parseInt(value); return v; }catch (NumberFormatException nfe) { return def; } } public long getValueAsLong(long def) { if (value==null) return def; try { return Long.parseLong(value); }catch (NumberFormatException nfe) { return def; } } public byte getValueAsByte(byte def) { if (value==null) return def; try { return Byte.parseByte(value); }catch (NumberFormatException nfe) { return def; } } public short getValueAsShort(short def) { if (value==null) return def; try { return Short.parseShort(value); }catch (NumberFormatException nfe) { return def; } } public float getValueAsFloat(float def) { if (value==null) return def; try { return Float.parseFloat(value); }catch (NumberFormatException nfe) { return def; } } public double getValueAsDouble(double def) { if (value==null) return def; try { return Double.parseDouble(value); }catch (NumberFormatException nfe) { return def; } } public char getValueAschar(char def) { if (value==null) return def; try { return value.charAt(0); }catch (StringIndexOutOfBoundsException nfe) { return def; } } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object o) { if (o==this) return true; if (o instanceof InterceptorProperty) { InterceptorProperty other = (InterceptorProperty)o; return other.name.equals(this.name); } return false; } } /** * {@inheritDoc} */ @Override public boolean isUseEquals() { return useEquals; } /** * {@inheritDoc} */ @Override public void setUseEquals(boolean useEquals) { this.useEquals = useEquals; } /** * {@inheritDoc} */ @Override public long getMaxAge() { return maxAge; } /** * {@inheritDoc} */ @Override public void setMaxAge(long maxAge) { this.maxAge = maxAge; } /** * {@inheritDoc} */ @Override public boolean getUseLock() { return useLock; } /** * {@inheritDoc} */ @Override public void setUseLock(boolean useLock) { this.useLock = useLock; } /** * {@inheritDoc} */ @Override public void setDataSource(Object ds) { this.dataSource = ds; } /** * {@inheritDoc} */ @Override public Object getDataSource() { return dataSource; } /** * {@inheritDoc} */ @Override public void setDataSourceJNDI(String jndiDS) { this.dataSourceJNDI = jndiDS; } /** * {@inheritDoc} */ @Override public String getDataSourceJNDI() { return this.dataSourceJNDI; } public static Properties getProperties(String propText, Properties props) { if (props==null) props = new Properties(); if (propText != null) { try { props.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes())); }catch (IOException x) { throw new RuntimeException(x); } } return props; } /** * {@inheritDoc} */ @Override public boolean isAlternateUsernameAllowed() { return alternateUsernameAllowed; } /** * {@inheritDoc} */ @Override public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) { this.alternateUsernameAllowed = alternateUsernameAllowed; } /** * {@inheritDoc} */ @Override public void setCommitOnReturn(boolean commitOnReturn) { this.commitOnReturn = commitOnReturn; } /** * {@inheritDoc} */ @Override public boolean getCommitOnReturn() { return this.commitOnReturn; } /** * {@inheritDoc} */ @Override public void setRollbackOnReturn(boolean rollbackOnReturn) { this.rollbackOnReturn = rollbackOnReturn; } /** * {@inheritDoc} */ @Override public boolean getRollbackOnReturn() { return this.rollbackOnReturn; } /** * {@inheritDoc} */ @Override public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) { this.useDisposableConnectionFacade = useDisposableConnectionFacade; } /** * {@inheritDoc} */ @Override public boolean getUseDisposableConnectionFacade() { return useDisposableConnectionFacade; } /** * {@inheritDoc} */ @Override public void setLogValidationErrors(boolean logValidationErrors) { this.logValidationErrors = logValidationErrors; } /** * {@inheritDoc} */ @Override public boolean getLogValidationErrors() { return this.logValidationErrors; } /** * {@inheritDoc} */ @Override public boolean getPropagateInterruptState() { return propagateInterruptState; } /** * {@inheritDoc} */ @Override public void setPropagateInterruptState(boolean propagateInterruptState) { this.propagateInterruptState = propagateInterruptState; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } }
54,712
Bug 54712 Prefer Locale.ENGLISH over Locale.US for case conversion
null
resolved fixed
dc16474
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T14:07:25Z
2013-03-17T17:06:40Z
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.US); 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; protected 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,709
Bug 54709 Official schemes for WebSocket are "ws"/"wss"; WsWebSocketContainer only allows "http"/"https"
null
resolved fixed
ad148dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T18:49:45Z
2013-03-17T11:33:20Z
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.IOException; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.charset.Charset; 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.Future; 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 javax.xml.bind.DatatypeConverter; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.pojo.PojoEndpointClient; public class WsWebSocketContainer implements WebSocketContainer, BackgroundProcess { 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 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 { String scheme = path.getScheme(); if (!("http".equalsIgnoreCase(scheme) || "https".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.getConfigurator(). beforeRequest(reqHeaders); ByteBuffer request = createRequest(path.getRawPath(), reqHeaders); SocketAddress sa; if (port == -1) { if ("http".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 80); } else { // TODO HTTPS support // sa = new InetSocketAddress(host, 443); throw new DeploymentException("TODO: HTTPS"); } } else { sa = new InetSocketAddress(host, port); } AsynchronousSocketChannel channel; try { channel = AsynchronousSocketChannel.open(); } catch (IOException ioe) { throw new DeploymentException("TODO", ioe); } Future<Void> fConnect = channel.connect(sa); ByteBuffer response; String subProtocol; try { fConnect.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 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, subProtocol, Collections.EMPTY_MAP, false, clientEndpointConfiguration.getEncoders()); 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) { 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) { 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); return headers; } private String generateWsKeyValue() { byte[] keyBytes = new byte[16]; random.nextBytes(keyBytes); return DatatypeConverter.printBase64Binary(keyBytes); } private ByteBuffer createRequest(String rawPath, Map<String,List<String>> reqHeaders) { ByteBuffer result = ByteBuffer.allocate(4 * 1024); // Request line result.put("GET ".getBytes(iso88591)); result.put(rawPath.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, AsynchronousSocketChannel channel) throws InterruptedException, ExecutionException, DeploymentException { Map<String,List<String>> headers = new HashMap<>(); boolean readStatus = false; boolean readHeaders = false; String line = null; while (!readHeaders) { // Blocking read Future<Integer> written = channel.read(response); written.get(); response.flip(); while (response.hasRemaining()) { 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 != 10) { c = (char) response.get(); sb.append(c); } return sb.toString(); } @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; } private static class WsHandshakeResponse implements HandshakeResponse { private final Map<String,List<String>> headers; public WsHandshakeResponse(Map<String,List<String>> headers) { this.headers = headers; } @Override public Map<String,List<String>> getHeaders() { return headers; } } // ----------------------------------------------- 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; } }
54,709
Bug 54709 Official schemes for WebSocket are "ws"/"wss"; WsWebSocketContainer only allows "http"/"https"
null
resolved fixed
ad148dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T18:49:45Z
2013-03-17T11:33:20Z
test/org/apache/tomcat/websocket/TestWsRemoteEndpoint.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.Writer; import java.net.URI; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.websocket.ClientEndpointConfig.Builder; import javax.websocket.ContainerProvider; import javax.websocket.Endpoint; import javax.websocket.Session; import javax.websocket.WebSocketContainer; 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.websocket.TesterSingleMessageClient.AsyncHandler; import org.apache.tomcat.websocket.TesterSingleMessageClient.AsyncText; import org.apache.tomcat.websocket.TesterSingleMessageClient.TesterAnnotatedEndpoint; import org.apache.tomcat.websocket.TesterSingleMessageClient.TesterProgrammaticEndpoint; public class TestWsRemoteEndpoint extends TomcatBaseTest { private static final String SEQUENCE = "ABCDE"; private static final int S_LEN = SEQUENCE.length(); private static final String TEST_MESSAGE_5K; static { StringBuilder sb = new StringBuilder(S_LEN * 1024); for (int i = 0; i < 1024; i++) { sb.append(SEQUENCE); } TEST_MESSAGE_5K = sb.toString(); } @Test public void testWriterAnnotation() throws Exception { doTestWriter(TesterAnnotatedEndpoint.class); } @Test public void testWriterProgrammatic() throws Exception { doTestWriter(TesterProgrammaticEndpoint.class); } private void doTestWriter(Class<?> clazz) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); ctx.addApplicationListener(TesterEchoServer.Config.class.getName()); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Session wsSession; URI uri = new URI("http://localhost:" + getPort() + TesterEchoServer.Config.PATH_ASYNC); if (Endpoint.class.isAssignableFrom(clazz)) { @SuppressWarnings("unchecked") Class<? extends Endpoint> endpointClazz = (Class<? extends Endpoint>) clazz; wsSession = wsContainer.connectToServer(endpointClazz, Builder.create().build(), uri); } else { wsSession = wsContainer.connectToServer(clazz, uri); } CountDownLatch latch = new CountDownLatch(1); wsSession.getUserProperties().put("latch", latch); AsyncHandler<?> handler = new AsyncText(latch); wsSession.addMessageHandler(handler); Writer w = wsSession.getBasicRemote().getSendWriter(); for (int i = 0; i < 8; i++) { w.write(TEST_MESSAGE_5K); } w.close(); boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS); Assert.assertTrue(latchResult); List<String> messages = (List<String>) handler.getMessages(); int offset = 0; int i = 0; for (String message : messages) { // First may be a fragment Assert.assertEquals(SEQUENCE.substring(offset, S_LEN), message.substring(0, S_LEN - offset)); i = S_LEN - offset; while (i + S_LEN < message.length()) { if (!SEQUENCE.equals(message.substring(i, i + S_LEN))) { Assert.fail(); } i += S_LEN; } offset = message.length() - i; if (!SEQUENCE.substring(0, offset).equals(message.substring(i))) { Assert.fail(); } } } }
54,709
Bug 54709 Official schemes for WebSocket are "ws"/"wss"; WsWebSocketContainer only allows "http"/"https"
null
resolved fixed
ad148dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T18:49:45Z
2013-03-17T11:33:20Z
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.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; 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.coyote.http11.Http11Protocol; 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.TesterProgrammaticEndpoint; import org.apache.tomcat.websocket.server.WsListener; import org.apache.tomcat.websocket.server.WsServerContainer; 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(TesterEchoServer.Config.class.getName()); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("http://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(TesterEchoServer.Config.class.getName()); 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(TesterEchoServer.Config.class.getName()); tomcat.start(); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("http://" + 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(TesterEchoServer.Config.class.getName()); 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("http://localhost:" + getPort() + TesterEchoServer.Config.PATH_BASIC)); BasicHandler<?> handler; CountDownLatch latch = new CountDownLatch(1); wsSession.getUserProperties().put("latch", 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 { 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(BlockingConfig.class.getName()); 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("http://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(WsListener.class.getName()); ctx.addApplicationListener(ConstantTxConfig.class.getName()); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Session wsSession = wsContainer.connectToServer(TesterProgrammaticEndpoint.class, ClientEndpointConfig.Builder.create().build(), new URI("http://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); WsServerContainer sc = WsServerContainer.getServerContainer(); sc.setServletContext(sce.getServletContext()); 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); WsServerContainer sc = WsServerContainer.getServerContainer(); 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(TesterEchoServer.Config.class.getName()); 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(TesterEchoServer.Config.class.getName()); 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; setA = s3a.getOpenSessions(); while (setA.size() > 0 && count < 8) { count ++; Thread.sleep(1000); setA = s3a.getOpenSessions(); } if (setA.size() > 0) { Assert.fail("There were [" + setA.size() + "] 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(TesterEchoServer.Config.class.getName()); 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, setA.size()); int count = 0; while (setA.size() == expected && count < 5) { count ++; Thread.sleep(1000); setA = s3a.getOpenSessions(); } expected--; } Assert.assertEquals(0, setA.size()); } private Session connectToEchoServerBasic(WebSocketContainer wsContainer, Class<? extends Endpoint> clazz) throws Exception { return wsContainer.connectToServer(clazz, ClientEndpointConfig.Builder.create().build(), new URI("http://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 } } }
54,709
Bug 54709 Official schemes for WebSocket are "ws"/"wss"; WsWebSocketContainer only allows "http"/"https"
null
resolved fixed
ad148dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T18:49:45Z
2013-03-17T11:33: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.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.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.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(ServerConfigListener.class.getName()); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Client client = new Client(); URI uri = new URI("http://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 extends Encoder.Adapter implements Encoder.Text<MsgString> { @Override public String encode(MsgString msg) throws EncodeException { return "MsgString:" + msg.getData(); } } public static class MsgStringDecoder extends Decoder.Adapter implements Decoder.Text<MsgString> { @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 extends Encoder.Adapter implements Encoder.Binary<MsgByte> { @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 extends Decoder.Adapter implements Decoder.Binary<MsgByte> { @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; } } }
54,709
Bug 54709 Official schemes for WebSocket are "ws"/"wss"; WsWebSocketContainer only allows "http"/"https"
null
resolved fixed
ad148dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-17T18:49:45Z
2013-03-17T11:33:20Z
test/org/apache/tomcat/websocket/pojo/TestPojoMethodMapping.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.util.ArrayList; import java.util.List; import javax.websocket.ClientEndpoint; import javax.websocket.ContainerProvider; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; 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.websocket.pojo.Util.ServerConfigListener; import org.apache.tomcat.websocket.pojo.Util.SingletonConfigurator; public class TestPojoMethodMapping extends TomcatBaseTest { private static final String PARAM_ONE = "abcde"; private static final String PARAM_TWO = "12345"; private static final String PARAM_THREE = "true"; @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(ServerConfigListener.class.getName()); WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer(); tomcat.start(); Client client = new Client(); URI uri = new URI("http://localhost:" + getPort() + "/" + PARAM_ONE + "/" + PARAM_TWO + "/" + PARAM_THREE); Session session = wsContainer.connectToServer(client, uri); session.getBasicRemote().sendText("NO-OP"); session.close(); // Give server 5s to close int count = 0; while (count < 50) { if (server.isClosed()) { break; } count++; Thread.sleep(100); } if (count == 50) { Assert.fail("Server did not process an onClose event within 5 " + "seconds of the client sending a close message"); } // Check no errors List<String> errors = server.getErrors(); for (String error : errors) { System.err.println(error); } Assert.assertEquals("Found errors", 0, errors.size()); } @ClientEndpoint public static final class Client { } @ServerEndpoint(value="/{one}/{two}/{three}", configurator=SingletonConfigurator.class) public static final class Server { private final List<String> errors = new ArrayList<>(); private volatile boolean closed; @OnOpen public void onOpen(@PathParam("one") String p1, @PathParam("two")int p2, @PathParam("three")boolean p3) { checkParams("onOpen", p1, p2, p3); } @OnMessage public void onMessage(@SuppressWarnings("unused") String msg, @PathParam("one") String p1, @PathParam("two")int p2, @PathParam("three")boolean p3) { checkParams("onMessage", p1, p2, p3); } @OnClose public void onClose(@PathParam("one") String p1, @PathParam("two")int p2, @PathParam("three")boolean p3) { checkParams("onClose", p1, p2, p3); closed = true; } public List<String> getErrors() { return errors; } public boolean isClosed() { return closed; } private void checkParams(String method, String p1, int p2, boolean p3) { checkParam(method, PARAM_ONE, p1); checkParam(method, PARAM_TWO, Integer.toString(p2)); checkParam(method, PARAM_THREE, Boolean.toString(p3)); } private void checkParam(String method, String expected, String actual) { if (!expected.equals(actual)) { errors.add("Method [" + method + "]. Expected [" + expected + "] was + [" + actual + "]"); } } } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoEndpointBase.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.lang.reflect.InvocationTargetException; import java.util.Map; import java.util.Set; import javax.websocket.CloseReason; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.Session; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * Base implementation (client and server have different concrete * implementations) of the wrapper that converts a POJO instance into a * WebSocket endpoint instance. */ public abstract class PojoEndpointBase extends Endpoint { private static final Log log = LogFactory.getLog(PojoEndpointBase.class); private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private Object pojo; private Map<String,String> pathParameters; private PojoMethodMapping methodMapping; protected final void doOnOpen(Session session, EndpointConfig config) { PojoMethodMapping methodMapping = getMethodMapping(); Object pojo = getPojo(); Map<String,String> pathParameters = getPathParameters(); if (methodMapping.getOnOpen() != null) { try { methodMapping.getOnOpen().invoke(pojo, methodMapping.getOnOpenArgs(pathParameters, session)); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalArgumentException(sm.getString( "pojoEndpointBase.onOpenFail", pojo.getClass().getName()), e); } } for (MessageHandler mh : methodMapping.getMessageHandlers(pojo, pathParameters, session, config)) { session.addMessageHandler(mh); } } @Override public final void onClose(Session session, CloseReason closeReason) { if (methodMapping.getOnClose() != null) { try { methodMapping.getOnClose().invoke(pojo, methodMapping.getOnCloseArgs(pathParameters, session)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.error(sm.getString("pojoEndpointBase.onCloseFail", pojo.getClass().getName()), e); } } // Trigger the destroy method for any associated decoders Set<MessageHandler> messageHandlers = session.getMessageHandlers(); for (MessageHandler messageHandler : messageHandlers) { if (messageHandler instanceof PojoMessageHandlerWholeBase<?>) { ((PojoMessageHandlerWholeBase<?>) messageHandler).onClose(); } } } @Override public final void onError(Session session, Throwable throwable) { if (methodMapping.getOnError() != null) { try { methodMapping.getOnError().invoke( pojo, methodMapping.getOnErrorArgs(pathParameters, session, throwable)); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { log.error(sm.getString("pojoEndpointBase.onErrorFail", pojo.getClass().getName()), e); } } } protected Object getPojo() { return pojo; } protected void setPojo(Object pojo) { this.pojo = pojo; } protected Map<String,String> getPathParameters() { return pathParameters; } protected void setPathParameters(Map<String,String> pathParameters) { this.pathParameters = pathParameters; } protected PojoMethodMapping getMethodMapping() { return methodMapping; } protected void setMethodMapping(PojoMethodMapping methodMapping) { this.methodMapping = methodMapping; } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerBase.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.lang.reflect.Method; import java.nio.ByteBuffer; import javax.websocket.EncodeException; import javax.websocket.RemoteEndpoint; import javax.websocket.Session; /** * Common implementation code for the POJO message handlers. * * @param <T> The type of message to handle */ public abstract class PojoMessageHandlerBase<T> { protected final Object pojo; protected final Method method; protected final Session session; protected final Object[] params; protected final int indexPayload; protected final boolean unwrap; protected final int indexSession; public PojoMessageHandlerBase(Object pojo, Method method, Session session, Object[] params, int indexPayload, boolean unwrap, int indexSession) { this.pojo = pojo; this.method = method; this.session = session; this.params = params; this.indexPayload = indexPayload; this.unwrap = unwrap; this.indexSession = indexSession; } protected final void processResult(Object result) { if (result == null) { return; } RemoteEndpoint.Basic remoteEndpoint = session.getBasicRemote(); try { if (result instanceof String) { remoteEndpoint.sendText((String) result); } else if (result instanceof ByteBuffer) { remoteEndpoint.sendBinary((ByteBuffer) result); } else if (result instanceof byte[]) { remoteEndpoint.sendBinary(ByteBuffer.wrap((byte[]) result)); } else { remoteEndpoint.sendObject(result); } } catch (IOException | EncodeException ioe) { throw new IllegalStateException(ioe); } } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerPartialBase.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.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import javax.websocket.MessageHandler; import javax.websocket.Session; /** * Common implementation code for the POJO partial message handlers. All * the real work is done in this class and in the superclass. * * @param <T> The type of message to handle */ public abstract class PojoMessageHandlerPartialBase<T> extends PojoMessageHandlerBase<T> implements MessageHandler.Partial<T> { private final int indexBoolean; public PojoMessageHandlerPartialBase(Object pojo, Method method, Session session, Object[] params, int indexPayload, boolean unwrap, int indexBoolean, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexSession); this.indexBoolean = indexBoolean; } @Override public final void onMessage(T message, boolean last) { Object[] parameters = params.clone(); if (indexBoolean != -1) { parameters[indexBoolean] = Boolean.valueOf(last); } if (indexSession != -1) { parameters[indexSession] = session; } if (unwrap) { parameters[indexPayload] = ((ByteBuffer) message).array(); } else { parameters[indexPayload] = message; } Object result; try { result = method.invoke(pojo, parameters); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalArgumentException(e); } processResult(result); } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerPartialBinary.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.lang.reflect.Method; import java.nio.ByteBuffer; import javax.websocket.Session; /** * ByteBuffer specific concrete implementation for handling partial messages. */ public class PojoMessageHandlerPartialBinary extends PojoMessageHandlerPartialBase<ByteBuffer>{ public PojoMessageHandlerPartialBinary(Object pojo, Method method, Session session, Object[] params, int indexPayload, boolean unwrap, int indexBoolean, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexBoolean, indexSession); } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerPartialText.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.lang.reflect.Method; import javax.websocket.Session; /** * Text specific concrete implementation for handling partial messages. */ public class PojoMessageHandlerPartialText extends PojoMessageHandlerPartialBase<String>{ public PojoMessageHandlerPartialText(Object pojo, Method method, Session session, Object[] params, int indexPayload, boolean unwrap, int indexBoolean, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexBoolean, indexSession); } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerWholeBase.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.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import javax.websocket.DecodeException; import javax.websocket.MessageHandler; import javax.websocket.Session; import javax.websocket.SessionException; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.websocket.WsSession; /** * Common implementation code for the POJO whole message handlers. All the real * work is done in this class and in the superclass. * * @param <T> The type of message to handle */ public abstract class PojoMessageHandlerWholeBase<T> extends PojoMessageHandlerBase<T> implements MessageHandler.Whole<T> { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); public PojoMessageHandlerWholeBase(Object pojo, Method method, Session session, Object[] params, int indexPayload, boolean unwrap, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexSession); } @Override public final void onMessage(T message) { // Can this message be decoded? Object payload; try { payload = decode(message); } catch (DecodeException de) { SessionException se = new SessionException(sm.getString( "pojoMessageHandlerWhole.decodeFail"), de, session); ((WsSession) session).getLocal().onError(session, se); return; } if (payload == null) { // Not decoded. Unwrap if required. Unwrap only ever applies to // ByteBuffers if (unwrap) { ByteBuffer bb = (ByteBuffer) message; byte[] array = new byte[bb.remaining()]; bb.get(array); payload = array; } else { payload = message; } } Object[] parameters = params.clone(); if (indexSession != -1) { parameters[indexSession] = session; } parameters[indexPayload] = payload; Object result; try { result = method.invoke(pojo, parameters); } catch (IllegalAccessException | InvocationTargetException e) { throw new IllegalArgumentException(); } processResult(result); } protected abstract Object decode(T message) throws DecodeException; protected abstract void onClose(); }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerWholeBinary.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.ByteArrayInputStream; import java.io.IOException; import java.lang.reflect.Method; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.Decoder.Binary; import javax.websocket.Decoder.BinaryStream; import javax.websocket.EndpointConfig; import javax.websocket.Session; import org.apache.tomcat.util.res.StringManager; /** * ByteBuffer specific concrete implementation for handling whole messages. */ public class PojoMessageHandlerWholeBinary extends PojoMessageHandlerWholeBase<ByteBuffer> { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final List<Decoder> decoders = new ArrayList<>(); public PojoMessageHandlerWholeBinary(Object pojo, Method method, Session session, EndpointConfig config, Object[] params, int indexPayload, boolean unwrap, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexSession); try { for (Class<? extends Decoder> decoderClazz : config.getDecoders()) { if (Binary.class.isAssignableFrom(decoderClazz)) { Binary<?> decoder = (Binary<?>) decoderClazz.newInstance(); decoder.init(config); decoders.add(decoder); } else if (Decoder.TextStream.class.isAssignableFrom( decoderClazz)) { BinaryStream<?> decoder = (BinaryStream<?>) decoderClazz.newInstance(); decoder.init(config); decoders.add(decoder); } else { // Text decoder - ignore it } } } catch (IllegalAccessException | InstantiationException e) { throw new IllegalArgumentException(e); } } @Override protected Object decode(ByteBuffer message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Binary) { if (((Binary<?>) decoder).willDecode(message)) { return ((Binary<?>) decoder).decode(message); } } else { byte[] array = new byte[message.limit() - message.position()]; message.get(array); ByteArrayInputStream bais = new ByteArrayInputStream(array); try { return ((BinaryStream<?>) decoder).decode(bais); } catch (IOException ioe) { throw new DecodeException(message, sm.getString( "pojoMessageHandlerWhole.decodeIoFail"), ioe); } } } return null; } @Override protected void onClose() { for (Decoder decoder : decoders) { decoder.destroy(); } } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerWholePong.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.lang.reflect.Method; import javax.websocket.PongMessage; import javax.websocket.Session; /** * PongMessage specific concrete implementation for handling whole messages. */ public class PojoMessageHandlerWholePong extends PojoMessageHandlerWholeBase<PongMessage> { public PojoMessageHandlerWholePong(Object pojo, Method method, Session session, Object[] params, int indexPayload, boolean unwrap, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexSession); } @Override protected Object decode(PongMessage message) { // Never decoded return null; } @Override protected void onClose() { // NO-OP } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20:00Z
java/org/apache/tomcat/websocket/pojo/PojoMessageHandlerWholeText.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.io.StringReader; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import javax.websocket.DecodeException; import javax.websocket.Decoder; import javax.websocket.Decoder.Text; import javax.websocket.Decoder.TextStream; import javax.websocket.EndpointConfig; import javax.websocket.Session; import org.apache.tomcat.util.res.StringManager; /** * Text specific concrete implementation for handling whole messages. */ public class PojoMessageHandlerWholeText extends PojoMessageHandlerWholeBase<String> { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final List<Decoder> decoders = new ArrayList<>(); public PojoMessageHandlerWholeText(Object pojo, Method method, Session session, EndpointConfig config, Object[] params, int indexPayload, boolean unwrap, int indexSession) { super(pojo, method, session, params, indexPayload, unwrap, indexSession); try { for (Class<? extends Decoder> decoderClazz : config.getDecoders()) { if (Text.class.isAssignableFrom(decoderClazz)) { Text<?> decoder = (Text<?>) decoderClazz.newInstance(); decoder.init(config); decoders.add(decoder); } else if (Decoder.TextStream.class.isAssignableFrom( decoderClazz)) { TextStream<?> decoder = (TextStream<?>) decoderClazz.newInstance(); decoder.init(config); decoders.add(decoder); } else { // Binary decoder - ignore it } } } catch (IllegalAccessException | InstantiationException e) { throw new IllegalArgumentException(e); } } @Override protected Object decode(String message) throws DecodeException { for (Decoder decoder : decoders) { if (decoder instanceof Text) { if (((Text<?>) decoder).willDecode(message)) { return ((Text<?>) decoder).decode(message); } } else { StringReader r = new StringReader(message); try { return ((TextStream<?>) decoder).decode(r); } catch (IOException ioe) { throw new DecodeException(message, sm.getString( "pojoMessageHandlerWhole.decodeIoFail"), ioe); } } } return null; } @Override protected void onClose() { for (Decoder decoder : decoders) { decoder.destroy(); } } }
54,710
Bug 54710 Java WebSocket specification says @OnMessage methods can have InputStream/Reader parameters; @OnClose can have CloseReason parameters
null
resolved fixed
06800eb
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-18T21:47:02Z
2013-03-17T14:20: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.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.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, false); onCloseParams = getPathParams(onClose, false); onErrorParams = getPathParams(onError, true); } public String getWsPath() { return wsPath; } public Method getOnOpen() { return onOpen; } public Object[] getOnOpenArgs(Map<String,String> pathParameters, Session session) { return buildArgs(onOpenParams, pathParameters, session, null); } public Method getOnClose() { return onClose; } public Object[] getOnCloseArgs(Map<String,String> pathParameters, Session session) { return buildArgs(onCloseParams, pathParameters, session, null); } public Method getOnError() { return onError; } public Object[] getOnErrorArgs(Map<String,String> pathParameters, Session session, Throwable throwable) { return buildArgs(onErrorParams, pathParameters, session, throwable); } 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, boolean isOnError) { 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 (isOnError && type.equals(Throwable.class)) { foundThrowable = true; 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 (isOnError && !foundThrowable) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.onErrorNoThrowable", m.getName(), m.getClass().getName())); } return result; } private static Object[] buildArgs(PojoPathParam[] pathParams, Map<String,String> pathParameters, Session session, Throwable throwable) { 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(Throwable.class)) { result[i] = throwable; } else { String name = pathParams[i].getName(); String value = pathParameters.get(name); if (value == null) { result[i] = null; } else { result[i] = coerceToType(type, value); } } } return result; } private static Object coerceToType(Class<?> type, String value) { if (type.equals(String.class)) { return value; } else if (type.equals(boolean.class) || type.equals(Boolean.class)) { return Boolean.valueOf(value); } else if (type.equals(byte.class) || type.equals(Byte.class)) { return Byte.valueOf(value); } else if (value.length() == 1 && (type.equals(char.class) || type.equals(Character.class))) { return Character.valueOf(value.charAt(0)); } else if (type.equals(double.class) || type.equals(Double.class)) { return Double.valueOf(value); } else if (type.equals(float.class) || type.equals(Float.class)) { return Float.valueOf(value); } else if (type.equals(int.class) || type.equals(Integer.class)) { return Integer.valueOf(value); } else if (type.equals(long.class) || type.equals(Long.class)) { return Long.valueOf(value); } else if (type.equals(short.class) || type.equals(Short.class)) { return Short.valueOf(value); } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.invalidType", value, type.getName())); } } 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 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 (types[i] == String.class) { if (indexString == -1) { indexString = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getClass().getName())); } } else if (types[i] == boolean.class) { if (indexBoolean == -1) { indexBoolean = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateLastParam", m.getName(), m.getClass().getName())); } } else if (types[i] == ByteBuffer.class) { if (indexByteBuffer == -1) { indexByteBuffer = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getClass().getName())); } } else if (types[i] == byte[].class) { if (indexByteArray == -1) { indexByteArray = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getClass().getName())); } } else if (types[i] == Session.class) { if (indexSession == -1) { indexSession = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateSessionParam", m.getName(), m.getClass().getName())); } } else if (types[i] == PongMessage.class) { if (indexPong == -1) { indexPong = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicatePongMessageParam", m.getName(), m.getClass().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.getClass().getName())); } break; } else { if (indexString == -1) { indexString = i; } else { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getClass().getName())); } } } } } } // Additional checks required if (indexString != -1) { indexPayload = indexString; } if (indexByteArray != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getClass().getName())); } else { indexPayload = indexByteArray; } } if (indexByteBuffer != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.duplicateMessageParam", m.getName(), m.getClass().getName())); } else { indexPayload = indexByteBuffer; } } if (indexPong != -1) { if (indexPayload != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.pongWithPayload", m.getName(), m.getClass().getName())); } else { indexPayload = indexPong; } } if (indexPayload == -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.noPayload", m.getName(), m.getClass().getName())); } if (indexPong != -1 && indexBoolean != -1) { throw new IllegalArgumentException(sm.getString( "pojoMethodMapping.partialPong", m.getName(), m.getClass().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; if (valueString != null) { value = coerceToType(pathParam.getType(), valueString); } 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 (indexByteArray != -1) { mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, params, indexByteArray, true, indexSession); } else if (indexByteBuffer != -1) { mh = new PojoMessageHandlerWholeBinary(pojo, m, session, config, params, indexByteBuffer, false, 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; } } }
54,721
Bug 54721 RemoteEndpoint blocks indefinitely if sendObject called with BinaryStream of TextStream encoders
null
resolved fixed
80ef59a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-19T14:26:49Z
2013-03-19T02:26:40Z
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) { 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) { Writer w = getSendWriter(); ((Encoder.TextStream) encoder).encode(obj, w); } else if (encoder instanceof Encoder.Binary) { ByteBuffer msg = ((Encoder.Binary) encoder).encode(obj); sendBytesByCompletion(msg, completion); } else if (encoder instanceof Encoder.BinaryStream) { OutputStream os = getSendStream(); ((Encoder.BinaryStream) encoder).encode(obj, os); } 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 volatile 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 flushRequired = true; 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 flushRequired = true; outputBuffer.flip(); endpoint.doWrite(this, outputBuffer); return; } if (flushRequired) { flushRequired = false; 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) { outputBuffer.clear(); if (result.isOK()) { 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; } } }
54,724
Bug 54724 WsSession does not throw IllegalStateException if closed when methods on it are called
Spec JavaDoc says: "Once the session is closed, it is no longer valid for use by applications. Calling any of its methods once the session has been closed will result in an IllegalStateException being thrown. Developers should retrieve any information from the session during the Endpoint.onClose(Session, CloseReason) method." Of course, the rules of Closeable also apply here, and calling Session#close(...) more than once should have no effect subsequent times. There are actually three problems here: 1) None of the methods throw IllegalStateException if the session is closed. Instead, they return things (like the basic remote, for example), and some methods in the endpoint implementation will not notice concurrent exceptions from the socket and then block forever waiting four the Countdown to clear. 2) The Session#state is never actually changed to State.CLOSED unless Session#onClose is called. However, Session#onClose is never actually called that I can find (though I will look harder before I make changes). 3) Even in Session#onClose, the state is incorrectly changed to State.CLOSED BEFORE Endpoint#onClose is called, when it should be changed AFTER. I'm working on a patch for this.
resolved fixed
12f89ff
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-19T19:49:51Z
2013-03-19T16: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; 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() { return webSocketContainer; } @SuppressWarnings("unchecked") @Override public void addMessageHandler(MessageHandler listener) { Type t = Util.getMessageType(listener); if (t.equals(String.class)) { if (textMessageHandler != null) { throw new IllegalStateException( sm.getString("wsSession.duplicateHandlerText")); } textMessageHandler = listener; } else if (t.equals(ByteBuffer.class)) { if (binaryMessageHandler != null) { throw new IllegalStateException( sm.getString("wsSession.duplicateHandlerBinary")); } binaryMessageHandler = listener; } else if (t.equals(PongMessage.class)) { 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() { 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) { if (listener == null) { return; } if (listener.equals(textMessageHandler)) { textMessageHandler = null; } else if (listener.equals(binaryMessageHandler)) { binaryMessageHandler = null; } else if (listener.equals(pongMessageHandler)) { pongMessageHandler = null; } // 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() { return Constants.WS_VERSION_HEADER_VALUE; } @Override public String getNegotiatedSubprotocol() { return subProtocol; } @Override public List<Extension> getNegotiatedExtensions() { return Collections.EMPTY_LIST; } @Override public boolean isSecure() { return secure; } @Override public boolean isOpen() { return state == State.OPEN; } @Override public long getMaxIdleTimeout() { return maxIdleTimeout; } @Override public void setMaxIdleTimeout(long timeout) { this.maxIdleTimeout = timeout; } @Override public void setMaxBinaryMessageBufferSize(int max) { this.maxBinaryMessageBufferSize = max; } @Override public int getMaxBinaryMessageBufferSize() { return maxBinaryMessageBufferSize; } @Override public void setMaxTextMessageBufferSize(int max) { this.maxTextMessageBufferSize = max; } @Override public int getMaxTextMessageBufferSize() { return maxTextMessageBufferSize; } @Override public Set<Session> getOpenSessions() { return webSocketContainer.getOpenSessions(localEndpoint.getClass()); } @Override public RemoteEndpoint.Async getAsyncRemote() { return remoteEndpointAsync; } @Override public RemoteEndpoint.Basic getBasicRemote() { return remoteEndpointBasic; } @Override public void close() throws IOException { close(new CloseReason(CloseCodes.NORMAL_CLOSURE, "")); } @Override public void close(CloseReason closeReason) throws IOException { // Double-checked locking. OK because state is volatile if (state != State.OPEN) { return; } synchronized (stateLock) { if (state != State.OPEN) { return; } state = State.CLOSING; sendCloseMessage(closeReason); } } /** * Called when a close message is received. Should only ever happen once. */ void onClose(CloseReason closeReason) { boolean sendCloseMessage = false; synchronized (stateLock) { if (state == State.OPEN) { sendCloseMessage = true; } state = State.CLOSED; if (sendCloseMessage) { sendCloseMessage(closeReason); } // Close the socket wsRemoteEndpoint.close(); } } 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); // Fire the onClose event Thread t = Thread.currentThread(); ClassLoader cl = t.getContextClassLoader(); t.setContextClassLoader(applicationClassLoader); try { localEndpoint.onClose(this, closeReason); } finally { t.setContextClassLoader(cl); } } } @Override public URI getRequestURI() { return requestUri; } @Override public Map<String,List<String>> getRequestParameterMap() { return requestParameterMap; } @Override public String getQueryString() { return queryString; } @Override public Principal getUserPrincipal() { return userPrincipal; } @Override public Map<String,String> getPathParameters() { return pathParameters; } @Override public String getId() { return id; } @Override public Map<String,Object> getUserProperties() { 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) { try { close(new CloseReason(CloseCodes.GOING_AWAY, sm.getString("wsSession.timeout"))); } catch (IOException e) { log.warn(sm.getString("wsSession.expireFailed"), e); } } } private static enum State { OPEN, CLOSING, CLOSED } }
54,724
Bug 54724 WsSession does not throw IllegalStateException if closed when methods on it are called
Spec JavaDoc says: "Once the session is closed, it is no longer valid for use by applications. Calling any of its methods once the session has been closed will result in an IllegalStateException being thrown. Developers should retrieve any information from the session during the Endpoint.onClose(Session, CloseReason) method." Of course, the rules of Closeable also apply here, and calling Session#close(...) more than once should have no effect subsequent times. There are actually three problems here: 1) None of the methods throw IllegalStateException if the session is closed. Instead, they return things (like the basic remote, for example), and some methods in the endpoint implementation will not notice concurrent exceptions from the socket and then block forever waiting four the Countdown to clear. 2) The Session#state is never actually changed to State.CLOSED unless Session#onClose is called. However, Session#onClose is never actually called that I can find (though I will look harder before I make changes). 3) Even in Session#onClose, the state is incorrectly changed to State.CLOSED BEFORE Endpoint#onClose is called, when it should be changed AFTER. I'm working on a patch for this.
resolved fixed
12f89ff
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-19T19:49:51Z
2013-03-19T16:20: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.ServerEndpoint; import javax.websocket.server.ServerEndpointConfig; 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.coyote.http11.Http11Protocol; 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.TesterProgrammaticEndpoint; import org.apache.tomcat.websocket.server.WsListener; import org.apache.tomcat.websocket.server.WsServerContainer; 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(TesterEchoServer.Config.class.getName()); 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(TesterEchoServer.Config.class.getName()); 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(TesterEchoServer.Config.class.getName()); 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(TesterEchoServer.Config.class.getName()); 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); wsSession.getUserProperties().put("latch", 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 { 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(BlockingConfig.class.getName()); 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(WsListener.class.getName()); ctx.addApplicationListener(ConstantTxConfig.class.getName()); 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); WsServerContainer sc = WsServerContainer.getServerContainer(); sc.setServletContext(sce.getServletContext()); 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); WsServerContainer sc = WsServerContainer.getServerContainer(); 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(TesterEchoServer.Config.class.getName()); 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(TesterEchoServer.Config.class.getName()); 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; setA = s3a.getOpenSessions(); while (setA.size() > 0 && count < 8) { count ++; Thread.sleep(1000); setA = s3a.getOpenSessions(); } if (setA.size() > 0) { Assert.fail("There were [" + setA.size() + "] 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(TesterEchoServer.Config.class.getName()); 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, setA.size()); int count = 0; while (setA.size() == expected && count < 5) { count ++; Thread.sleep(1000); setA = s3a.getOpenSessions(); } expected--; } Assert.assertEquals(0, setA.size()); } 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 } } }
54,599
Bug 54599 DataSource password is exposed to applications via toString method
On the server side, create a DataSource using "org.apache.tomcat.jdbc.pool.DataSourceFactory". Ex: <Resource auth="Container" description="" name="jdbc/testTomcatJdbc" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" type="javax.sql.DataSource" username="sa" password="super-secret" driverClassName="org.h2.Driver" url="jdbc:h2:mem:test" minIdle="1" initialSize="1" /> In a web application, create a JSP file, add the following: <%@ page import="javax.naming.*" session="false" %> <!DOCTYPE HTML> <html> <head> <title>Display Password!</title> </head> <body> <h1>toString for Tomcat JDBC</h1> <% dataSource = (javax.sql.DataSource) ctx.lookup("java:/comp/env/jdbc/testTomcatJdbc"); out.println("<p>" + dataSource.toString() + "</p>"); %> </body> </html> Access the JSP in your browser. The output from toString on the DataSource will display the password that was configured in the <Resource/> tag. Example Output: toString for Tomcat JDBC org.apache.tomcat.jdbc.pool.DataSource@75cae120{ConnectionPool[defaultAutoCommit=null; defaultReadOnly=null; defaultTransactionIsolation=-1; defaultCatalog=null; driverClassName=org.h2.Driver; maxActive=100; maxIdle=100; minIdle=1; initialSize=1; maxWait=30000; testOnBorrow=false; testOnReturn=false; timeBetweenEvictionRunsMillis=5000; numTestsPerEvictionRun=0; minEvictableIdleTimeMillis=60000; testWhileIdle=false; testOnConnect=false; password=super-secret; url=jdbc:h2:mem:test; username=sa; validationQuery=null; validatorClassName=null; validationInterval=30000; accessToUnderlyingConnectionAllowed=true; removeAbandoned=false; removeAbandonedTimeout=60; logAbandoned=false; connectionProperties=null; initSQL=null; jdbcInterceptors=null; jmxEnabled=true; fairQueue=true; useEquals=true; abandonWhenPercentageFull=0; maxAge=0; useLock=false; dataSource=null; dataSourceJNDI=null; suspectTimeout=0; alternateUsernameAllowed=false; commitOnReturn=false; rollbackOnReturn=false; useDisposableConnectionFacade=true; logValidationErrors=false; propagateInterruptState=false; }
resolved fixed
8445d9a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-22T09:16:06Z
2013-02-22T21:53:20Z
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/PoolProperties.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.jdbc.pool; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.Serializable; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.atomic.AtomicInteger; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * @author Filip Hanik * */ public class PoolProperties implements PoolConfiguration, Cloneable, Serializable { private static final long serialVersionUID = -8519283440854213745L; private static final Log log = LogFactory.getLog(PoolProperties.class); public static final int DEFAULT_MAX_ACTIVE = 100; protected static AtomicInteger poolCounter = new AtomicInteger(0); private volatile Properties dbProperties = new Properties(); private volatile String url = null; private volatile String driverClassName = null; private volatile Boolean defaultAutoCommit = null; private volatile Boolean defaultReadOnly = null; private volatile int defaultTransactionIsolation = DataSourceFactory.UNKNOWN_TRANSACTIONISOLATION; private volatile String defaultCatalog = null; private volatile String connectionProperties; private volatile int initialSize = 10; private volatile int maxActive = DEFAULT_MAX_ACTIVE; private volatile int maxIdle = maxActive; private volatile int minIdle = initialSize; private volatile int maxWait = 30000; private volatile String validationQuery; private volatile String validatorClassName; private volatile Validator validator; private volatile boolean testOnBorrow = false; private volatile boolean testOnReturn = false; private volatile boolean testWhileIdle = false; private volatile int timeBetweenEvictionRunsMillis = 5000; private volatile int numTestsPerEvictionRun; private volatile int minEvictableIdleTimeMillis = 60000; private volatile boolean accessToUnderlyingConnectionAllowed = true; private volatile boolean removeAbandoned = false; private volatile int removeAbandonedTimeout = 60; private volatile boolean logAbandoned = false; private volatile String name = "Tomcat Connection Pool["+(poolCounter.addAndGet(1))+"-"+System.identityHashCode(PoolProperties.class)+"]"; private volatile String password; private volatile String username; private volatile long validationInterval = 30000; private volatile boolean jmxEnabled = true; private volatile String initSQL; private volatile boolean testOnConnect =false; private volatile String jdbcInterceptors=null; private volatile boolean fairQueue = true; private volatile boolean useEquals = true; private volatile int abandonWhenPercentageFull = 0; private volatile long maxAge = 0; private volatile boolean useLock = false; private volatile InterceptorDefinition[] interceptors = null; private volatile int suspectTimeout = 0; private volatile Object dataSource = null; private volatile String dataSourceJNDI = null; private volatile boolean alternateUsernameAllowed = false; private volatile boolean commitOnReturn = false; private volatile boolean rollbackOnReturn = false; private volatile boolean useDisposableConnectionFacade = true; private volatile boolean logValidationErrors = false; private volatile boolean propagateInterruptState = false; /** * {@inheritDoc} */ @Override public void setAbandonWhenPercentageFull(int percentage) { if (percentage<0) abandonWhenPercentageFull = 0; else if (percentage>100) abandonWhenPercentageFull = 100; else abandonWhenPercentageFull = percentage; } /** * {@inheritDoc} */ @Override public int getAbandonWhenPercentageFull() { return abandonWhenPercentageFull; } /** * {@inheritDoc} */ @Override public boolean isFairQueue() { return fairQueue; } /** * {@inheritDoc} */ @Override public void setFairQueue(boolean fairQueue) { this.fairQueue = fairQueue; } /** * {@inheritDoc} */ @Override public boolean isAccessToUnderlyingConnectionAllowed() { return accessToUnderlyingConnectionAllowed; } /** * {@inheritDoc} */ @Override public String getConnectionProperties() { return connectionProperties; } /** * {@inheritDoc} */ @Override public Properties getDbProperties() { return dbProperties; } /** * {@inheritDoc} */ @Override public Boolean isDefaultAutoCommit() { return defaultAutoCommit; } /** * {@inheritDoc} */ @Override public String getDefaultCatalog() { return defaultCatalog; } /** * {@inheritDoc} */ @Override public Boolean isDefaultReadOnly() { return defaultReadOnly; } /** * {@inheritDoc} */ @Override public int getDefaultTransactionIsolation() { return defaultTransactionIsolation; } /** * {@inheritDoc} */ @Override public String getDriverClassName() { return driverClassName; } /** * {@inheritDoc} */ @Override public int getInitialSize() { return initialSize; } /** * {@inheritDoc} */ @Override public boolean isLogAbandoned() { return logAbandoned; } /** * {@inheritDoc} */ @Override public int getMaxActive() { return maxActive; } /** * {@inheritDoc} */ @Override public int getMaxIdle() { return maxIdle; } /** * {@inheritDoc} */ @Override public int getMaxWait() { return maxWait; } /** * {@inheritDoc} */ @Override public int getMinEvictableIdleTimeMillis() { return minEvictableIdleTimeMillis; } /** * {@inheritDoc} */ @Override public int getMinIdle() { return minIdle; } /** * {@inheritDoc} */ @Override public String getName() { return name; } /** * {@inheritDoc} */ @Override public int getNumTestsPerEvictionRun() { return numTestsPerEvictionRun; } /** * {@inheritDoc} */ @Override public String getPassword() { return password; } /** * {@inheritDoc} */ @Override public String getPoolName() { return getName(); } /** * {@inheritDoc} */ @Override public boolean isRemoveAbandoned() { return removeAbandoned; } /** * {@inheritDoc} */ @Override public int getRemoveAbandonedTimeout() { return removeAbandonedTimeout; } /** * {@inheritDoc} */ @Override public boolean isTestOnBorrow() { return testOnBorrow; } /** * {@inheritDoc} */ @Override public boolean isTestOnReturn() { return testOnReturn; } /** * {@inheritDoc} */ @Override public boolean isTestWhileIdle() { return testWhileIdle; } /** * {@inheritDoc} */ @Override public int getTimeBetweenEvictionRunsMillis() { return timeBetweenEvictionRunsMillis; } /** * {@inheritDoc} */ @Override public String getUrl() { return url; } /** * {@inheritDoc} */ @Override public String getUsername() { return username; } /** * {@inheritDoc} */ @Override public String getValidationQuery() { return validationQuery; } /** * {@inheritDoc} */ @Override public String getValidatorClassName() { return validatorClassName; } /** * {@inheritDoc} */ @Override public Validator getValidator() { return validator; } /** * {@inheritDoc} */ @Override public void setValidator(Validator validator) { this.validator = validator; if (validator!=null) { this.validatorClassName = validator.getClass().getName(); } else { this.validatorClassName = null; } } /** * {@inheritDoc} */ @Override public long getValidationInterval() { return validationInterval; } /** * {@inheritDoc} */ @Override public String getInitSQL() { return initSQL; } /** * {@inheritDoc} */ @Override public boolean isTestOnConnect() { return testOnConnect; } /** * {@inheritDoc} */ @Override public String getJdbcInterceptors() { return jdbcInterceptors; } /** * {@inheritDoc} */ @Override public InterceptorDefinition[] getJdbcInterceptorsAsArray() { if (interceptors == null) { if (jdbcInterceptors==null) { interceptors = new InterceptorDefinition[0]; } else { String[] interceptorValues = jdbcInterceptors.split(";"); InterceptorDefinition[] definitions = new InterceptorDefinition[interceptorValues.length+1]; //always add the trap interceptor to the mix definitions[0] = new InterceptorDefinition(TrapException.class); for (int i=0; i<interceptorValues.length; i++) { int propIndex = interceptorValues[i].indexOf("("); int endIndex = interceptorValues[i].indexOf(")"); if (propIndex<0 || endIndex<0 || endIndex <= propIndex) { definitions[i+1] = new InterceptorDefinition(interceptorValues[i].trim()); } else { String name = interceptorValues[i].substring(0,propIndex).trim(); definitions[i+1] = new InterceptorDefinition(name); String propsAsString = interceptorValues[i].substring(propIndex+1, interceptorValues[i].length()-1); String[] props = propsAsString.split(","); for (int j=0; j<props.length; j++) { int pidx = props[j].indexOf("="); String propName = props[j].substring(0,pidx).trim(); String propValue = props[j].substring(pidx+1).trim(); definitions[i+1].addProperty(new InterceptorProperty(propName,propValue)); } } } interceptors = definitions; } } return interceptors; } /** * {@inheritDoc} */ @Override public void setAccessToUnderlyingConnectionAllowed(boolean accessToUnderlyingConnectionAllowed) { // NOOP } /** * {@inheritDoc} */ @Override public void setConnectionProperties(String connectionProperties) { this.connectionProperties = connectionProperties; getProperties(connectionProperties, getDbProperties()); } /** * {@inheritDoc} */ @Override public void setDbProperties(Properties dbProperties) { this.dbProperties = dbProperties; } /** * {@inheritDoc} */ @Override public void setDefaultAutoCommit(Boolean defaultAutoCommit) { this.defaultAutoCommit = defaultAutoCommit; } /** * {@inheritDoc} */ @Override public void setDefaultCatalog(String defaultCatalog) { this.defaultCatalog = defaultCatalog; } /** * {@inheritDoc} */ @Override public void setDefaultReadOnly(Boolean defaultReadOnly) { this.defaultReadOnly = defaultReadOnly; } /** * {@inheritDoc} */ @Override public void setDefaultTransactionIsolation(int defaultTransactionIsolation) { this.defaultTransactionIsolation = defaultTransactionIsolation; } /** * {@inheritDoc} */ @Override public void setDriverClassName(String driverClassName) { this.driverClassName = driverClassName; } /** * {@inheritDoc} */ @Override public void setInitialSize(int initialSize) { this.initialSize = initialSize; } /** * {@inheritDoc} */ @Override public void setLogAbandoned(boolean logAbandoned) { this.logAbandoned = logAbandoned; } /** * {@inheritDoc} */ @Override public void setMaxActive(int maxActive) { this.maxActive = maxActive; } /** * {@inheritDoc} */ @Override public void setMaxIdle(int maxIdle) { this.maxIdle = maxIdle; } /** * {@inheritDoc} */ @Override public void setMaxWait(int maxWait) { this.maxWait = maxWait; } /** * {@inheritDoc} */ @Override public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) { this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis; } /** * {@inheritDoc} */ @Override public void setMinIdle(int minIdle) { this.minIdle = minIdle; } /** * {@inheritDoc} */ @Override public void setName(String name) { this.name = name; } /** * {@inheritDoc} */ @Override public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) { this.numTestsPerEvictionRun = numTestsPerEvictionRun; } /** * {@inheritDoc} */ @Override public void setPassword(String password) { this.password = password; } /** * {@inheritDoc} */ @Override public void setRemoveAbandoned(boolean removeAbandoned) { this.removeAbandoned = removeAbandoned; } /** * {@inheritDoc} */ @Override public void setRemoveAbandonedTimeout(int removeAbandonedTimeout) { this.removeAbandonedTimeout = removeAbandonedTimeout; } /** * {@inheritDoc} */ @Override public void setTestOnBorrow(boolean testOnBorrow) { this.testOnBorrow = testOnBorrow; } /** * {@inheritDoc} */ @Override public void setTestWhileIdle(boolean testWhileIdle) { this.testWhileIdle = testWhileIdle; } /** * {@inheritDoc} */ @Override public void setTestOnReturn(boolean testOnReturn) { this.testOnReturn = testOnReturn; } /** * {@inheritDoc} */ @Override public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) { this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis; } /** * {@inheritDoc} */ @Override public void setUrl(String url) { this.url = url; } /** * {@inheritDoc} */ @Override public void setUsername(String username) { this.username = username; } /** * {@inheritDoc} */ @Override public void setValidationInterval(long validationInterval) { this.validationInterval = validationInterval; } /** * {@inheritDoc} */ @Override public void setValidationQuery(String validationQuery) { this.validationQuery = validationQuery; } /** * {@inheritDoc} */ @Override public void setValidatorClassName(String className) { this.validatorClassName = className; validator = null; if (className == null) { return; } try { Class<Validator> validatorClass = (Class<Validator>)Class.forName(className); validator = validatorClass.newInstance(); } catch (ClassNotFoundException e) { log.warn("The class "+className+" cannot be found.", e); } catch (ClassCastException e) { log.warn("The class "+className+" does not implement the Validator interface.", e); } catch (InstantiationException e) { log.warn("An object of class "+className+" cannot be instantiated. Make sure that "+ "it includes an implicit or explicit no-arg constructor.", e); } catch (IllegalAccessException e) { log.warn("The class "+className+" or its no-arg constructor are inaccessible.", e); } } /** * {@inheritDoc} */ @Override public void setInitSQL(String initSQL) { this.initSQL = initSQL; } /** * {@inheritDoc} */ @Override public void setTestOnConnect(boolean testOnConnect) { this.testOnConnect = testOnConnect; } /** * {@inheritDoc} */ @Override public void setJdbcInterceptors(String jdbcInterceptors) { this.jdbcInterceptors = jdbcInterceptors; this.interceptors = null; } @Override public String toString() { StringBuilder buf = new StringBuilder("ConnectionPool["); try { String[] fields = DataSourceFactory.ALL_PROPERTIES; for (int i=0; i<fields.length; i++) { final String[] prefix = new String[] {"get","is"}; for (int j=0; j<prefix.length; j++) { String name = prefix[j] + fields[i].substring(0, 1).toUpperCase(Locale.ENGLISH) + fields[i].substring(1); Method m = null; try { m = getClass().getMethod(name); }catch (NoSuchMethodException nm) { continue; } buf.append(fields[i]); buf.append("="); buf.append(m.invoke(this, new Object[0])); buf.append("; "); break; } } }catch (Exception x) { //shouldn;t happen x.printStackTrace(); } return buf.toString(); } public static int getPoolCounter() { return poolCounter.get(); } /** * {@inheritDoc} */ @Override public boolean isJmxEnabled() { return jmxEnabled; } /** * {@inheritDoc} */ @Override public void setJmxEnabled(boolean jmxEnabled) { this.jmxEnabled = jmxEnabled; } /** * {@inheritDoc} */ @Override public Boolean getDefaultAutoCommit() { return defaultAutoCommit; } /** * {@inheritDoc} */ @Override public Boolean getDefaultReadOnly() { return defaultReadOnly; } /** * {@inheritDoc} */ @Override public int getSuspectTimeout() { return this.suspectTimeout; } /** * {@inheritDoc} */ @Override public void setSuspectTimeout(int seconds) { this.suspectTimeout = seconds; } /** * {@inheritDoc} */ @Override public boolean isPoolSweeperEnabled() { boolean timer = getTimeBetweenEvictionRunsMillis()>0; boolean result = timer && (isRemoveAbandoned() && getRemoveAbandonedTimeout()>0); result = result || (timer && getSuspectTimeout()>0); result = result || (timer && isTestWhileIdle() && getValidationQuery()!=null); result = result || (timer && getMinEvictableIdleTimeMillis()>0); return result; } public static class InterceptorDefinition implements Serializable { private static final long serialVersionUID = 1L; protected String className; protected Map<String,InterceptorProperty> properties = new HashMap<>(); protected volatile Class<?> clazz = null; public InterceptorDefinition(String className) { this.className = className; } public InterceptorDefinition(Class<?> cl) { this(cl.getName()); clazz = cl; } public String getClassName() { return className; } public void addProperty(String name, String value) { InterceptorProperty p = new InterceptorProperty(name,value); addProperty(p); } public void addProperty(InterceptorProperty p) { properties.put(p.getName(), p); } public Map<String,InterceptorProperty> getProperties() { return properties; } @SuppressWarnings("unchecked") public Class<? extends JdbcInterceptor> getInterceptorClass() throws ClassNotFoundException { if (clazz==null) { if (getClassName().indexOf(".")<0) { if (log.isDebugEnabled()) { log.debug("Loading interceptor class:"+PoolConfiguration.PKG_PREFIX+getClassName()); } clazz = Class.forName(PoolConfiguration.PKG_PREFIX+getClassName(), true, this.getClass().getClassLoader()); } else { if (log.isDebugEnabled()) { log.debug("Loading interceptor class:"+getClassName()); } clazz = Class.forName(getClassName(), true, this.getClass().getClassLoader()); } } return (Class<? extends JdbcInterceptor>)clazz; } } public static class InterceptorProperty implements Serializable { private static final long serialVersionUID = 1L; String name; String value; public InterceptorProperty(String name, String value) { assert(name!=null); this.name = name; this.value = value; } public String getName() { return name; } public String getValue() { return value; } public boolean getValueAsBoolean(boolean def) { if (value==null) return def; if ("true".equals(value)) return true; if ("false".equals(value)) return false; return def; } public int getValueAsInt(int def) { if (value==null) return def; try { int v = Integer.parseInt(value); return v; }catch (NumberFormatException nfe) { return def; } } public long getValueAsLong(long def) { if (value==null) return def; try { return Long.parseLong(value); }catch (NumberFormatException nfe) { return def; } } public byte getValueAsByte(byte def) { if (value==null) return def; try { return Byte.parseByte(value); }catch (NumberFormatException nfe) { return def; } } public short getValueAsShort(short def) { if (value==null) return def; try { return Short.parseShort(value); }catch (NumberFormatException nfe) { return def; } } public float getValueAsFloat(float def) { if (value==null) return def; try { return Float.parseFloat(value); }catch (NumberFormatException nfe) { return def; } } public double getValueAsDouble(double def) { if (value==null) return def; try { return Double.parseDouble(value); }catch (NumberFormatException nfe) { return def; } } public char getValueAschar(char def) { if (value==null) return def; try { return value.charAt(0); }catch (StringIndexOutOfBoundsException nfe) { return def; } } @Override public int hashCode() { return name.hashCode(); } @Override public boolean equals(Object o) { if (o==this) return true; if (o instanceof InterceptorProperty) { InterceptorProperty other = (InterceptorProperty)o; return other.name.equals(this.name); } return false; } } /** * {@inheritDoc} */ @Override public boolean isUseEquals() { return useEquals; } /** * {@inheritDoc} */ @Override public void setUseEquals(boolean useEquals) { this.useEquals = useEquals; } /** * {@inheritDoc} */ @Override public long getMaxAge() { return maxAge; } /** * {@inheritDoc} */ @Override public void setMaxAge(long maxAge) { this.maxAge = maxAge; } /** * {@inheritDoc} */ @Override public boolean getUseLock() { return useLock; } /** * {@inheritDoc} */ @Override public void setUseLock(boolean useLock) { this.useLock = useLock; } /** * {@inheritDoc} */ @Override public void setDataSource(Object ds) { this.dataSource = ds; } /** * {@inheritDoc} */ @Override public Object getDataSource() { return dataSource; } /** * {@inheritDoc} */ @Override public void setDataSourceJNDI(String jndiDS) { this.dataSourceJNDI = jndiDS; } /** * {@inheritDoc} */ @Override public String getDataSourceJNDI() { return this.dataSourceJNDI; } public static Properties getProperties(String propText, Properties props) { if (props==null) props = new Properties(); if (propText != null) { try { props.load(new ByteArrayInputStream(propText.replace(';', '\n').getBytes())); }catch (IOException x) { throw new RuntimeException(x); } } return props; } /** * {@inheritDoc} */ @Override public boolean isAlternateUsernameAllowed() { return alternateUsernameAllowed; } /** * {@inheritDoc} */ @Override public void setAlternateUsernameAllowed(boolean alternateUsernameAllowed) { this.alternateUsernameAllowed = alternateUsernameAllowed; } /** * {@inheritDoc} */ @Override public void setCommitOnReturn(boolean commitOnReturn) { this.commitOnReturn = commitOnReturn; } /** * {@inheritDoc} */ @Override public boolean getCommitOnReturn() { return this.commitOnReturn; } /** * {@inheritDoc} */ @Override public void setRollbackOnReturn(boolean rollbackOnReturn) { this.rollbackOnReturn = rollbackOnReturn; } /** * {@inheritDoc} */ @Override public boolean getRollbackOnReturn() { return this.rollbackOnReturn; } /** * {@inheritDoc} */ @Override public void setUseDisposableConnectionFacade(boolean useDisposableConnectionFacade) { this.useDisposableConnectionFacade = useDisposableConnectionFacade; } /** * {@inheritDoc} */ @Override public boolean getUseDisposableConnectionFacade() { return useDisposableConnectionFacade; } /** * {@inheritDoc} */ @Override public void setLogValidationErrors(boolean logValidationErrors) { this.logValidationErrors = logValidationErrors; } /** * {@inheritDoc} */ @Override public boolean getLogValidationErrors() { return this.logValidationErrors; } /** * {@inheritDoc} */ @Override public boolean getPropagateInterruptState() { return propagateInterruptState; } /** * {@inheritDoc} */ @Override public void setPropagateInterruptState(boolean propagateInterruptState) { this.propagateInterruptState = propagateInterruptState; } @Override protected Object clone() throws CloneNotSupportedException { // TODO Auto-generated method stub return super.clone(); } }
54,732
Bug 54732 StatementCache interceptor does not forward calls to Statement.close() which causes memory leaks
null
resolved fixed
8cf47b4
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-22T13:44:00Z
2013-03-20T20:06:40Z
modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/interceptor/StatementCache.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.jdbc.pool.interceptor; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Statement; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import org.apache.tomcat.jdbc.pool.ConnectionPool; import org.apache.tomcat.jdbc.pool.PoolProperties.InterceptorProperty; import org.apache.tomcat.jdbc.pool.PooledConnection; public class StatementCache extends StatementDecoratorInterceptor { protected static final String[] ALL_TYPES = new String[] {PREPARE_STATEMENT,PREPARE_CALL}; protected static final String[] CALLABLE_TYPE = new String[] {PREPARE_CALL}; protected static final String[] PREPARED_TYPE = new String[] {PREPARE_STATEMENT}; protected static final String[] NO_TYPE = new String[] {}; protected static final String STATEMENT_CACHE_ATTR = StatementCache.class.getName() + ".cache"; /*begin properties for the statement cache*/ private boolean cachePrepared = true; private boolean cacheCallable = false; private int maxCacheSize = 50; private PooledConnection pcon; private String[] types; public boolean isCachePrepared() { return cachePrepared; } public boolean isCacheCallable() { return cacheCallable; } public int getMaxCacheSize() { return maxCacheSize; } public String[] getTypes() { return types; } public AtomicInteger getCacheSize() { return cacheSize; } @Override public void setProperties(Map<String, InterceptorProperty> properties) { super.setProperties(properties); InterceptorProperty p = properties.get("prepared"); if (p!=null) cachePrepared = p.getValueAsBoolean(cachePrepared); p = properties.get("callable"); if (p!=null) cacheCallable = p.getValueAsBoolean(cacheCallable); p = properties.get("max"); if (p!=null) maxCacheSize = p.getValueAsInt(maxCacheSize); if (cachePrepared && cacheCallable) { this.types = ALL_TYPES; } else if (cachePrepared) { this.types = PREPARED_TYPE; } else if (cacheCallable) { this.types = CALLABLE_TYPE; } else { this.types = NO_TYPE; } } /*end properties for the statement cache*/ /*begin the cache size*/ private static ConcurrentHashMap<ConnectionPool,AtomicInteger> cacheSizeMap = new ConcurrentHashMap<>(); private AtomicInteger cacheSize; @Override public void poolStarted(ConnectionPool pool) { cacheSizeMap.putIfAbsent(pool, new AtomicInteger(0)); super.poolStarted(pool); } @Override public void poolClosed(ConnectionPool pool) { cacheSizeMap.remove(pool); super.poolClosed(pool); } /*end the cache size*/ /*begin the actual statement cache*/ @Override public void reset(ConnectionPool parent, PooledConnection con) { super.reset(parent, con); if (parent==null) { cacheSize = null; this.pcon = null; } else { cacheSize = cacheSizeMap.get(parent); this.pcon = con; if (!pcon.getAttributes().containsKey(STATEMENT_CACHE_ATTR)) { ConcurrentHashMap<String,CachedStatement> cache = new ConcurrentHashMap<>(); pcon.getAttributes().put(STATEMENT_CACHE_ATTR,cache); } } } @Override public void disconnected(ConnectionPool parent, PooledConnection con, boolean finalizing) { ConcurrentHashMap<String,CachedStatement> statements = (ConcurrentHashMap<String,CachedStatement>)con.getAttributes().get(STATEMENT_CACHE_ATTR); if (statements!=null) { for (Map.Entry<String, CachedStatement> p : statements.entrySet()) { closeStatement(p.getValue()); } statements.clear(); } super.disconnected(parent, con, finalizing); } public void closeStatement(CachedStatement st) { if (st==null) return; st.forceClose(); } @Override protected Object createDecorator(Object proxy, Method method, Object[] args, Object statement, Constructor<?> constructor, String sql) throws InstantiationException, IllegalAccessException, InvocationTargetException { boolean process = process(this.types, method, false); if (process) { Object result = null; CachedStatement statementProxy = new CachedStatement((Statement)statement,sql); result = constructor.newInstance(new Object[] { statementProxy }); statementProxy.setActualProxy(result); statementProxy.setConnection(proxy); statementProxy.setConstructor(constructor); return result; } else { return super.createDecorator(proxy, method, args, statement, constructor, sql); } } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { boolean process = process(this.types, method, false); if (process && args.length>0 && args[0] instanceof String) { CachedStatement statement = isCached((String)args[0]); if (statement!=null) { //remove it from the cache since it is used removeStatement(statement); return statement.getActualProxy(); } else { return super.invoke(proxy, method, args); } } else { return super.invoke(proxy,method,args); } } public CachedStatement isCached(String sql) { ConcurrentHashMap<String,CachedStatement> cache = (ConcurrentHashMap<String,CachedStatement>)pcon.getAttributes().get(STATEMENT_CACHE_ATTR); return cache.get(sql); } public boolean cacheStatement(CachedStatement proxy) { ConcurrentHashMap<String,CachedStatement> cache = (ConcurrentHashMap<String,CachedStatement>)pcon.getAttributes().get(STATEMENT_CACHE_ATTR); if (proxy.getSql()==null) { return false; } else if (cache.containsKey(proxy.getSql())) { return false; } else if (cacheSize.get()>=maxCacheSize) { return false; } else if (cacheSize.incrementAndGet()>maxCacheSize) { cacheSize.decrementAndGet(); return false; } else { //cache the statement cache.put(proxy.getSql(), proxy); return true; } } public boolean removeStatement(CachedStatement proxy) { ConcurrentHashMap<String,CachedStatement> cache = (ConcurrentHashMap<String,CachedStatement>)pcon.getAttributes().get(STATEMENT_CACHE_ATTR); if (cache.remove(proxy.getSql()) != null) { cacheSize.decrementAndGet(); return true; } else { return false; } } /*end the actual statement cache*/ protected class CachedStatement extends StatementDecoratorInterceptor.StatementProxy<Statement> { boolean cached = false; public CachedStatement(Statement parent, String sql) { super(parent, sql); } @Override public void closeInvoked() { //should we cache it boolean shouldClose = true; if (cacheSize.get() < maxCacheSize) { //cache a proxy so that we don't reuse the facade CachedStatement proxy = new CachedStatement(getDelegate(),getSql()); try { //create a new facade Object actualProxy = getConstructor().newInstance(new Object[] { proxy }); proxy.setActualProxy(actualProxy); proxy.setConnection(getConnection()); proxy.setConstructor(getConstructor()); if (cacheStatement(proxy)) { proxy.cached = true; shouldClose = false; } } catch (Exception x) { removeStatement(proxy); } } closed = true; delegate = null; if (shouldClose) { super.closeInvoked(); } } public void forceClose() { removeStatement(this); super.closeInvoked(); } } }
54,732
Bug 54732 StatementCache interceptor does not forward calls to Statement.close() which causes memory leaks
null
resolved fixed
8cf47b4
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-22T13:44:00Z
2013-03-20T20:06:40Z
modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/interceptor/StatementCounterInterceptor.java
54,732
Bug 54732 StatementCache interceptor does not forward calls to Statement.close() which causes memory leaks
null
resolved fixed
8cf47b4
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-22T13:44:00Z
2013-03-20T20:06:40Z
modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/test/TestStatementCache.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.jdbc.test; import java.sql.Connection; import java.sql.PreparedStatement; import org.junit.After; import org.junit.Assert; import org.junit.Test; import org.apache.tomcat.jdbc.pool.interceptor.StatementCache; public class TestStatementCache extends DefaultTestCase { private static volatile TestStatementCacheInterceptor interceptor = null; @Override @After public void tearDown() throws Exception { interceptor = null; super.tearDown(); } private void config(boolean cachePrepared, boolean cacheCallable, int max) { datasource.getPoolProperties().setJdbcInterceptors(TestStatementCacheInterceptor.class.getName()+ "(prepared="+cachePrepared+",callable="+cacheCallable+",max="+max+")"); } @Test public void testIsCacheEnabled() throws Exception { config(true,true,50); datasource.getConnection().close(); Assert.assertNotNull("Interceptor was not created.", interceptor); } @Test public void testCacheProperties() throws Exception { config(true,true,50); datasource.getConnection().close(); Assert.assertTrue(interceptor.isCacheCallable()); Assert.assertTrue(interceptor.isCachePrepared()); Assert.assertEquals(50,interceptor.getMaxCacheSize()); } @Test public void testCacheProperties2() throws Exception { config(false,false,100); datasource.getConnection().close(); Assert.assertFalse(interceptor.isCacheCallable()); Assert.assertFalse(interceptor.isCachePrepared()); Assert.assertEquals(100,interceptor.getMaxCacheSize()); } @Test public void testPreparedStatementCache() throws Exception { config(true,false,100); Connection con = datasource.getConnection(); PreparedStatement ps1 = con.prepareStatement("select 1"); PreparedStatement ps2 = con.prepareStatement("select 1"); Assert.assertEquals(0,interceptor.getCacheSize().get()); ps1.close(); Assert.assertTrue(ps1.isClosed()); Assert.assertEquals(1,interceptor.getCacheSize().get()); PreparedStatement ps3 = con.prepareStatement("select 1"); Assert.assertEquals(0,interceptor.getCacheSize().get()); ps2.close(); Assert.assertTrue(ps2.isClosed()); ps3.close(); Assert.assertTrue(ps3.isClosed()); Assert.assertEquals(1,interceptor.getCacheSize().get()); } @Test public void testPreparedStatementCache2() throws Exception { init(); config(false,false,100); Connection con = datasource.getConnection(); PreparedStatement ps1 = con.prepareStatement("select 1"); PreparedStatement ps2 = con.prepareStatement("select 1"); Assert.assertEquals(0,interceptor.getCacheSize().get()); ps1.close(); Assert.assertTrue(ps1.isClosed()); Assert.assertEquals(0,interceptor.getCacheSize().get()); PreparedStatement ps3 = con.prepareStatement("select 1"); Assert.assertEquals(0,interceptor.getCacheSize().get()); ps2.close(); Assert.assertTrue(ps2.isClosed()); ps3.close(); Assert.assertTrue(ps3.isClosed()); Assert.assertEquals(0,interceptor.getCacheSize().get()); } @Test public void testMaxCacheSize() throws Exception { init(); config(true,false,100); Connection con1 = datasource.getConnection(); Connection con2 = datasource.getConnection(); for (int i=0; i<120; i++) { @SuppressWarnings("resource") // Connections are closed below Connection con = (i%2==0)?con1:con2; PreparedStatement ps = con.prepareStatement("select "+i); ps.close(); } Assert.assertEquals(100,interceptor.getCacheSize().get()); con1.close(); con2.close(); } public static class TestStatementCacheInterceptor extends StatementCache { public TestStatementCacheInterceptor() { TestStatementCache.interceptor = this; } } }
54,748
Bug 54748 IOException in echo WebSocket example
The IOException "New frame received after a close control frame" is raised after pressing Disconnect. The exception can be detected by adding an onError method to EchoEndpoint.
resolved fixed
cf0c064
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-25T21:54:33Z
2013-03-25T14:00:00Z
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 boolean closed = false; 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 (closed) { throw new IOException(sm.getString("wsFrame.closed")); } if (!processInitialHeader()) { break; } } 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 { 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)))); } } 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) { closed = true; 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) { MessageHandler mh = wsSession.getTextMessageHandler(); if (mh != null) { 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) { MessageHandler mh = wsSession.getBinaryMessageHandler(); if (mh != null) { 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; } private static enum State { NEW_FRAME, PARTIAL_HEADER, DATA } }
54,748
Bug 54748 IOException in echo WebSocket example
The IOException "New frame received after a close control frame" is raised after pressing Disconnect. The exception can be detected by adding an onError method to EchoEndpoint.
resolved fixed
cf0c064
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-25T21:54:33Z
2013-03-25T14:00:00Z
java/org/apache/tomcat/websocket/WsFrameClient.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.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; public class WsFrameClient extends WsFrameBase { private final ByteBuffer response; private final AsynchronousSocketChannel channel; private final CompletionHandler<Integer,Void> handler; public WsFrameClient(ByteBuffer response, AsynchronousSocketChannel channel, WsSession wsSession) { super(wsSession); this.response = response; this.channel = channel; this.handler = new WsFrameClientCompletionHandler(); try { processSocketRead(); } catch (IOException e) { close(e); } } private void processSocketRead() throws IOException { while (response.hasRemaining()) { int remaining = response.remaining(); int toCopy = Math.min(remaining, inputBuffer.length - writePos); // Copy remaining bytes read in HTTP phase to input buffer used by // frame processing response.get(inputBuffer, writePos, toCopy); writePos += toCopy; // Process the data we have processInputBuffer(); } response.clear(); // Get some more data channel.read(response, null, handler); } private final void close(Throwable t) { CloseReason cr; if (t instanceof WsIOException) { cr = ((WsIOException) t).getCloseReason(); } else { cr = new CloseReason( CloseCodes.CLOSED_ABNORMALLY, t.getMessage()); } try { wsSession.close(cr); } catch (IOException ignore) { // Ignore } } @Override protected boolean isMasked() { // Data is from the server so it is not masked return false; } private class WsFrameClientCompletionHandler implements CompletionHandler<Integer,Void> { @Override public void completed(Integer result, Void attachment) { response.flip(); try { processSocketRead(); } catch (IOException e) { close(e); } } @Override public void failed(Throwable exc, Void attachment) { close(exc); } } }
54,748
Bug 54748 IOException in echo WebSocket example
The IOException "New frame received after a close control frame" is raised after pressing Disconnect. The exception can be detected by adding an onError method to EchoEndpoint.
resolved fixed
cf0c064
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-25T21:54:33Z
2013-03-25T14:00:00Z
java/org/apache/tomcat/websocket/server/WsFrameServer.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 javax.servlet.ServletInputStream; import org.apache.tomcat.websocket.WsFrameBase; import org.apache.tomcat.websocket.WsSession; public class WsFrameServer extends WsFrameBase { private final ServletInputStream sis; private final Object connectionReadLock = new Object(); public WsFrameServer(ServletInputStream sis, WsSession wsSession) { super(wsSession); this.sis = sis; } /** * Called when there is data in the ServletInputStream to process. */ public void onDataAvailable() throws IOException { synchronized (connectionReadLock) { while (sis.isReady()) { // Fill up the input buffer with as much data as we can int read = sis.read( inputBuffer, writePos, inputBuffer.length - writePos); if (read == 0) { return; } if (read == -1) { throw new EOFException(); } writePos += read; processInputBuffer(); } } } @Override protected boolean isMasked() { // Data is from the client so it should be masked return true; } }
54,755
Bug 54755 Type-based Endpoint's cannot be deployed by instance
For type-based Endpoint's, WsServlet instantiates the Endpoint via reflection instead of using the Configurator as is done in PojoEndpointServer: sec.getConfigurator().getEndpointInstance(sec.getEndpointClass())
resolved fixed
d025179
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-03-26T21:19:51Z
2013-03-26T17:46:40Z
java/org/apache/tomcat/websocket/server/WsServlet.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; import java.util.Map.Entry; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; 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 WsServlet extends HttpServlet { private static final long serialVersionUID = 1L; 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 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Information required to send the server handshake message String key; String subProtocol = null; List<Extension> extensions = Collections.emptyList(); if (!headerContainsToken(req, Constants.UPGRADE_HEADER_NAME, Constants.UPGRADE_HEADER_VALUE)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } 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(); Map<String,String> pathParameters = sc.getPathParameters( req.getServletPath(), req.getPathInfo()); ServerEndpointConfig sec = sc.getServerEndpointConfiguration( req.getServletPath(), pathParameters); // 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.getEndpointClass().newInstance(); } else { ep = new PojoEndpointServer(); } } catch (InstantiationException | IllegalAccessException 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, pathParameters, req.isSecure()); } /* * 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,851
Bug 54851 Folder without web-fragment.xml should not impact the status of distributable
null
resolved fixed
e97e158
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-16T13:51:06Z
2013-04-16T13:46:40Z
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.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.Properties; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.annotation.HandlesTypes; 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.StandardContext; import org.apache.catalina.core.StandardHost; import org.apache.catalina.deploy.ErrorPage; import org.apache.catalina.deploy.FilterDef; import org.apache.catalina.deploy.FilterMap; import org.apache.catalina.deploy.LoginConfig; import org.apache.catalina.deploy.SecurityConstraint; import org.apache.catalina.deploy.ServletDef; 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.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; /** * The list of JARs that will be skipped when scanning a web application * for JARs. This means the JAR will not be scanned for web fragments, SCIs, * annotations or classes that match @HandlesTypes. */ private static final Set<String> pluggabilityJarsToSkip = new HashSet<>(); 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; // Load the list of JARS to skip addJarsToSkip(Constants.DEFAULT_JARS_TO_SKIP); addJarsToSkip(Constants.PLUGGABILITY_JARS_TO_SKIP); } private static void addJarsToSkip(String systemPropertyName) { String jarList = System.getProperty(systemPropertyName); if (jarList != null) { StringTokenizer tokenizer = new StringTokenizer(jarList, ","); while (tokenizer.hasMoreElements()) { pluggabilityJarsToSkip.add(tokenizer.nextToken()); } } } /** * 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; /** * 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) { String docBase = context.getDocBase(); context.setDocBase(originalDocBase); originalDocBase = docBase; } } else if (event.getType().equals(Lifecycle.CONFIGURE_STOP_EVENT)) { if (originalDocBase != null) { String docBase = context.getDocBase(); context.setDocBase(originalDocBase); originalDocBase = docBase; } 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()); stream = contextXml.openStream(); } 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() && (docBase.startsWith(host.getAppBaseFile().getPath())); } 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; } if (originalDocBase == null) { originalDocBase = docBase; } else { docBase = originalDocBase; } 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(); File file = null; if (originalDocBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) { file = new File(System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase + ".war"); } else { file = new File(System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase); } if (log.isDebugEnabled()) { log.debug("Anti locking context[" + context.getName() + "] setting docBase to " + file); } // Cleanup just in case an old deployment is lying around ExpandWar.delete(file); if (ExpandWar.copy(docBaseFile, file)) { context.setDocBase(file.getAbsolutePath()); } } } /** * 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()); try { fixDocBase(); } catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); } } /** * Process a "before start" event for this Context. */ protected synchronized void beforeStart() { 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 Host host = (Host) context.getParent(); String docBase = context.getDocBase(); if ((docBase != null) && (originalDocBase != null)) { File docBaseFile = new File(docBase); if (!docBaseFile.isAbsolute()) { docBaseFile = new File(host.getAppBaseFile(), docBase); } // No need to log failure - it is expected in this case ExpandWar.delete(docBaseFile, 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 // If the JARs have a web-fragment.xml it will be parsed at this // point. 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) { webXml.configureContext(context); } } else { webXml.merge(defaults); convertJsps(webXml); webXml.configureContext(context); } // 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 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(context.getServletContext(), context.getLoader().getClassLoader(), callback, pluggabilityJarsToSkip); return callback.getFragments(); } protected void processAnnotations(Set<WebXml> fragments, boolean handlesTypesOnly) { for(WebXml fragment : fragments) { 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) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); try { 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) 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); } } 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; } } }
54,822
Bug 54822 URL with Query String can't work over SPDY
null
resolved fixed
3da2133
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-19T15:20:53Z
2013-04-10T10:33:20Z
java/org/apache/coyote/spdy/SpdyProcessor.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.io.InterruptedIOException; import java.net.InetAddress; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.http.HttpUpgradeHandler; import org.apache.coyote.AbstractProcessor; import org.apache.coyote.ActionCode; import org.apache.coyote.AsyncContextCallback; import org.apache.coyote.InputBuffer; import org.apache.coyote.OutputBuffer; import org.apache.coyote.Request; import org.apache.coyote.RequestInfo; import org.apache.coyote.Response; import org.apache.tomcat.spdy.SpdyConnection; import org.apache.tomcat.spdy.SpdyContext; import org.apache.tomcat.spdy.SpdyFrame; import org.apache.tomcat.spdy.SpdyStream; 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.MessageBytes; import org.apache.tomcat.util.http.HttpMessages; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.net.AbstractEndpoint; 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; /** * A spdy stream ( multiplexed over a spdy tcp connection ) processed by a * tomcat servlet. * * Based on the AJP processor. */ public class SpdyProcessor extends AbstractProcessor<Object> implements Runnable { // TODO: handle input // TODO: recycle // TODO: swallow input ( recycle only after input close ) // TODO: find a way to inject an OutputBuffer, or interecept close() - // so we can send FIN in the last data packet. private final SpdyConnection spdy; // Associated spdy stream private SpdyStream spdyStream; private final ByteChunk keyBuffer = new ByteChunk(); private boolean error = false; private boolean finished; private SpdyFrame inFrame = null; private boolean outClosed = false; private boolean outCommit = false; public SpdyProcessor(SpdyConnection spdy, AbstractEndpoint endpoint) { super(endpoint); this.spdy = spdy; request.setInputBuffer(new LiteInputBuffer()); response.setOutputBuffer(new LiteOutputBuffer()); } class LiteInputBuffer implements InputBuffer { @Override public int doRead(ByteChunk bchunk, Request request) throws IOException { if (inFrame == null) { // blocking inFrame = spdyStream.getDataFrame(endpoint.getSoTimeout()); } if (inFrame == null) { return -1; // timeout } if (inFrame.remaining() == 0 && inFrame.isHalfClose()) { return -1; } int rd = Math.min(inFrame.remaining(), bchunk.getBytes().length); System.arraycopy(inFrame.data, inFrame.off, bchunk.getBytes(), bchunk.getStart(), rd); inFrame.advance(rd); if (inFrame.remaining() == 0) { if (!inFrame.isHalfClose()) { inFrame = null; } } bchunk.setEnd(bchunk.getEnd() + rd); return rd; } } final class LiteOutputBuffer implements OutputBuffer { long byteCount; @Override public int doWrite(org.apache.tomcat.util.buf.ByteChunk chunk, Response response) throws IOException { if (!response.isCommitted()) { // 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); } spdyStream.sendDataFrame(chunk.getBuffer(), chunk.getStart(), chunk.getLength(), false); byteCount += chunk.getLength(); return chunk.getLength(); } @Override public long getBytesWritten() { return byteCount; } } void onRequest() { Executor exec = spdy.getSpdyContext().getExecutor(); exec.execute(this); } /** * Execute the request. */ @Override public void run() { RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); getAdapter().service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); // log.error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error t.printStackTrace(); response.setStatus(500); getAdapter().log(request, response, 0); error = true; } // TODO: async, etc ( detached mode - use a special light protocol) // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); // TODO: recycle } private void finish() { if (!response.isCommitted()) { response.action(ActionCode.COMMIT, response); } if (finished) return; finished = true; response.finish(); } private static final byte[] EMPTY = new byte[0]; // Processor implementation private void maybeCommit() { if (outCommit) { return; } if (!response.isCommitted()) { // Validate and write response headers sendSynReply(); } } @Override public void action(ActionCode actionCode, Object param) { if (SpdyContext.debug) { // System.err.println(actionCode); } // TODO: async if (actionCode == ActionCode.COMMIT) { maybeCommit(); } else if (actionCode == ActionCode.CLIENT_FLUSH) { maybeCommit(); // try { // flush(true); // } catch (IOException e) { // // Set error flag // error = true; // } } else if (actionCode == ActionCode.DISABLE_SWALLOW_INPUT) { // TODO: Do not swallow request input but // make sure we are closing the connection error = true; } else if (actionCode == ActionCode.CLOSE) { if (outClosed) { return; } outClosed = true; // Close // End the processing of the current request, and stop any further // transactions with the client maybeCommit(); spdyStream.sendDataFrame(EMPTY, 0, 0, true); } else if (actionCode == ActionCode.REQ_SSL_ATTRIBUTE) { // if (!certificates.isNull()) { // ByteChunk certData = certificates.getByteChunk(); // X509Certificate jsseCerts[] = null; // ByteArrayInputStream bais = // new ByteArrayInputStream(certData.getBytes(), // certData.getStart(), // certData.getLength()); // // Fill the elements. // try { // CertificateFactory cf; // if (clientCertProvider == null) { // cf = CertificateFactory.getInstance("X.509"); // } else { // cf = CertificateFactory.getInstance("X.509", // clientCertProvider); // } // while(bais.available() > 0) { // X509Certificate cert = (X509Certificate) // cf.generateCertificate(bais); // if(jsseCerts == null) { // jsseCerts = new X509Certificate[1]; // jsseCerts[0] = cert; // } else { // X509Certificate [] temp = new // X509Certificate[jsseCerts.length+1]; // System.arraycopy(jsseCerts,0,temp,0,jsseCerts.length); // temp[jsseCerts.length] = cert; // jsseCerts = temp; // } // } // } catch (java.security.cert.CertificateException e) { // getLog().error(sm.getString("ajpprocessor.certs.fail"), e); // return; // } catch (NoSuchProviderException e) { // getLog().error(sm.getString("ajpprocessor.certs.fail"), e); // return; // } // request.setAttribute(SSLSupport.CERTIFICATE_KEY, jsseCerts); // } } else if (actionCode == ActionCode.REQ_HOST_ATTRIBUTE) { // Get remote host name using a DNS resolution if (request.remoteHost().isNull()) { try { request.remoteHost().setString( InetAddress.getByName( request.remoteAddr().toString()) .getHostName()); } catch (IOException iex) { // Ignore } } } else if (actionCode == ActionCode.REQ_LOCALPORT_ATTRIBUTE) { String configured = (String) endpoint.getAttribute("proxyPort"); int localPort = 0; if (configured != null) { localPort = Integer.parseInt(configured); } else { localPort = endpoint.getPort(); } request.setLocalPort(localPort); } else if (actionCode == ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE) { InetAddress localAddress = endpoint.getAddress(); String localIp = localAddress == null ? null : localAddress .getHostAddress(); if (localIp == null) { localIp = (String) endpoint.getAttribute("proxyIP"); } if (localIp == null) { localIp = "127.0.0.1"; } request.localAddr().setString(localIp); } else if (actionCode == ActionCode.REQ_HOST_ADDR_ATTRIBUTE) { InetAddress localAddress = endpoint.getAddress(); String localH = localAddress == null ? null : localAddress .getCanonicalHostName(); if (localH == null) { localH = (String) endpoint.getAttribute("proxyName"); } if (localH == null) { localH = "localhost"; } request.localAddr().setString(localH); } else if (actionCode == ActionCode.REQ_SET_BODY_REPLAY) { // // Set the given bytes as the content // ByteChunk bc = (ByteChunk) param; // int length = bc.getLength(); // bodyBytes.setBytes(bc.getBytes(), bc.getStart(), length); // request.setContentLength(length); // first = false; // empty = false; // replay = true; } 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_ASYNC_OPERATION) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncOperation()); } 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 { // TODO: // actionInternal(actionCode, param); } } /** * When committing the response, we have to validate the set of headers, as * well as setup the response filters. */ protected void sendSynReply() { response.setCommitted(true); // Special headers MimeHeaders headers = response.getMimeHeaders(); 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(); if (contentLength >= 0) { headers.setValue("Content-Length").setLong(contentLength); } sendResponseHead(); } private void sendResponseHead() { SpdyFrame rframe = spdy.getFrame(SpdyConnection.TYPE_SYN_REPLY); rframe.associated = 0; MimeHeaders headers = response.getMimeHeaders(); for (int i = 0; i < headers.size(); i++) { MessageBytes mb = headers.getName(i); mb.toBytes(); ByteChunk bc = mb.getByteChunk(); byte[] bb = bc.getBuffer(); for (int j = bc.getStart(); j < bc.getEnd(); j++) { bb[j] = (byte) Ascii.toLower(bb[j]); } // TODO: filter headers: Connection, Keep-Alive, Proxy-Connection, rframe.headerName(bc.getBuffer(), bc.getStart(), bc.getLength()); mb = headers.getValue(i); mb.toBytes(); bc = mb.getByteChunk(); rframe.headerValue(bc.getBuffer(), bc.getStart(), bc.getLength()); } if (response.getStatus() == 0) { rframe.addHeader(SpdyFrame.STATUS, SpdyFrame.OK200); } else { // HTTP header contents String message = null; if (org.apache.coyote.Constants.USE_CUSTOM_STATUS_MSG_IN_HEADER && HttpMessages.isSafeInHttpHeader(response.getMessage())) { message = response.getMessage(); } if (message == null) { message = HttpMessages.getMessage(response.getStatus()); } if (message == null) { // mod_jk + httpd 2.x fails with a null status message - bug // 45026 message = Integer.toString(response.getStatus()); } // TODO: optimize String status = response.getStatus() + " " + message; byte[] statusB = status.getBytes(); rframe.headerName(SpdyFrame.STATUS, 0, SpdyFrame.STATUS.length); rframe.headerValue(statusB, 0, statusB.length); } rframe.addHeader(SpdyFrame.VERSION, SpdyFrame.HTTP11); rframe.streamId = spdyStream.reqFrame.streamId; spdy.send(rframe, spdyStream); // we can't reuse the frame - it'll be queued, the coyote processor // may be reused as well. outCommit = true; } @Override public boolean isComet() { return false; } @Override public SocketState process(SocketWrapper<Object> socket) throws IOException { throw new IOException("Unimplemented"); } @Override public SocketState event(SocketStatus status) throws IOException { System.err.println("EVENT: " + status); return null; } @Override public SocketState asyncDispatch(SocketStatus status) { System.err.println("ASYNC DISPATCH: " + status); return null; } @Override public boolean isUpgrade() { return false; } @Override public SocketState upgradeDispatch(SocketStatus status) throws IOException { return null; } public void onSynStream(SpdyStream str) throws IOException { this.spdyStream = str; SpdyFrame frame = str.reqFrame; // We need to make a copy - the frame buffer will be reused. // We use the 'wrap' methods of MimeHeaders - which should be // lighter on mem in some cases. RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); // Request received. MimeHeaders mimeHeaders = request.getMimeHeaders(); // Set this every time in case limit has been changed via JMX mimeHeaders.setLimit(endpoint.getMaxHeaderCount()); for (int i = 0; i < frame.nvCount; i++) { int nameLen = frame.read16(); if (nameLen > frame.remaining()) { throw new IOException("Name too long"); } keyBuffer.setBytes(frame.data, frame.off, nameLen); if (keyBuffer.equals("method")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.method().setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } else if (keyBuffer.equals("url")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } request.requestURI().setBytes(frame.data, frame.off, valueLen); if (SpdyContext.debug) { System.err.println("URL= " + request.requestURI()); } frame.advance(valueLen); } else if (keyBuffer.equals("version")) { frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } frame.advance(valueLen); } else { MessageBytes value = mimeHeaders.addValue(frame.data, frame.off, nameLen); frame.advance(nameLen); int valueLen = frame.read16(); if (valueLen > frame.remaining()) { throw new IOException("Name too long"); } value.setBytes(frame.data, frame.off, valueLen); frame.advance(valueLen); } } onRequest(); } @Override public void recycle(boolean socketClosing) { } @Override public void setSslSupport(SSLSupport sslSupport) { } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { return null; } }
54,807
Bug 54807 [jsr356] java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer$TemplatePathMatch
Caused by: java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer$TemplatePathMatch cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1188) at java.util.TreeMap.put(TreeMap.java:531) at java.util.TreeSet.add(TreeSet.java:255) at org.apache.tomcat.websocket.server.WsServerContainer.addEndpoint(WsServerContainer.java:144) at org.apache.tomcat.websocket.server.WsSci.onStartup(WsSci.java:118) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5195) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 11 more Reproducible when a path is defined as {path}. For example: @Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) { logger.debug("{} detected", JSR356ServerEndpointConfig.class.getName()); return new HashSet<ServerEndpointConfig>() {{ add(ServerEndpointConfig.Builder.create(JSR356Endpoint.class, "/{path}").configurator(c).build()); }}; }
resolved fixed
0339fec
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-19T19:25:49Z
2013-04-05T19:26:40Z
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.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.WeakHashMap; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.websocket.DeploymentException; 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); 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; } private final WsWriteTimeout wsWriteTimeout = new WsWriteTimeout(); private volatile ServletContext servletContext = null; private final Map<String,ServerEndpointConfig> configExactMatchMap = new HashMap<>(); private final Map<Integer,SortedSet<TemplatePathMatch>> configTemplateMatchMap = new HashMap<>(); 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); fr.addMappingForUrlPatterns(null, false, "/*"); } /** * 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 (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) { templateMatches = new TreeSet<>(); configTemplateMatchMap.put(key, templateMatches); } templateMatches.add(new TemplatePathMatch(sec, uriTemplate)); } else { // Exact match configExactMatchMap.put(path, sec); } } /** * 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(); // Uri Template UriTemplate uriTemplate = new UriTemplate(path); // 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 IllegalStateException(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); if (uriTemplate.hasParameters()) { Integer key = Integer.valueOf(uriTemplate.getSegmentCount()); SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key); if (templateMatches == null) { templateMatches = new TreeSet<>(new TemplatePathMatchComparator()); configTemplateMatchMap.put(key, templateMatches); } templateMatches.add(new TemplatePathMatch(sec, uriTemplate)); } else { // Exact match configExactMatchMap.put(path, sec); } } public WsMappingResult findMapping(String path) { // 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 = new UriTemplate(path); // Number of segments has to match Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount()); SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key); // 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 them visible to other classes in this package. */ @Override protected void registerSession(Class<?> endpoint, WsSession wsSession) { super.registerSession(endpoint, wsSession); } /** * {@inheritDoc} * * Overridden to make them visible to other classes in this package. */ @Override protected void unregisterSession(Class<?> endpoint, WsSession wsSession) { super.unregisterSession(endpoint, wsSession); } 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; } } private static class TemplatePathMatchComparator implements Comparator<TemplatePathMatch> { @Override public int compare(TemplatePathMatch tpm1, TemplatePathMatch tpm2) { return tpm1.getUriTemplate().getNormalizedPath().compareTo( tpm2.getUriTemplate().getNormalizedPath()); } } }
54,807
Bug 54807 [jsr356] java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer$TemplatePathMatch
Caused by: java.lang.ClassCastException: org.apache.tomcat.websocket.server.WsServerContainer$TemplatePathMatch cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1188) at java.util.TreeMap.put(TreeMap.java:531) at java.util.TreeSet.add(TreeSet.java:255) at org.apache.tomcat.websocket.server.WsServerContainer.addEndpoint(WsServerContainer.java:144) at org.apache.tomcat.websocket.server.WsSci.onStartup(WsSci.java:118) at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5195) at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) ... 11 more Reproducible when a path is defined as {path}. For example: @Override public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> endpointClasses) { logger.debug("{} detected", JSR356ServerEndpointConfig.class.getName()); return new HashSet<ServerEndpointConfig>() {{ add(ServerEndpointConfig.Builder.create(JSR356Endpoint.class, "/{path}").configurator(c).build()); }}; }
resolved fixed
0339fec
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-19T19:25:49Z
2013-04-05T19:26:40Z
test/org/apache/tomcat/websocket/server/TestWebSocketServerContainer.java
54,800
Bug 54800 Possible thread/memory leak with use of WebSocketContainer
Whenever WebSocketContainer is used to connect to a server endpoint, the following message appears when Tomcat shuts down: SEVERE: The web application [/websocket-test] appears to have started a thread named [Thread-4] but has failed to stop it. This is very likely to create a memory leak. The message is repeated for 6 different threads. I don't have proof this is caused by the use of WebSocketContainer but the messages don't appear when it isn't used. The Endpoint used to connect is very simple. It sends a message when the session is opened to the EchoEndpoint on the server side, and prints the response and closes when the message is echoed back.
resolved fixed
d2630df
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-23T16:23:20Z
2013-04-05T02: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.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.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.Future; 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.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 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(); } catch (IOException ioe) { throw new DeploymentException("TODO", 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 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 { Map<String,List<String>> headers = new HashMap<>(); boolean readStatus = false; boolean readHeaders = false; String line = null; while (!readHeaders) { // Blocking read Future<Integer> written = channel.read(response); written.get(); 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("TODO", 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; } }
54,792
Bug 54792 IllegalStateException with chat sample
This looks related to 54659 and 54724 but possibly a new issue. To reproduce, open the chat sample page, send a message or two, and then close the browser tab. The following exception appears in the log and it doesn't seem to step from anything done in the application: java.lang.IllegalStateException: The WebSocket session has been closed and no method (apart from close()) may be called on a closed session at org.apache.tomcat.websocket.WsSession.checkState(WsSession.java:516) at org.apache.tomcat.websocket.WsSession.getMessageHandlers(WsSession.java:191) at org.apache.tomcat.websocket.pojo.PojoEndpointBase.onClose(PojoEndpointBase.java:113) at org.apache.tomcat.websocket.WsSession.fireEndpointOnClose(WsSession.java:392) at org.apache.tomcat.websocket.WsSession.onClose(WsSession.java:370) at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.close(WsHttpUpgradeHandler.java:166) at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler.access$200(WsHttpUpgradeHandler.java:44) at org.apache.tomcat.websocket.server.WsHttpUpgradeHandler$WsReadListener.onDataAvailable(WsHttpUpgradeHandler.java:192) at org.apache.coyote.http11.upgrade.AbstractServletInputStream.onDataAvailable(AbstractServletInputStream.java:169) at org.apache.coyote.http11.upgrade.AbstractProcessor.upgradeDispatch(AbstractProcessor.java:94) at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:618) 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:1537) 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)
resolved fixed
e26d61d
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-23T16:34:04Z
2013-04-03T00:46:40Z
webapps/examples/WEB-INF/classes/websocket/chat/ChatAnnotation.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 websocket.chat; import java.io.IOException; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.atomic.AtomicInteger; import javax.websocket.OnClose; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; import util.HTMLFilter; @ServerEndpoint(value = "/websocket/chat") public class ChatAnnotation { private static final String GUEST_PREFIX = "Guest"; private static final AtomicInteger connectionIds = new AtomicInteger(0); private static final Set<ChatAnnotation> connections = new CopyOnWriteArraySet<>(); private final String nickname; private Session session; public ChatAnnotation() { nickname = GUEST_PREFIX + connectionIds.getAndIncrement(); } @OnOpen public void start(Session session) { this.session = session; connections.add(this); String message = String.format("* %s %s", nickname, "has joined."); broadcast(message); } @OnClose public void end() { try { session.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } connections.remove(this); String message = String.format("* %s %s", nickname, "has disconnected."); broadcast(message); } @OnMessage public void incoming(String message) { // Never trust the client String filteredMessage = String.format("%s: %s", nickname, HTMLFilter.filter(message.toString())); broadcast(filteredMessage); } private static void broadcast(String msg) { for (ChatAnnotation client : connections) { try { client.session.getBasicRemote().sendText(msg); } catch (IOException e) { connections.remove(client); try { client.session.close(); } catch (IOException e1) { // Ignore } String message = String.format("* %s %s", client.nickname, "has been disconnected."); broadcast(message); } } } }
54,781
Bug 54781 NPE in WsServerContainer if there is no matching path
null
resolved fixed
67ed3e7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-23T19:58:34Z
2013-04-01T23: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)) { // Note 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); 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,781
Bug 54781 NPE in WsServerContainer if there is no matching path
null
resolved fixed
67ed3e7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-23T19:58:34Z
2013-04-01T23:46:40Z
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.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.SortedSet; import java.util.TreeSet; import java.util.WeakHashMap; import javax.servlet.FilterRegistration; import javax.servlet.ServletContext; import javax.websocket.DeploymentException; 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); 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; } private final WsWriteTimeout wsWriteTimeout = new WsWriteTimeout(); private volatile ServletContext servletContext = null; private final Map<String,ServerEndpointConfig> configExactMatchMap = new HashMap<>(); private final Map<Integer,SortedSet<TemplatePathMatch>> configTemplateMatchMap = new HashMap<>(); 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); fr.addMappingForUrlPatterns(null, false, "/*"); } /** * 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 (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) { templateMatches = new TreeSet<>( TemplatePathMatchComparator.getInstance()); configTemplateMatchMap.put(key, templateMatches); } templateMatches.add(new TemplatePathMatch(sec, uriTemplate)); } else { // Exact match configExactMatchMap.put(path, sec); } } /** * 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(); // Uri Template UriTemplate uriTemplate = new UriTemplate(path); // 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 IllegalStateException(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); if (uriTemplate.hasParameters()) { Integer key = Integer.valueOf(uriTemplate.getSegmentCount()); SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key); if (templateMatches == null) { templateMatches = new TreeSet<>( TemplatePathMatchComparator.getInstance()); configTemplateMatchMap.put(key, templateMatches); } templateMatches.add(new TemplatePathMatch(sec, uriTemplate)); } else { // Exact match configExactMatchMap.put(path, sec); } } public WsMappingResult findMapping(String path) { // 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 = new UriTemplate(path); // Number of segments has to match Integer key = Integer.valueOf(pathUriTemplate.getSegmentCount()); SortedSet<TemplatePathMatch> templateMatches = configTemplateMatchMap.get(key); // 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 them visible to other classes in this package. */ @Override protected void registerSession(Class<?> endpoint, WsSession wsSession) { super.registerSession(endpoint, wsSession); } /** * {@inheritDoc} * * Overridden to make them visible to other classes in this package. */ @Override protected void unregisterSession(Class<?> endpoint, WsSession wsSession) { super.unregisterSession(endpoint, wsSession); } 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()); } } }
54,708
Bug 54708 Use base file name ("ROOT") as the work directory for the default webapp instead of "_"
null
resolved fixed
59a0676
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-23T20:06:02Z
2013-03-16T02:13:20Z
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.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; 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.FilterConfig; 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.ServletRequest; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.ServletSecurityElement; 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.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 web.xml file. */ private String applicationListeners[] = new String[0]; private final Object applicationListenersLock = new Object(); /** * The set of instantiated application event listener objects</code>. */ private Object applicationEventListenersObjects[] = new Object[0]; /** * The set of instantiated application lifecycle listener objects</code>. */ 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; /** * 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; } /** * 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(String listener) { synchronized (applicationListenersLock) { String results[] =new String[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 String[] 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].equals(listener)) { n = i; break; } } if (n < 0) return; // Remove the specified constraint int j = 0; String results[] = new String[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 String listeners[] = findApplicationListeners(); Object results[] = new Object[listeners.length]; boolean ok = true; for (int i = 0; i < results.length; i++) { if (getLogger().isDebugEnabled()) getLogger().debug(" Configuring event listener class '" + listeners[i] + "'"); try { results[i] = instanceManager.newInstance(listeners[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]); } } //Listeners may have been added by ServletContextInitializers. Put them after the ones we know about. for (Object eventListener: getApplicationEventListeners()) { eventListeners.add(eventListener); } setApplicationEventListeners(eventListeners.toArray()); for (Object lifecycleListener: getApplicationLifecycleListeners()) { lifecycleListeners.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()); 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); 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()); 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 String[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().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 = getName(); 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; } }
54,178
Bug 54178 [CVE-2013-2071] runtime exception in onComplete of AsyncListener, will make org.apache.catalina.connector.Request not recycled (orginally reported MESSAGE POST to tomcat, but it called doGet)
one HTTP request use POST method, but in tomcat it calls doGet() what is really strage. as I only tested in 7.0.23, and 7.0.32. in 7.0.32, 7.0.32 is more reproduceable than 7.0.23. I know it must be a very strange issue, as tomcat has so many release. I can't believe it if I didn't see it with my own eyes. so I attache the image.
resolved fixed
4171baf
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-24T11:27:11Z
2012-11-21T12:13:20Z
java/org/apache/catalina/core/AsyncContextImpl.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.lang.reflect.InvocationTargetException; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.NamingException; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.AsyncDispatcher; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Valve; import org.apache.catalina.connector.Request; import org.apache.coyote.ActionCode; import org.apache.coyote.AsyncContextCallback; import org.apache.coyote.RequestInfo; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * * @author fhanik * */ public class AsyncContextImpl implements AsyncContext, AsyncContextCallback { private static final Log log = LogFactory.getLog(AsyncContextImpl.class); protected static final StringManager sm = StringManager.getManager(Constants.Package); private ServletRequest servletRequest = null; private ServletResponse servletResponse = null; private final List<AsyncListenerWrapper> listeners = new ArrayList<>(); private boolean hasOriginalRequestAndResponse = true; private volatile Runnable dispatch = null; private Context context = null; private long timeout = -1; private AsyncEvent event = null; private Request request; private volatile InstanceManager instanceManager; public AsyncContextImpl(Request request) { if (log.isDebugEnabled()) { logDebug("Constructor"); } this.request = request; } @Override public void complete() { if (log.isDebugEnabled()) { logDebug("complete "); } check(); request.getCoyoteRequest().action(ActionCode.COMMIT, null); request.getCoyoteRequest().action(ActionCode.ASYNC_COMPLETE, null); } @Override public void fireOnComplete() { List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(); listenersCopy.addAll(listeners); ClassLoader oldCL; if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); oldCL = AccessController.doPrivileged(pa); } else { oldCL = Thread.currentThread().getContextClassLoader(); } ClassLoader newCL = context.getLoader().getClassLoader(); try { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(newCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(newCL); } for (AsyncListenerWrapper listener : listenersCopy) { try { listener.fireOnComplete(event); } catch (IOException ioe) { log.warn("onComplete() failed for listener of type [" + listener.getClass().getName() + "]", ioe); } } } finally { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } } } public boolean canRead() throws IOException { if (request.getCoyoteRequest().getReadListener()==null) return false; ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); request.getCoyoteRequest().getReadListener().onDataAvailable(); if (request.getInputStream().isFinished()) { request.getCoyoteRequest().getReadListener().onAllDataRead(); } }finally { Thread.currentThread().setContextClassLoader(oldCL); } return true; } public boolean canWrite() throws IOException { if (request.getResponse().getCoyoteResponse().getWriteListener()==null) return false; ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); request.getResponse().getCoyoteResponse().getWriteListener().onWritePossible(); }finally { Thread.currentThread().setContextClassLoader(oldCL); } return true; } public boolean notifyWriteError(Throwable error) { if (request.getResponse().getCoyoteResponse().getWriteListener()==null) return false; ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); request.getResponse().getCoyoteResponse().getWriteListener().onError(error); return true; } finally { Thread.currentThread().setContextClassLoader(oldCL); } } public boolean notifyReadError(Throwable error) { if (request.getCoyoteRequest().getReadListener()==null) return false; ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); request.getCoyoteRequest().getReadListener().onError(error); return true; } finally { Thread.currentThread().setContextClassLoader(oldCL); } } public boolean timeout() { AtomicBoolean result = new AtomicBoolean(); request.getCoyoteRequest().action(ActionCode.ASYNC_TIMEOUT, result); if (result.get()) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(); listenersCopy.addAll(listeners); for (AsyncListenerWrapper listener : listenersCopy) { try { listener.fireOnTimeout(event); } catch (IOException ioe) { log.warn("onTimeout() failed for listener of type [" + listener.getClass().getName() + "]", ioe); } } request.getCoyoteRequest().action( ActionCode.ASYNC_IS_TIMINGOUT, result); return !result.get(); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } return true; } @Override public void dispatch() { check(); HttpServletRequest sr = (HttpServletRequest)getRequest(); String path = sr.getRequestURI(); String cpath = sr.getContextPath(); if (cpath.length()>1) path = path.substring(cpath.length()); dispatch(path); } @Override public void dispatch(String path) { check(); dispatch(request.getServletContext(),path); } @Override public void dispatch(ServletContext context, String path) { if (log.isDebugEnabled()) { logDebug("dispatch "); } check(); if (request.getAttribute(ASYNC_REQUEST_URI)==null) { request.setAttribute(ASYNC_REQUEST_URI, request.getRequestURI()); request.setAttribute(ASYNC_CONTEXT_PATH, request.getContextPath()); request.setAttribute(ASYNC_SERVLET_PATH, request.getServletPath()); request.setAttribute(ASYNC_PATH_INFO, request.getPathInfo()); request.setAttribute(ASYNC_QUERY_STRING, request.getQueryString()); } final RequestDispatcher requestDispatcher = context.getRequestDispatcher(path); if (!(requestDispatcher instanceof AsyncDispatcher)) { throw new UnsupportedOperationException( sm.getString("asyncContextImpl.noAsyncDispatcher")); } final AsyncDispatcher applicationDispatcher = (AsyncDispatcher) requestDispatcher; final HttpServletRequest servletRequest = (HttpServletRequest) getRequest(); final HttpServletResponse servletResponse = (HttpServletResponse) getResponse(); Runnable run = new Runnable() { @Override public void run() { request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCHED, null); try { applicationDispatcher.dispatch(servletRequest, servletResponse); }catch (Exception x) { //log.error("Async.dispatch",x); throw new RuntimeException(x); } } }; this.dispatch = run; this.request.getCoyoteRequest().action(ActionCode.ASYNC_DISPATCH, null); } @Override public ServletRequest getRequest() { check(); return servletRequest; } @Override public ServletResponse getResponse() { check(); return servletResponse; } @Override public void start(final Runnable run) { if (log.isDebugEnabled()) { logDebug("start "); } check(); Runnable wrapper = new RunnableWrapper(run, context); this.request.getCoyoteRequest().action(ActionCode.ASYNC_RUN, wrapper); } @Override public void addListener(AsyncListener listener) { check(); AsyncListenerWrapper wrapper = new AsyncListenerWrapper(); wrapper.setListener(listener); listeners.add(wrapper); } @Override public void addListener(AsyncListener listener, ServletRequest servletRequest, ServletResponse servletResponse) { check(); AsyncListenerWrapper wrapper = new AsyncListenerWrapper(); wrapper.setListener(listener); listeners.add(wrapper); } @Override public <T extends AsyncListener> T createListener(Class<T> clazz) throws ServletException { check(); T listener = null; try { listener = (T) getInstanceManager().newInstance(clazz.getName(), clazz.getClassLoader()); } catch (InstantiationException e) { ServletException se = new ServletException(e); throw se; } catch (IllegalAccessException e) { ServletException se = new ServletException(e); throw se; } catch (InvocationTargetException e) { ExceptionUtils.handleThrowable(e.getCause()); ServletException se = new ServletException(e); throw se; } catch (NamingException e) { ServletException se = new ServletException(e); throw se; } catch (ClassNotFoundException e) { ServletException se = new ServletException(e); throw se; } return listener; } public void recycle() { if (log.isDebugEnabled()) { logDebug("recycle "); } context = null; dispatch = null; event = null; hasOriginalRequestAndResponse = true; instanceManager = null; listeners.clear(); request = null; servletRequest = null; servletResponse = null; timeout = -1; } public boolean isStarted() { AtomicBoolean result = new AtomicBoolean(false); request.getCoyoteRequest().action( ActionCode.ASYNC_IS_STARTED, result); return result.get(); } public void setStarted(Context context, ServletRequest request, ServletResponse response, boolean originalRequestResponse) { this.request.getCoyoteRequest().action( ActionCode.ASYNC_START, this); this.context = context; this.servletRequest = request; this.servletResponse = response; this.hasOriginalRequestAndResponse = originalRequestResponse; this.event = new AsyncEvent(this, request, response); List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(); listenersCopy.addAll(listeners); for (AsyncListenerWrapper listener : listenersCopy) { try { listener.fireOnStartAsync(event); } catch (IOException ioe) { log.warn("onStartAsync() failed for listener of type [" + listener.getClass().getName() + "]", ioe); } } listeners.clear(); } @Override public boolean hasOriginalRequestAndResponse() { check(); return hasOriginalRequestAndResponse; } protected void doInternalDispatch() throws ServletException, IOException { if (log.isDebugEnabled()) { logDebug("intDispatch"); } try { dispatch.run(); if (!request.isAsync()) { fireOnComplete(); } } catch (RuntimeException x) { // doInternalComplete(true); if (x.getCause() instanceof ServletException) { throw (ServletException)x.getCause(); } if (x.getCause() instanceof IOException) { throw (IOException)x.getCause(); } throw new ServletException(x); } } @Override public long getTimeout() { check(); return timeout; } @Override public void setTimeout(long timeout) { check(); this.timeout = timeout; request.getCoyoteRequest().action(ActionCode.ASYNC_SETTIMEOUT, Long.valueOf(timeout)); } public void setErrorState(Throwable t, boolean fireOnError) { if (t!=null) request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t); request.getCoyoteRequest().action(ActionCode.ASYNC_ERROR, null); if (fireOnError) { AsyncEvent errorEvent = new AsyncEvent(event.getAsyncContext(), event.getSuppliedRequest(), event.getSuppliedResponse(), t); List<AsyncListenerWrapper> listenersCopy = new ArrayList<>(); listenersCopy.addAll(listeners); for (AsyncListenerWrapper listener : listenersCopy) { try { listener.fireOnError(errorEvent); } catch (IOException ioe) { log.warn("onError() failed for listener of type [" + listener.getClass().getName() + "]", ioe); } } } AtomicBoolean result = new AtomicBoolean(); request.getCoyoteRequest().action(ActionCode.ASYNC_IS_ERROR, result); if (result.get()) { // No listener called dispatch() or complete(). This is an error. // SRV.2.3.3.3 (search for "error dispatch") if (servletResponse instanceof HttpServletResponse) { ((HttpServletResponse) servletResponse).setStatus( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } Host host = (Host) context.getParent(); Valve stdHostValve = host.getPipeline().getBasic(); if (stdHostValve instanceof StandardHostValve) { ((StandardHostValve) stdHostValve).throwable(request, request.getResponse(), t); } request.getCoyoteRequest().action( ActionCode.ASYNC_IS_ERROR, result); if (result.get()) { // Still in the error state. The error page did not call // complete() or dispatch(). Complete the async processing. complete(); } } } private void logDebug(String method) { String rHashCode; String crHashCode; String rpHashCode; String stage; StringBuilder uri = new StringBuilder(); if (request == null) { rHashCode = "null"; crHashCode = "null"; rpHashCode = "null"; stage = "-"; uri.append("N/A"); } else { rHashCode = Integer.toHexString(request.hashCode()); org.apache.coyote.Request coyoteRequest = request.getCoyoteRequest(); if (coyoteRequest == null) { crHashCode = "null"; rpHashCode = "null"; stage = "-"; } else { crHashCode = Integer.toHexString(coyoteRequest.hashCode()); RequestInfo rp = coyoteRequest.getRequestProcessor(); if (rp == null) { rpHashCode = "null"; stage = "-"; } else { rpHashCode = Integer.toHexString(rp.hashCode()); stage = Integer.toString(rp.getStage()); } } uri.append(request.getRequestURI()); if (request.getQueryString() != null) { uri.append('?'); uri.append(request.getQueryString()); } } String threadName = Thread.currentThread().getName(); int len = threadName.length(); if (len > 20) { threadName = threadName.substring(len - 20, len); } String msg = String.format( "Req: %1$8s CReq: %2$8s RP: %3$8s Stage: %4$s " + "Thread: %5$20s State: %6$20s Method: %7$11s URI: %8$s", rHashCode, crHashCode, rpHashCode, stage, threadName, "N/A", method, uri); if (log.isTraceEnabled()) { log.trace(msg, new DebugException()); } else { log.debug(msg); } } private InstanceManager getInstanceManager() { if (instanceManager == null) { if (context instanceof StandardContext) { instanceManager = ((StandardContext)context).getInstanceManager(); } else { instanceManager = new DefaultInstanceManager(null, new HashMap<String, Map<String, String>>(), context, getClass().getClassLoader()); } } return instanceManager; } private void check() { if (request == null) { // AsyncContext has been recycled and should not be being used throw new IllegalStateException(sm.getString( "asyncContextImpl.requestEnded")); } } private static class DebugException extends Exception { private static final long serialVersionUID = 1L; } private static class RunnableWrapper implements Runnable { private Runnable wrapped = null; private Context context = null; public RunnableWrapper(Runnable wrapped, Context ctxt) { this.wrapped = wrapped; this.context = ctxt; } @Override public void run() { ClassLoader oldCL; if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<ClassLoader> pa = new PrivilegedGetTccl(); oldCL = AccessController.doPrivileged(pa); } else { oldCL = Thread.currentThread().getContextClassLoader(); } try { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( context.getLoader().getClassLoader()); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader (context.getLoader().getClassLoader()); } wrapped.run(); } finally { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl( oldCL); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(oldCL); } } } } private static class PrivilegedSetTccl implements PrivilegedAction<Void> { private ClassLoader cl; PrivilegedSetTccl(ClassLoader cl) { this.cl = cl; } @Override public Void run() { Thread.currentThread().setContextClassLoader(cl); return null; } } private static class PrivilegedGetTccl implements PrivilegedAction<ClassLoader> { @Override public ClassLoader run() { return Thread.currentThread().getContextClassLoader(); } } }
54,178
Bug 54178 [CVE-2013-2071] runtime exception in onComplete of AsyncListener, will make org.apache.catalina.connector.Request not recycled (orginally reported MESSAGE POST to tomcat, but it called doGet)
one HTTP request use POST method, but in tomcat it calls doGet() what is really strage. as I only tested in 7.0.23, and 7.0.32. in 7.0.32, 7.0.32 is more reproduceable than 7.0.23. I know it must be a very strange issue, as tomcat has so many release. I can't believe it if I didn't see it with my own eyes. so I attache the image.
resolved fixed
4171baf
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-24T11:27:11Z
2012-11-21T12:13:20Z
test/org/apache/catalina/core/TestAsyncContextImpl.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.PrintWriter; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.servlet.AsyncContext; import javax.servlet.AsyncEvent; import javax.servlet.AsyncListener; import javax.servlet.DispatcherType; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.ServletResponse; 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 static org.junit.Assert.fail; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Request; import org.apache.catalina.deploy.ErrorPage; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.catalina.valves.TesterAccessLogValve; import org.apache.tomcat.util.buf.ByteChunk; public class TestAsyncContextImpl extends TomcatBaseTest { // Time for a request to process (need to allow for threads to start etc.) private static final long REQUEST_TIME = 1500; // Timeout thread (where used) checks for timeout every second private static final long TIMEOUT_MARGIN = 1000; // Default timeout for these tests private static final long TIMEOUT = 3000; @Test public void testBug49528() 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")); Bug49528Servlet servlet = new Bug49528Servlet(); Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/", "servlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); // Call the servlet once ByteChunk bc = getUrl("http://localhost:" + getPort() + "/"); assertEquals("OK", bc.toString()); // Give the async thread a chance to finish (but not too long) int counter = 0; while (!servlet.isDone() && counter < 10) { Thread.sleep(1000); counter++; } assertEquals("1false2true3true4true5false", servlet.getResult()); // Check the access log alv.validateAccessLog(1, 200, Bug49528Servlet.THREAD_SLEEP_TIME, Bug49528Servlet.THREAD_SLEEP_TIME + REQUEST_TIME); } @Test public void testBug49567() 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")); Bug49567Servlet servlet = new Bug49567Servlet(); Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/", "servlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); // Call the servlet once ByteChunk bc = getUrl("http://localhost:" + getPort() + "/"); assertEquals("OK", bc.toString()); // Give the async thread a chance to finish (but not too long) int counter = 0; while (!servlet.isDone() && counter < 10) { Thread.sleep(1000); counter++; } assertEquals("1false2true3true4true5false", servlet.getResult()); // Check the access log alv.validateAccessLog(1, 200, Bug49567Servlet.THREAD_SLEEP_TIME, Bug49567Servlet.THREAD_SLEEP_TIME + REQUEST_TIME); } @Test public void testAsyncStartNoComplete() throws Exception { // Setup Tomcat instance Tomcat tomcat = getTomcatInstance(); // Minimise pauses during test tomcat.getConnector().setAttribute( "connectionTimeout", Integer.valueOf(3000)); // Must have a real docBase - just use temp Context ctx = tomcat.addContext("", System.getProperty("java.io.tmpdir")); AsyncStartNoCompleteServlet servlet = new AsyncStartNoCompleteServlet(); Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/", "servlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); // Call the servlet the first time ByteChunk bc1 = getUrl("http://localhost:" + getPort() + "/?echo=run1"); assertEquals("OK-run1", bc1.toString()); // Call the servlet the second time with a request parameter ByteChunk bc2 = getUrl("http://localhost:" + getPort() + "/?echo=run2"); assertEquals("OK-run2", bc2.toString()); // Check the access log alv.validateAccessLog(2, 500, AsyncStartNoCompleteServlet.ASYNC_TIMEOUT, AsyncStartNoCompleteServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); } @Test public void testAsyncStartWithComplete() 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")); AsyncStartWithCompleteServlet servlet = new AsyncStartWithCompleteServlet(); Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/", "servlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); // Call the servlet once ByteChunk bc = getUrl("http://localhost:" + getPort() + "/"); assertEquals("OK", bc.toString()); // Check the access log alv.validateAccessLog(1, 200, 0, REQUEST_TIME); } /* * NOTE: This servlet is only intended to be used in single-threaded tests. */ private static class Bug49528Servlet extends HttpServlet { private static final long serialVersionUID = 1L; private volatile boolean done = false; private StringBuilder result; public static final long THREAD_SLEEP_TIME = 1000; public String getResult() { return result.toString(); } public boolean isDone() { return done; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { result = new StringBuilder(); result.append('1'); result.append(req.isAsyncStarted()); req.startAsync().setTimeout(10000); result.append('2'); result.append(req.isAsyncStarted()); req.getAsyncContext().start(new Runnable() { @Override public void run() { try { result.append('3'); result.append(req.isAsyncStarted()); Thread.sleep(THREAD_SLEEP_TIME); result.append('4'); result.append(req.isAsyncStarted()); resp.setContentType("text/plain"); resp.getWriter().print("OK"); req.getAsyncContext().complete(); result.append('5'); result.append(req.isAsyncStarted()); done = true; } catch (InterruptedException e) { result.append(e); } catch (IOException e) { result.append(e); } } }); // Pointless method call so there is somewhere to put a break point // when debugging req.getMethod(); } } /* * NOTE: This servlet is only intended to be used in single-threaded tests. */ private static class Bug49567Servlet extends HttpServlet { private static final long serialVersionUID = 1L; private volatile boolean done = false; private StringBuilder result; public static final long THREAD_SLEEP_TIME = 1000; public String getResult() { return result.toString(); } public boolean isDone() { return done; } @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { result = new StringBuilder(); result.append('1'); result.append(req.isAsyncStarted()); req.startAsync(); result.append('2'); result.append(req.isAsyncStarted()); req.getAsyncContext().start(new Runnable() { @Override public void run() { Thread t = new Thread(new Runnable() { @Override public void run() { try { result.append('3'); result.append(req.isAsyncStarted()); Thread.sleep(THREAD_SLEEP_TIME); result.append('4'); result.append(req.isAsyncStarted()); resp.setContentType("text/plain"); resp.getWriter().print("OK"); req.getAsyncContext().complete(); result.append('5'); result.append(req.isAsyncStarted()); done = true; } catch (InterruptedException e) { result.append(e); } catch (IOException e) { result.append(e); } } }); t.start(); } }); // Pointless method call so there is somewhere to put a break point // when debugging req.getMethod(); } } private static class AsyncStartNoCompleteServlet extends HttpServlet { public static final long ASYNC_TIMEOUT = 1000; private static final long serialVersionUID = 1L; @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { String echo = req.getParameter("echo"); AsyncContext actxt = req.startAsync(); resp.setContentType("text/plain"); resp.getWriter().print("OK"); if (echo != null) { resp.getWriter().print("-" + echo); } // Speed up the test by reducing the timeout actxt.setTimeout(ASYNC_TIMEOUT); } } private static class AsyncStartWithCompleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { AsyncContext actxt = req.startAsync(); actxt.setTimeout(3000); resp.setContentType("text/plain"); resp.getWriter().print("OK"); actxt.complete(); } } @Test public void testTimeoutListenerCompleteNoDispatch() throws Exception { // Should work doTestTimeout(Boolean.TRUE, null); } @Test public void testTimeoutListenerNoCompleteNoDispatch() throws Exception { // Should trigger an error - must do one or other doTestTimeout(Boolean.FALSE, null); } @Test public void testTimeoutListenerCompleteDispatch() throws Exception { // Should trigger an error - can't do both doTestTimeout(Boolean.TRUE, "/nonasync"); } @Test public void testTimeoutListenerNoCompleteDispatch() throws Exception { // Should work doTestTimeout(Boolean.FALSE, "/nonasync"); } @Test public void testTimeoutNoListener() throws Exception { // Should work doTestTimeout(null, null); } private void doTestTimeout(Boolean completeOnTimeout, String dispatchUrl) 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, "async"); addDeleteOnTearDown(foo); if (!foo.mkdirs() && !foo.isDirectory()) { fail("Unable to create async directory in docBase"); } Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); TimeoutServlet timeout = new TimeoutServlet(completeOnTimeout, dispatchUrl); Wrapper wrapper = Tomcat.addServlet(ctx, "time", timeout); wrapper.setAsyncSupported(true); ctx.addServletMapping("/async", "time"); if (dispatchUrl != null) { NonAsyncServlet nonAsync = new NonAsyncServlet(); Tomcat.addServlet(ctx, "nonasync", nonAsync); ctx.addServletMapping(dispatchUrl, "nonasync"); } ctx.addApplicationListener(TrackingRequestListener.class.getName()); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); TesterAccessLogValve alvGlobal = new TesterAccessLogValve(); tomcat.getHost().getPipeline().addValve(alvGlobal); tomcat.start(); ByteChunk res = new ByteChunk(); try { getUrl("http://localhost:" + getPort() + "/async", res, null); } catch (IOException ioe) { // Ignore - expected for some error conditions } StringBuilder expected = new StringBuilder("requestInitialized-"); expected.append("TimeoutServletGet-"); if (completeOnTimeout == null) { expected.append("requestDestroyed"); } else if (completeOnTimeout.booleanValue()) { expected.append("onTimeout-"); if (dispatchUrl == null) { expected.append("onComplete-"); expected.append("requestDestroyed"); } else { // Error - no further output // There is no onComplete- since the complete event would be // fired during post processing but since there is an error that // never happens. } } else { expected.append("onTimeout-"); if (dispatchUrl != null) { expected.append("NonAsyncServletGet-"); } expected.append("onComplete-"); expected.append("requestDestroyed"); } assertEquals(expected.toString(), res.toString()); // Check the access log if (completeOnTimeout == null) { alvGlobal.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); alv.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); } else if (completeOnTimeout.booleanValue() && dispatchUrl != null) { // This error is written into Host-level AccessLogValve only alvGlobal.validateAccessLog(1, 500, 0, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); alv.validateAccessLog(0, 500, 0, 0); } else { alvGlobal.validateAccessLog(1, 200, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); alv.validateAccessLog(1, 200, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); } } private static class TimeoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final Boolean completeOnTimeout; private final String dispatchUrl; public static final long ASYNC_TIMEOUT = 3000; public TimeoutServlet(Boolean completeOnTimeout, String dispatchUrl) { this.completeOnTimeout = completeOnTimeout; this.dispatchUrl = dispatchUrl; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if (req.isAsyncSupported()) { resp.getWriter().print("TimeoutServletGet-"); final AsyncContext ac = req.startAsync(); ac.setTimeout(ASYNC_TIMEOUT); if (completeOnTimeout != null) { ac.addListener(new TrackingListener(false, completeOnTimeout.booleanValue(), dispatchUrl)); } } else { resp.getWriter().print("FAIL: Async unsupported"); } } } @Test public void testDispatchSingle() throws Exception { doTestDispatch(1, false); } @Test public void testDispatchDouble() throws Exception { doTestDispatch(2, false); } @Test public void testDispatchMultiple() throws Exception { doTestDispatch(5, false); } @Test public void testDispatchWithThreadSingle() throws Exception { doTestDispatch(1, true); } @Test public void testDispatchWithThreadDouble() throws Exception { doTestDispatch(2, true); } @Test public void testDispatchWithThreadMultiple() throws Exception { doTestDispatch(5, true); } private void doTestDispatch(int iter, boolean useThread) 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); DispatchingServlet dispatch = new DispatchingServlet(false, false); Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch); wrapper.setAsyncSupported(true); ctx.addServletMapping("/stage1", "dispatch"); NonAsyncServlet nonasync = new NonAsyncServlet(); Wrapper wrapper2 = Tomcat.addServlet(ctx, "nonasync", nonasync); wrapper2.setAsyncSupported(true); ctx.addServletMapping("/stage2", "nonasync"); ctx.addApplicationListener(TrackingRequestListener.class.getName()); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/stage1?iter="); url.append(iter); if (useThread) { url.append("&useThread=y"); } ByteChunk res = getUrl(url.toString()); StringBuilder expected = new StringBuilder("requestInitialized-"); int loop = iter; while (loop > 0) { expected.append("DispatchingServletGet-"); loop--; } expected.append("NonAsyncServletGet-"); expected.append("requestDestroyed"); assertEquals(expected.toString(), res.toString()); // Check the access log alv.validateAccessLog(1, 200, 0, REQUEST_TIME); } private static class DispatchingServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final String ITER_PARAM = "iter"; private static final String DISPATCH_CHECK = "check"; private boolean addTrackingListener = false; private boolean completeOnError = false; public DispatchingServlet(boolean addTrackingListener, boolean completeOnError) { this.addTrackingListener = addTrackingListener; this.completeOnError = completeOnError; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { if ("y".equals(req.getParameter(DISPATCH_CHECK))) { if (req.getDispatcherType() != DispatcherType.ASYNC) { resp.getWriter().write("WrongDispatcherType-"); } } resp.getWriter().write("DispatchingServletGet-"); resp.flushBuffer(); final int iter = Integer.parseInt(req.getParameter(ITER_PARAM)) - 1; final AsyncContext ctxt = req.startAsync(); if (addTrackingListener) { TrackingListener listener = new TrackingListener(completeOnError, true, null); ctxt.addListener(listener); } Runnable run = new Runnable() { @Override public void run() { if (iter > 0) { ctxt.dispatch("/stage1?" + ITER_PARAM + "=" + iter + "&" + DISPATCH_CHECK + "=y"); } else { ctxt.dispatch("/stage2"); } } }; if ("y".equals(req.getParameter("useThread"))) { new Thread(run).start(); } else { run.run(); } } } private static class NonAsyncServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("NonAsyncServletGet-"); resp.flushBuffer(); } } @Test public void testListeners() 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); TrackingServlet tracking = new TrackingServlet(); Wrapper wrapper = Tomcat.addServlet(ctx, "tracking", tracking); wrapper.setAsyncSupported(true); ctx.addServletMapping("/stage1", "tracking"); TimeoutServlet timeout = new TimeoutServlet(Boolean.TRUE, null); Wrapper wrapper2 = Tomcat.addServlet(ctx, "timeout", timeout); wrapper2.setAsyncSupported(true); ctx.addServletMapping("/stage2", "timeout"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/stage1"); ByteChunk res = getUrl(url.toString()); assertEquals( "DispatchingServletGet-DispatchingServletGet-onStartAsync-" + "TimeoutServletGet-onStartAsync-onTimeout-onComplete-", res.toString()); // Check the access log alv.validateAccessLog(1, 200, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); } private static class TrackingServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static volatile boolean first = true; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("DispatchingServletGet-"); resp.flushBuffer(); final boolean first = TrackingServlet.first; TrackingServlet.first = false; final AsyncContext ctxt = req.startAsync(); TrackingListener listener = new TrackingListener(false, true, null); ctxt.addListener(listener); ctxt.setTimeout(3000); Runnable run = new Runnable() { @Override public void run() { if (first) { ctxt.dispatch("/stage1"); } else { ctxt.dispatch("/stage2"); } } }; if ("y".equals(req.getParameter("useThread"))) { new Thread(run).start(); } else { run.run(); } } } private static class TrackingListener implements AsyncListener { private final boolean completeOnError; private final boolean completeOnTimeout; private final String dispatchUrl; public TrackingListener(boolean completeOnError, boolean completeOnTimeout, String dispatchUrl) { this.completeOnError = completeOnError; this.completeOnTimeout = completeOnTimeout; this.dispatchUrl = dispatchUrl; } @Override public void onComplete(AsyncEvent event) throws IOException { ServletResponse resp = event.getAsyncContext().getResponse(); resp.getWriter().write("onComplete-"); resp.flushBuffer(); } @Override public void onTimeout(AsyncEvent event) throws IOException { ServletResponse resp = event.getAsyncContext().getResponse(); resp.getWriter().write("onTimeout-"); resp.flushBuffer(); if (completeOnTimeout){ event.getAsyncContext().complete(); } if (dispatchUrl != null) { event.getAsyncContext().dispatch(dispatchUrl); } } @Override public void onError(AsyncEvent event) throws IOException { ServletResponse resp = event.getAsyncContext().getResponse(); resp.getWriter().write("onError-"); resp.flushBuffer(); if (completeOnError) { event.getAsyncContext().complete(); } } @Override public void onStartAsync(AsyncEvent event) throws IOException { ServletResponse resp = event.getAsyncContext().getResponse(); resp.getWriter().write("onStartAsync-"); resp.flushBuffer(); } } public static class TrackingRequestListener implements ServletRequestListener { @Override public void requestDestroyed(ServletRequestEvent sre) { // Need the response and it isn't available via the Servlet API Request r = (Request) sre.getServletRequest(); try { r.getResponse().getWriter().print("requestDestroyed"); } catch (IOException e) { // Test will fail if this happens e.printStackTrace(); } } @Override public void requestInitialized(ServletRequestEvent sre) { // Need the response and it isn't available via the Servlet API Request r = (Request) sre.getServletRequest(); try { r.getResponse().getWriter().print("requestInitialized-"); } catch (IOException e) { // Test will fail if this happens e.printStackTrace(); } } } @Test public void testDispatchErrorSingle() throws Exception { doTestDispatchError(1, false, false); } @Test public void testDispatchErrorDouble() throws Exception { doTestDispatchError(2, false, false); } @Test public void testDispatchErrorMultiple() throws Exception { doTestDispatchError(5, false, false); } @Test public void testDispatchErrorWithThreadSingle() throws Exception { doTestDispatchError(1, true, false); } @Test public void testDispatchErrorWithThreadDouble() throws Exception { doTestDispatchError(2, true, false); } @Test public void testDispatchErrorWithThreadMultiple() throws Exception { doTestDispatchError(5, true, false); } @Test public void testDispatchErrorSingleThenComplete() throws Exception { doTestDispatchError(1, false, true); } @Test public void testDispatchErrorDoubleThenComplete() throws Exception { doTestDispatchError(2, false, true); } @Test public void testDispatchErrorMultipleThenComplete() throws Exception { doTestDispatchError(5, false, true); } @Test public void testDispatchErrorWithThreadSingleThenComplete() throws Exception { doTestDispatchError(1, true, true); } @Test public void testDispatchErrorWithThreadDoubleThenComplete() throws Exception { doTestDispatchError(2, true, true); } @Test public void testDispatchErrorWithThreadMultipleThenComplete() throws Exception { doTestDispatchError(5, true, true); } private void doTestDispatchError(int iter, boolean useThread, boolean completeOnError) 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); DispatchingServlet dispatch = new DispatchingServlet(true, completeOnError); Wrapper wrapper = Tomcat.addServlet(ctx, "dispatch", dispatch); wrapper.setAsyncSupported(true); ctx.addServletMapping("/stage1", "dispatch"); ErrorServlet error = new ErrorServlet(true); Tomcat.addServlet(ctx, "error", error); ctx.addServletMapping("/stage2", "error"); ctx.addApplicationListener(TrackingRequestListener.class.getName()); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/stage1?iter="); url.append(iter); if (useThread) { url.append("&useThread=y"); } ByteChunk res = getUrl(url.toString()); StringBuilder expected = new StringBuilder("requestInitialized-"); int loop = iter; while (loop > 0) { expected.append("DispatchingServletGet-"); if (loop != iter) { expected.append("onStartAsync-"); } loop--; } expected.append("ErrorServletGet-onError-onComplete-requestDestroyed"); assertEquals(expected.toString(), res.toString()); // Check the access log alv.validateAccessLog(1, 200, 0, REQUEST_TIME); } private static class ErrorServlet extends HttpServlet { private static final long serialVersionUID = 1L; private boolean flush = false; public ErrorServlet(boolean flush) { this.flush = flush; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write("ErrorServletGet-"); if (flush) { resp.flushBuffer(); } try { // Give the original thread a chance to exit the // ErrorReportValve before we throw this exception Thread.sleep(500); } catch (InterruptedException e) { throw new ServletException(e); } throw new ServletException("Opps."); } } @Test public void testBug50352() 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); AsyncStartRunnable servlet = new AsyncStartRunnable(); Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/", "servlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); ByteChunk res = getUrl("http://localhost:" + getPort() + "/"); assertEquals("Runnable-onComplete-", res.toString()); // Check the access log alv.validateAccessLog(1, 200, AsyncStartRunnable.THREAD_SLEEP_TIME, AsyncStartRunnable.THREAD_SLEEP_TIME + REQUEST_TIME); } private static final class AsyncStartRunnable extends HttpServlet { private static final long serialVersionUID = 1L; public static final long THREAD_SLEEP_TIME = 3000; @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final AsyncContext asyncContext = request.startAsync(request, response); asyncContext.addListener(new TrackingListener(false, false, null)); asyncContext.start(new Runnable() { @Override public void run() { try { Thread.sleep(THREAD_SLEEP_TIME); asyncContext.getResponse().getWriter().write( "Runnable-"); asyncContext.complete(); } catch (Exception e) { e.printStackTrace(); } } }); } } @Test public void testBug50753() 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")); Bug50753Servlet servlet = new Bug50753Servlet(); Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/", "servlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); // Call the servlet once Map<String,List<String>> headers = new LinkedHashMap<>(); ByteChunk bc = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/", bc, headers); assertEquals(200, rc); assertEquals("OK", bc.toString()); List<String> testHeader = headers.get("A"); assertNotNull(testHeader); assertEquals(1, testHeader.size()); assertEquals("xyz",testHeader.get(0)); // Check the access log alv.validateAccessLog(1, 200, Bug50753Servlet.THREAD_SLEEP_TIME, Bug50753Servlet.THREAD_SLEEP_TIME + REQUEST_TIME); } private static class Bug50753Servlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final long THREAD_SLEEP_TIME = 5000; @Override protected void doGet(HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final AsyncContext ctx = req.startAsync(); ctx.start(new Runnable() { @Override public void run() { try { Thread.sleep(THREAD_SLEEP_TIME); resp.setHeader("A", "xyz"); resp.setContentType("text/plain"); resp.setContentLength("OK".getBytes().length); resp.getWriter().print("OK"); ctx.complete(); } catch (Exception e) { e.printStackTrace(); } } }); } } @Test public void testErrorHandling() 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); ErrorServlet error = new ErrorServlet(false); Tomcat.addServlet(ctx, "error", error); ctx.addServletMapping("/error", "error"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/error"); int rc = getUrl(url.toString(), new ByteChunk(), null); assertEquals(500, rc); // Without this test may complete before access log has a chance to log // the request Thread.sleep(REQUEST_TIME); // Check the access log alv.validateAccessLog(1, 500, 0, REQUEST_TIME); } @Test public void testCommitOnComplete() 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); AsyncStatusServlet asyncStatusServlet = new AsyncStatusServlet(HttpServletResponse.SC_BAD_REQUEST); Wrapper wrapper = Tomcat.addServlet(ctx, "asyncStatusServlet", asyncStatusServlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/asyncStatusServlet", "asyncStatusServlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/asyncStatusServlet"); int rc = getUrl(url.toString(), new ByteChunk(), null); assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc); // Without this test may complete before access log has a chance to log // the request Thread.sleep(REQUEST_TIME); // Check the access log alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0, REQUEST_TIME); } private static class AsyncStatusServlet extends HttpServlet { private static final long serialVersionUID = 1L; private int status = 200; public AsyncStatusServlet(int status) { this.status = status; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { AsyncContext actxt = req.startAsync(); resp.setStatus(status); actxt.complete(); } } @Test public void testBug51197a() throws Exception { doTestBug51197(false); } @Test public void testBug51197b() throws Exception { doTestBug51197(true); } private void doTestBug51197(boolean threaded) 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); AsyncErrorServlet asyncErrorServlet = new AsyncErrorServlet(HttpServletResponse.SC_BAD_REQUEST, threaded); Wrapper wrapper = Tomcat.addServlet(ctx, "asyncErrorServlet", asyncErrorServlet); wrapper.setAsyncSupported(true); ctx.addServletMapping("/asyncErrorServlet", "asyncErrorServlet"); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/asyncErrorServlet"); ByteChunk res = new ByteChunk(); int rc = getUrl(url.toString(), res, null); assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc); // SRV 10.9.2 - Writing the response is entirely the application's // responsibility when an error occurs on an application thread. // The test servlet writes no content in this case. if (threaded) { assertEquals(0, res.getLength()); } else { assertTrue(res.getLength() > 0); } // Without this test may complete before access log has a chance to log // the request Thread.sleep(REQUEST_TIME); // Check the access log alv.validateAccessLog(1, HttpServletResponse.SC_BAD_REQUEST, 0, REQUEST_TIME); } private static class AsyncErrorServlet extends HttpServlet { private static final long serialVersionUID = 1L; public static final String ERROR_MESSAGE = "It broke."; private int status; private boolean threaded; public AsyncErrorServlet(int status, boolean threaded) { this.status = status; this.threaded = threaded; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { final AsyncContext actxt = req.startAsync(); actxt.setTimeout(TIMEOUT); if (threaded) { actxt.start(new Runnable() { @Override public void run() { try { HttpServletResponse resp = (HttpServletResponse) actxt.getResponse(); resp.sendError(status, ERROR_MESSAGE); // Complete so there is no delay waiting for the // timeout actxt.complete(); } catch (IOException e) { // Ignore } } }); } else { resp.sendError(status); } } } @Test public void testBug53337() 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); Wrapper a = Tomcat.addServlet(ctx, "ServletA", new Bug53337ServletA()); a.setAsyncSupported(true); Wrapper b = Tomcat.addServlet(ctx, "ServletB", new Bug53337ServletB()); b.setAsyncSupported(true); Tomcat.addServlet(ctx, "ServletC", new Bug53337ServletC()); ctx.addServletMapping("/ServletA", "ServletA"); ctx.addServletMapping("/ServletB", "ServletB"); ctx.addServletMapping("/ServletC", "ServletC"); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/ServletA"); ByteChunk body = new ByteChunk(); int rc = getUrl(url.toString(), body, null); assertEquals(HttpServletResponse.SC_OK, rc); assertEquals("OK", body.toString()); } private static class Bug53337ServletA extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { RequestDispatcher rd = req.getRequestDispatcher("/ServletB"); rd.forward(req, resp); } } private static class Bug53337ServletB extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { final AsyncContext async = req.startAsync(); // Just for debugging async.setTimeout(100000); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.submit(new Runnable() { @Override public void run() { async.dispatch("/ServletC"); } }); executor.shutdown(); } } private static class Bug53337ServletC extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("OK"); } } @Test public void testBug53843() 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); Bug53843ServletA servletA = new Bug53843ServletA(); Wrapper a = Tomcat.addServlet(ctx, "ServletA", servletA); a.setAsyncSupported(true); Tomcat.addServlet(ctx, "ServletB", new Bug53843ServletB()); ctx.addServletMapping("/ServletA", "ServletA"); ctx.addServletMapping("/ServletB", "ServletB"); tomcat.start(); StringBuilder url = new StringBuilder(48); url.append("http://localhost:"); url.append(getPort()); url.append("/ServletA"); ByteChunk body = new ByteChunk(); int rc = getUrl(url.toString(), body, null); assertEquals(HttpServletResponse.SC_OK, rc); assertEquals("OK", body.toString()); assertTrue(servletA.isAsyncWhenExpected()); } private static class Bug53843ServletA extends HttpServlet { private static final long serialVersionUID = 1L; private boolean isAsyncWhenExpected = true; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Should not be async at this point isAsyncWhenExpected = isAsyncWhenExpected && !req.isAsyncStarted(); final AsyncContext async = req.startAsync(); // Should be async at this point isAsyncWhenExpected = isAsyncWhenExpected && req.isAsyncStarted(); async.start(new Runnable() { @Override public void run() { // This should be delayed until the original container // thread exists async.dispatch("/ServletB"); } }); try { Thread.sleep(3000); } catch (InterruptedException e) { throw new ServletException(e); } // Should be async at this point isAsyncWhenExpected = isAsyncWhenExpected && req.isAsyncStarted(); } public boolean isAsyncWhenExpected() { return isAsyncWhenExpected; } } private static class Bug53843ServletB extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/plain"); resp.getWriter().print("OK"); } } @Test public void testTimeoutErrorDispatchNone() throws Exception { doTestTimeoutErrorDispatch(null, null); } @Test public void testTimeoutErrorDispatchNonAsync() throws Exception { doTestTimeoutErrorDispatch(Boolean.FALSE, null); } @Test public void testTimeoutErrorDispatchAsyncStart() throws Exception { doTestTimeoutErrorDispatch( Boolean.TRUE, ErrorPageAsyncMode.NO_COMPLETE); } @Test public void testTimeoutErrorDispatchAsyncComplete() throws Exception { doTestTimeoutErrorDispatch(Boolean.TRUE, ErrorPageAsyncMode.COMPLETE); } @Test public void testTimeoutErrorDispatchAsyncDispatch() throws Exception { doTestTimeoutErrorDispatch(Boolean.TRUE, ErrorPageAsyncMode.DISPATCH); } private void doTestTimeoutErrorDispatch(Boolean asyncError, ErrorPageAsyncMode mode) 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")); Context ctx = tomcat.addContext("", docBase.getAbsolutePath()); TimeoutServlet timeout = new TimeoutServlet(null, null); Wrapper w1 = Tomcat.addServlet(ctx, "time", timeout); w1.setAsyncSupported(true); ctx.addServletMapping("/async", "time"); NonAsyncServlet nonAsync = new NonAsyncServlet(); Wrapper w2 = Tomcat.addServlet(ctx, "nonAsync", nonAsync); w2.setAsyncSupported(true); ctx.addServletMapping("/error/nonasync", "nonAsync"); AsyncErrorPage asyncErrorPage = new AsyncErrorPage(mode); Wrapper w3 = Tomcat.addServlet(ctx, "asyncErrorPage", asyncErrorPage); w3.setAsyncSupported(true); ctx.addServletMapping("/error/async", "asyncErrorPage"); if (asyncError != null) { ErrorPage ep = new ErrorPage(); ep.setErrorCode(500); if (asyncError.booleanValue()) { ep.setLocation("/error/async"); } else { ep.setLocation("/error/nonasync"); } ctx.addErrorPage(ep); } ctx.addApplicationListener(TrackingRequestListener.class.getName()); TesterAccessLogValve alv = new TesterAccessLogValve(); ctx.getPipeline().addValve(alv); TesterAccessLogValve alvGlobal = new TesterAccessLogValve(); tomcat.getHost().getPipeline().addValve(alvGlobal); tomcat.start(); ByteChunk res = new ByteChunk(); try { getUrl("http://localhost:" + getPort() + "/async", res, null); } catch (IOException ioe) { // Ignore - expected for some error conditions } StringBuilder expected = new StringBuilder(); if (asyncError == null) { // No error handler - just get the 500 response expected.append("requestInitialized-TimeoutServletGet-"); // Note: With an error handler the response will be reset and these // will be lost } if (asyncError != null) { if (asyncError.booleanValue()) { expected.append("AsyncErrorPageGet-"); if (mode == ErrorPageAsyncMode.NO_COMPLETE){ expected.append("NoOp-"); } else if (mode == ErrorPageAsyncMode.COMPLETE) { expected.append("Complete-"); } else if (mode == ErrorPageAsyncMode.DISPATCH) { expected.append("Dispatch-NonAsyncServletGet-"); } } else { expected.append("NonAsyncServletGet-"); } } expected.append("requestDestroyed"); Assert.assertEquals(expected.toString(), res.toString()); // Check the access log alvGlobal.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); alv.validateAccessLog(1, 500, TimeoutServlet.ASYNC_TIMEOUT, TimeoutServlet.ASYNC_TIMEOUT + TIMEOUT_MARGIN + REQUEST_TIME); } private static enum ErrorPageAsyncMode { NO_COMPLETE, COMPLETE, DISPATCH } private static class AsyncErrorPage extends HttpServlet { private static final long serialVersionUID = 1L; private final ErrorPageAsyncMode mode; public AsyncErrorPage(ErrorPageAsyncMode mode) { this.mode = mode; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter writer = resp.getWriter(); writer.write("AsyncErrorPageGet-"); resp.flushBuffer(); final AsyncContext ctxt = req.getAsyncContext(); switch(mode) { case COMPLETE: writer.write("Complete-"); ctxt.complete(); break; case DISPATCH: writer.write("Dispatch-"); ctxt.dispatch("/error/nonasync"); break; case NO_COMPLETE: writer.write("NoOp-"); break; default: // Impossible break; } } } }
54,801
Bug 54801 EL-like expressions in jsp:scriptlet break compilation of JSP XML documents
null
resolved fixed
1631be1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-25T13:16:45Z
2013-04-05T02:46: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) { 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; } }
54,801
Bug 54801 EL-like expressions in jsp:scriptlet break compilation of JSP XML documents
null
resolved fixed
1631be1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-04-25T13:16:45Z
2013-04-05T02:46:40Z
test/org/apache/jasper/compiler/TestJspDocumentParser.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.File; import java.io.IOException; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; 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 TestJspDocumentParser extends TomcatBaseTest { @Test public void testBug47977() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0"); // app dir is relative to server home tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug47977.jspx", new ByteChunk(), null); assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); } @Test public void testBug48827() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp-3.0"); // app dir is relative to server home tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); Exception e = null; try { getUrl("http://localhost:" + getPort() + "/test/bug48nnn/bug48827.jspx"); } catch (IOException ioe) { e = ioe; } // Should not fail assertNull(e); } }
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
java/org/apache/jasper/tagplugins/jstl/core/ForEach.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 org.apache.jasper.compiler.tagplugin.TagPlugin; import org.apache.jasper.compiler.tagplugin.TagPluginContext; public final class ForEach implements TagPlugin { private boolean hasVar, hasBegin, hasEnd, hasStep; @Override public void doTag(TagPluginContext ctxt) { String index = null; boolean hasVarStatus = ctxt.isAttributeSpecified("varStatus"); if (hasVarStatus) { ctxt.dontUseTagPlugin(); return; } hasVar = ctxt.isAttributeSpecified("var"); hasBegin = ctxt.isAttributeSpecified("begin"); hasEnd = ctxt.isAttributeSpecified("end"); hasStep = ctxt.isAttributeSpecified("step"); boolean hasItems = ctxt.isAttributeSpecified("items"); if (hasItems) { doCollection(ctxt); return; } // We must have a begin and end attributes index = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("for (int " + index + " = "); ctxt.generateAttribute("begin"); ctxt.generateJavaSource("; " + index + " <= "); ctxt.generateAttribute("end"); if (hasStep) { ctxt.generateJavaSource("; " + index + "+="); ctxt.generateAttribute("step"); ctxt.generateJavaSource(") {"); } else { ctxt.generateJavaSource("; " + index + "++) {"); } // If var is specified and the body contains an EL, then sycn // the var attribute if (hasVar /* && ctxt.hasEL() */) { ctxt.generateJavaSource("_jspx_page_context.setAttribute("); ctxt.generateAttribute("var"); ctxt.generateJavaSource(", String.valueOf(" + index + "));"); } ctxt.generateBody(); ctxt.generateJavaSource("}"); } /** * Generate codes for Collections * The pseudo code is: */ private void doCollection(TagPluginContext ctxt) { ctxt.generateImport("java.util.*"); generateIterators(ctxt); String itemsV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("Object " + itemsV + "= "); ctxt.generateAttribute("items"); ctxt.generateJavaSource(";"); String indexV=null, beginV=null, endV=null, stepV=null; if (hasBegin) { beginV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("int " + beginV + " = "); ctxt.generateAttribute("begin"); ctxt.generateJavaSource(";"); } if (hasEnd) { indexV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("int " + indexV + " = 0;"); endV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("int " + endV + " = "); ctxt.generateAttribute("end"); ctxt.generateJavaSource(";"); } if (hasStep) { stepV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("int " + stepV + " = "); ctxt.generateAttribute("step"); ctxt.generateJavaSource(";"); } String iterV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("Iterator " + iterV + " = null;"); // Object[] ctxt.generateJavaSource("if (" + itemsV + " instanceof Object[])"); ctxt.generateJavaSource(iterV + "=toIterator((Object[])" + itemsV + ");"); // boolean[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof boolean[])"); ctxt.generateJavaSource(iterV + "=toIterator((boolean[])" + itemsV + ");"); // byte[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof byte[])"); ctxt.generateJavaSource(iterV + "=toIterator((byte[])" + itemsV + ");"); // char[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof char[])"); ctxt.generateJavaSource(iterV + "=toIterator((char[])" + itemsV + ");"); // short[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof short[])"); ctxt.generateJavaSource(iterV + "=toIterator((short[])" + itemsV + ");"); // int[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof int[])"); ctxt.generateJavaSource(iterV + "=toIterator((int[])" + itemsV + ");"); // long[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof long[])"); ctxt.generateJavaSource(iterV + "=toIterator((long[])" + itemsV + ");"); // float[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof float[])"); ctxt.generateJavaSource(iterV + "=toIterator((float[])" + itemsV + ");"); // double[] ctxt.generateJavaSource("else if (" + itemsV + " instanceof double[])"); ctxt.generateJavaSource(iterV + "=toIterator((double[])" + itemsV + ");"); // Collection ctxt.generateJavaSource("else if (" + itemsV + " instanceof Collection)"); ctxt.generateJavaSource(iterV + "=((Collection)" + itemsV + ").iterator();"); // Iterator ctxt.generateJavaSource("else if (" + itemsV + " instanceof Iterator)"); ctxt.generateJavaSource(iterV + "=(Iterator)" + itemsV + ";"); // Enumeration ctxt.generateJavaSource("else if (" + itemsV + " instanceof Enumeration)"); ctxt.generateJavaSource(iterV + "=toIterator((Enumeration)" + itemsV + ");"); // Map ctxt.generateJavaSource("else if (" + itemsV + " instanceof Map)"); ctxt.generateJavaSource(iterV + "=((Map)" + itemsV + ").entrySet().iterator();"); // Not null ctxt.generateJavaSource("if (" + iterV + " != null) {"); if (hasBegin) { String tV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("for (int " + tV + "=" + beginV + ";" + tV + ">0 && " + iterV + ".hasNext(); " + tV + "--)"); ctxt.generateJavaSource(iterV + ".next();"); } ctxt.generateJavaSource("while (" + iterV + ".hasNext()){"); if (hasVar) { ctxt.generateJavaSource("_jspx_page_context.setAttribute("); ctxt.generateAttribute("var"); ctxt.generateJavaSource(", " + iterV + ".next());"); } ctxt.generateBody(); if (hasStep) { String tV = ctxt.getTemporaryVariableName(); ctxt.generateJavaSource("for (int " + tV + "=" + stepV + "-1;" + tV + ">0 && " + iterV + ".hasNext(); " + tV + "--)"); ctxt.generateJavaSource(iterV + ".next();"); } if (hasEnd) { if (hasStep) { ctxt.generateJavaSource(indexV + "+=" + stepV + ";"); } else { ctxt.generateJavaSource(indexV + "++;"); } if (hasBegin) { ctxt.generateJavaSource("if(" + beginV + "+" + indexV + ">"+ endV + ")"); } else { ctxt.generateJavaSource("if(" + indexV + ">" + endV + ")"); } ctxt.generateJavaSource("break;"); } ctxt.generateJavaSource("}"); // while ctxt.generateJavaSource("}"); // Not Null } /** * Generate iterators for data types supported in items */ private void generateIterators(TagPluginContext ctxt) { // Object[] ctxt.generateDeclaration("ObjectArrayIterator", "private Iterator toIterator(final Object[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return a[index++];}\n" + " public void remove() {}\n" + " });\n" + "}" ); // boolean[] ctxt.generateDeclaration("booleanArrayIterator", "private Iterator toIterator(final boolean[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Boolean(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // byte[] ctxt.generateDeclaration("byteArrayIterator", "private Iterator toIterator(final byte[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Byte(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // char[] ctxt.generateDeclaration("charArrayIterator", "private Iterator toIterator(final char[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Character(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // short[] ctxt.generateDeclaration("shortArrayIterator", "private Iterator toIterator(final short[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Short(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // int[] ctxt.generateDeclaration("intArrayIterator", "private Iterator toIterator(final int[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Integer(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // long[] ctxt.generateDeclaration("longArrayIterator", "private Iterator toIterator(final long[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Long(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // float[] ctxt.generateDeclaration("floatArrayIterator", "private Iterator toIterator(final float[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Float(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // double[] ctxt.generateDeclaration("doubleArrayIterator", "private Iterator toIterator(final double[] a){\n" + " return (new Iterator() {\n" + " int index=0;\n" + " public boolean hasNext() {\n" + " return index < a.length;}\n" + " public Object next() {\n" + " return new Double(a[index++]);}\n" + " public void remove() {}\n" + " });\n" + "}" ); // Enumeration ctxt.generateDeclaration("enumIterator", "private Iterator toIterator(final Enumeration e){\n" + " return (new Iterator() {\n" + " public boolean hasNext() {\n" + " return e.hasMoreElements();}\n" + " public Object next() {\n" + " return e.nextElement();}\n" + " public void remove() {}\n" + " });\n" + "}" ); } }