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
55,735
Bug 55735 Additional quote entity in html element attribute evaluated in tagx if attribute contains EL expression
null
resolved fixed
7ee1275
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-05T22:46:35Z
2013-11-02T11:00:00Z
test/org/apache/jasper/compiler/TesterValidator.java
55,735
Bug 55735 Additional quote entity in html element attribute evaluated in tagx if attribute contains EL expression
null
resolved fixed
7ee1275
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-05T22:46:35Z
2013-11-02T11:00:00Z
test/org/apache/jasper/runtime/TesterPageContextImpl.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 org.junit.Assert; import org.junit.Test; /** * Performance tests for {@link PageContextImpl}. */ public class TesterPageContextImpl { private static String[] bug53867TestData = new String[] { "Hello World!", "<meta http-equiv=\"Content-Language\">", "This connection has limited network connectivity.", "Please use this web page & to access file server resources." }; @Test public void testBug53867() { for (int i = 0; i < 10; i++) { doTestBug53867(); } } private static void doTestBug53867() { int count = 100000; for (int j = 0; j < bug53867TestData.length; j++) { Assert.assertEquals(doTestBug53867OldVersion(bug53867TestData[j]), PageContextImpl.XmlEscape(bug53867TestData[j])); } for (int i = 0; i < 100; i++) { for (int j = 0; j < bug53867TestData.length; j++) { doTestBug53867OldVersion(bug53867TestData[j]); } } for (int i = 0; i < 100; i++) { for (int j = 0; j < bug53867TestData.length; j++) { PageContextImpl.XmlEscape(bug53867TestData[j]); } } long start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { for (int j = 0; j < bug53867TestData.length; j++) { doTestBug53867OldVersion(bug53867TestData[j]); } } System.out.println( "Old escape:" + (System.currentTimeMillis() - start)); start = System.currentTimeMillis(); for (int i = 0; i < count; i++) { for (int j = 0; j < bug53867TestData.length; j++) { PageContextImpl.XmlEscape(bug53867TestData[j]); } } System.out.println( "New escape:" + (System.currentTimeMillis() - start)); } private static String doTestBug53867OldVersion(String s) { if (s == null) return null; StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if (c == '<') { sb.append("&lt;"); } else if (c == '>') { sb.append("&gt;"); } else if (c == '\'') { sb.append("&#039;"); // &apos; } else if (c == '&') { sb.append("&amp;"); } else if (c == '"') { sb.append("&#034;"); // &quot; } else { sb.append(c); } } return sb.toString(); } }
55,749
Bug 55749 Disabling SSLEngine in AprLifecycleListener leads to misleading error message at startup when SSL Connector is delcared
Put a <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="off" /> in you server.xml. Put the APR connector some weeks later in your server.xml: <Connector protocol="org.apache.coyote.http11.Http11AprProtocol" port="@HTTPS_PORT@" connectionTimeout="20000" maxHttpHeaderSize="24576" maxThreads="250" URIEncoding="UTF-8" bufferSize="4096" scheme="https" secure="true" SSLEnabled="true" SSLProtocol="TLSv1" SSLCipherSuite="HIGH:!ADH" SSLCertificateFile="@SSL_CERT_FILE@" SSLCertificateKeyFile="@SSL_CERT_KEY_FILE@" SSLPassword="@SSL_PASSWORD@" /> Start your Tomcat and receive following confusing message: Nov 06, 2013 1:30:39 PM org.apache.coyote.http11.Http11AprProtocol start SEVERE: Error starting endpoint java.lang.Exception: Socket bind failed: [226] Adresse bereits im Zugriff at org.apache.tomcat.util.net.AprEndpoint.init(AprEndpoint.java:671) at org.apache.tomcat.util.net.AprEndpoint.start(AprEndpoint.java:851) at org.apache.coyote.http11.Http11AprProtocol.start(Http11AprProtocol.java:139) at org.apache.catalina.connector.Connector.start(Connector.java:1196) at org.apache.catalina.core.StandardService.start(StandardService.java:540) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) Nov 06, 2013 1:30:39 PM org.apache.catalina.core.StandardService start SEVERE: Failed to start connector [Connector[HTTP/1.1-8444]] LifecycleException: service.getName(): "Catalina"; Protocol handler start failed: java.lang.Exception: Socket bind failed: [226] Adresse bereits im Zugriff at org.apache.catalina.connector.Connector.start(Connector.java:1203) at org.apache.catalina.core.StandardService.start(StandardService.java:540) at org.apache.catalina.core.StandardServer.start(StandardServer.java:754) at org.apache.catalina.startup.Catalina.start(Catalina.java:595) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:606) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) This is of course not correct. The port IS availble but the SSL engine has been turned off. There should be a check at stratup which says that this is an illegal state.
resolved fixed
014cf1c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-10T20:20:37Z
2013-11-06T17:46: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 java.util.concurrent.atomic.AtomicInteger; 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<Long> { // -------------------------------------------------------------- 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 final 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 = false; /* * When the endpoint is created and configured, the APR library will not * have been initialised. This flag is used to determine if the default * value of useSendFile should be changed if the APR library indicates it * supports send file once it has been initialised. If useSendFile is set * by configuration, that configuration will always take priority. */ private boolean useSendFileSet = false; public void setUseSendfile(boolean useSendfile) { useSendFileSet = true; 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 socket poller. */ protected AsyncTimeout asyncTimeout = null; public AsyncTimeout getAsyncTimeout() { return asyncTimeout; } /** * 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); } // Enable Sendfile by default if it has not been configured but usage on // systems which don't support it cause major problems if (!useSendFileSet) { useSendfile = Library.APR_HAS_SENDFILE; } else 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 if (useSendfile) { useSendfile = false; if (useSendFileSet) { log.warn(sm.getString("endpoint.apr.noSendfileWithSSL")); } } } } 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 asyncTimeout = new AsyncTimeout(); Thread timeoutThread = new Thread(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; poller.stop(); asyncTimeout.stop(); 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) { if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.debug.socket", Long.valueOf(socket))); } AprSocketWrapper wrapper = new AprSocketWrapper(Long.valueOf(socket)); wrapper.setKeepAliveLeft(getMaxKeepAliveRequests()); wrapper.setSecure(isSSLEnabled()); 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)); // Make sure connection hasn't been closed if (wrapper != null) { 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; } @Override public void processSocket(SocketWrapper<Long> socket, SocketStatus status, boolean dispatch) { try { // Synchronisation is required here as this code may be called as a // result of calling AsyncContext.dispatch() from a non-container // thread synchronized (socket) { if (waitingRequests.remove(socket)) { SocketProcessor proc = new SocketProcessor(socket, status); Executor executor = getExecutor(); if (dispatch && executor != null) { 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.execute(proc); } finally { if (Constants.IS_SECURITY_ENABLED) { PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader); AccessController.doPrivileged(pa); } else { Thread.currentThread().setContextClassLoader(loader); } } } else { proc.run(); } } } } catch (RejectedExecutionException ree) { log.warn(sm.getString("endpoint.executor.fail", socket) , ree); } 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); } } private void closeSocket(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. connections.remove(Long.valueOf(socket)); // 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 Poller poller = this.poller; if (poller != null) { if (!poller.close(socket)) { destroySocket(socket); } } } /* * This method should only be called if there is no chance that the socket * is currently being used by the Poller. It is generally a bad idea to call * this directly from a known error condition. */ private void destroySocket(long socket) { connections.remove(Long.valueOf(socket)); if (log.isDebugEnabled()) { String msg = sm.getString("endpoint.debug.destroySocket", Long.valueOf(socket)); if (log.isTraceEnabled()) { log.trace(msg, new Exception()); } else { log.debug(msg); } } // 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 (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); if (log.isDebugEnabled()) { long sa = Address.get(Socket.APR_REMOTE, socket); Sockaddr addr = Address.getInfo(sa); log.debug(sm.getString("endpoint.apr.remoteport", Long.valueOf(socket), Long.valueOf(addr.port))); } } 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 right away closeSocket(socket); } } else { // Close socket right away // No code path could have added the socket to the // Poller so use destroySocket() 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 { private volatile boolean asyncTimeoutRunning = true; /** * 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 (asyncTimeoutRunning) { 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.isAsync()) { long access = socket.getLastAccess(); if (socket.getTimeout() > 0 && (now-access)>socket.getTimeout()) { processSocket(socket, SocketStatus.TIMEOUT, true); } } } // Loop if endpoint is paused while (paused && asyncTimeoutRunning) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } } } protected void stop() { asyncTimeoutRunning = false; } } // -------------------------------------------------- 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++; } /** * Removes the specified socket from the poller. * * @return The configured timeout for the socket or zero if the socket * was not in the list of socket timeouts */ public long remove(long socket) { long result = 0; for (int i = 0; i < size; i++) { if (sockets[i] == socket) { result = timeouts[i]; sockets[i] = sockets[size - 1]; timeouts[i] = timeouts[size - 1]; size--; break; } } return result; } 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 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]; flags[size] = flags[size -1]; size--; return true; } } return false; } 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. */ private long[] pollers = null; /** * Actual poller size. */ private int actualPollerSize = 0; /** * Amount of spots left in the poller. */ private int[] pollerSpace = null; /** * Amount of low level pollers in use by this poller. */ private int pollerCount; /** * Timeout value for the poll call. */ private int pollerTime; /** * Variable poller timeout that adjusts depending on how many poll sets * are in use so that the total poll time across all poll sets remains * equal to pollTime. */ private int nextPollerTime; /** * Root pool. */ private long pool = 0; /** * Socket descriptors. */ private long[] desc; /** * List of sockets to be added to the poller. */ private SocketList addList = null; /** * List of sockets to be closed. */ private SocketList closeList = null; /** * Structure used for storing timeouts. */ private SocketTimeouts timeouts = null; /** * Last run of maintain. Maintain will run usually every 5s. */ private long lastMaintain = System.currentTimeMillis(); /** * The number of connections currently inside this Poller. The correct * operation of the Poller depends on this figure being correct. If it * is not, it is possible that the Poller will enter a wait loop where * it waits for the next connection to be added to the Poller before it * calls poll when it should still be polling existing connections. * Although not necessary at the time of writing this comment, it has * been implemented as an AtomicInteger to ensure that it remains * thread-safe. */ private AtomicInteger connectionCount = new AtomicInteger(0); public int getConnectionCount() { return connectionCount.get(); } private volatile boolean pollerRunning = true; /** * 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. actualPollerSize = 1024; } else { 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; nextPollerTime = pollerTime; 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.set(0); addList = new SocketList(defaultPollerSize); closeList = new SocketList(defaultPollerSize); } /* * This method is synchronized so that it is not possible for a socket * to be added to the Poller's addList once this method has completed. */ protected synchronized void stop() { pollerRunning = false; } /** * 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.notify(); 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))) { // Poller isn't running at this point so use destroySocket() // directly 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.set(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). 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 (log.isDebugEnabled()) { String msg = sm.getString("endpoint.debug.pollerAdd", Long.valueOf(socket), Integer.valueOf(timeout), Integer.valueOf(flags)); if (log.isTraceEnabled()) { log.trace(msg, new Exception()); } else { log.debug(msg); } } 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. Don't add the // socket once the poller has stopped but destroy it straight // away if (pollerRunning && 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))) { closeSocket(socket); } } } /** * Add specified socket to one of the pollers. Must only be called from * {@link Poller#run()}. */ private 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.incrementAndGet(); return true; } } } return false; } protected boolean close(long socket) { if (!pollerRunning) { return false; } synchronized (this) { if (!pollerRunning) { return false; } closeList.add(socket, 0, 0); this.notify(); return true; } } /** * Remove specified socket from the pollers. Must only be called from * {@link Poller#run()}. */ private boolean removeFromPoller(long socket) { if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.debug.pollerRemove", Long.valueOf(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.decrementAndGet(); if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.debug.pollerRemoved", Long.valueOf(socket))); } break; } } } timeouts.remove(socket); return (rv == Status.APR_SUCCESS); } /** * Timeout checks. Must only be called from {@link Poller#run()}. */ private void maintain() { long date = System.currentTimeMillis(); // Maintain runs at most once every 1s, although it will likely get // called more if ((date - lastMaintain) < 1000L) { return; } else { lastMaintain = date; } long socket = timeouts.check(date); while (socket != 0) { if (log.isDebugEnabled()) { log.debug(sm.getString("endpoint.debug.socketTimeout", Long.valueOf(socket))); } 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; SocketList localAddList = new SocketList(getMaxConnections()); SocketList localCloseList = new SocketList(getMaxConnections()); // Loop until we receive a shutdown command while (pollerRunning) { // Loop if endpoint is paused while (pollerRunning && paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Check timeouts if the poller is empty while (pollerRunning && connectionCount.get() < 1 && addList.size() < 1 && closeList.size() < 1) { // Reset maintain time. try { if (getSoTimeout() > 0 && pollerRunning) { maintain(); } synchronized (this) { this.wait(10000); } } catch (InterruptedException e) { // Ignore } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().warn(sm.getString("endpoint.timeout.err")); } } // Don't add or poll if the poller has been stopped if (!pollerRunning) { break; } try { // Duplicate the add and remove lists so that the syncs are // minimised if (closeList.size() > 0) { synchronized (this) { // Duplicate to another list, so that the syncing is // minimal closeList.duplicate(localCloseList); closeList.clear(); } } else { localCloseList.clear(); } if (addList.size() > 0) { synchronized (this) { // Duplicate to another list, so that the syncing is // minimal addList.duplicate(localAddList); addList.clear(); } } else { localAddList.clear(); } // Remove sockets if (localCloseList.size() > 0) { SocketInfo info = localCloseList.get(); while (info != null) { localAddList.remove(info.socket); removeFromPoller(info.socket); destroySocket(info.socket); info = localCloseList.get(); } } // Add sockets which are waiting to the poller if (localAddList.size() > 0) { SocketInfo info = localAddList.get(); while (info != null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.pollerAddDo", Long.valueOf(info.socket))); } timeouts.remove(info.socket); AprSocketWrapper wrapper = connections.get( Long.valueOf(info.socket)); if (wrapper == null) { continue; } if (info.read() || info.write()) { boolean comet = wrapper.isComet(); if (comet || wrapper.pollerFlags != 0) { 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))) { closeSocket(info.socket); } } else { timeouts.add(info.socket, System.currentTimeMillis() + info.timeout); } } else { // Should never happen. closeSocket(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], nextPollerTime, desc, true); // Reset the nextPollerTime nextPollerTime = pollerTime; } else { // Skipping an empty poll set means skipping a wait // time of pollerTime microseconds. If most of the // poll sets are skipped then this loop will be // tighter than expected which could lead to higher // than expected CPU usage. Extending the // nextPollerTime ensures that this loop always // takes about the same time to execute. nextPollerTime += pollerTime; } if (rv > 0) { pollerSpace[i] += rv; connectionCount.addAndGet(-rv); for (int n = 0; n < rv; n++) { long timeout = timeouts.remove(desc[n*2+1]); AprSocketWrapper wrapper = connections.get( Long.valueOf(desc[n*2+1])); if (getLog().isDebugEnabled()) { log.debug(sm.getString( "endpoint.debug.pollerProcess", Long.valueOf(desc[n*2+1]), Long.valueOf(desc[n*2]))); } wrapper.pollerFlags = wrapper.pollerFlags & ~((int) desc[n*2]); // 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 closeSocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) { if (wrapper.pollerFlags != 0) { add(desc[n*2+1], 1, wrapper.pollerFlags); } if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { // Close socket and clear pool closeSocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) { if (wrapper.pollerFlags != 0) { add(desc[n*2+1], 1, wrapper.pollerFlags); } if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool closeSocket(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 closeSocket(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)) { if (wrapper.isAsync() || wrapper.isUpgraded()) { // Must be using non-blocking IO for the socket to be in the // poller during async processing. Need to trigger error // handling. Poller may return error codes plus the flags it // was waiting for or it may just return an error code. We // could return ASYNC_[WRITE|READ]_ERROR here but if we do, // there will be no exception associated with the error in // application code. By signalling read/write is possible, a // read/write will be attempted, fail and that will trigger // an exception the application will see. // Check the return flags first, followed by what the socket // was registered for if ((desc[n*2] & Poll.APR_POLLIN) == Poll.APR_POLLIN) { // Error probably occurred during a non-blocking read if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { // Close socket and clear pool closeSocket(desc[n*2+1]); } } else if ((desc[n*2] & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) { // Error probably occurred during a non-blocking write if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool closeSocket(desc[n*2+1]); } } else if ((wrapper.pollerFlags & Poll.APR_POLLIN) == Poll.APR_POLLIN) { // Can't tell what was happening when the error occurred but the // socket is registered for non-blocking read so use that if (!processSocket(desc[n*2+1], SocketStatus.OPEN_READ)) { // Close socket and clear pool closeSocket(desc[n*2+1]); } } else if ((wrapper.pollerFlags & Poll.APR_POLLOUT) == Poll.APR_POLLOUT) { // Can't tell what was happening when the error occurred but the // socket is registered for non-blocking write so use that if (!processSocket(desc[n*2+1], SocketStatus.OPEN_WRITE)) { // Close socket and clear pool closeSocket(desc[n*2+1]); } } else { // Close socket and clear pool closeSocket(desc[n*2+1]); } } else { // Close socket and clear pool closeSocket(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 closeSocket(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 error = true; closeSocket(desc[n*2+1]); } if (!error && wrapper.pollerFlags != 0) { // If socket was registered for multiple events but // only some of the occurred, re-register for the // remaining events. // timeout is the value of System.currentTimeMillis() that // was set as the point that the socket will timeout. When // adding to the poller, the timeout from now in // milliseconds is required. // So first, subtract the current timestamp if (timeout > 0) { timeout = timeout - System.currentTimeMillis(); } // If the socket should have already expired by now, // re-add it with a very short timeout if (timeout <= 0) { timeout = 1; } // Should be impossible but just in case since timeout will // be cast to an int. if (timeout > Integer.MAX_VALUE) { timeout = Integer.MAX_VALUE; } add(desc[n*2+1], (int) timeout, wrapper.pollerFlags); } } else { // Unknown event getLog().warn(sm.getString( "endpoint.apr.pollUnknownEvent", Long.valueOf(desc[n*2]))); // Close socket and clear pool closeSocket(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.addAndGet(-count); Poll.destroy(pollers[i]); pollers[i] = newPoller; } } // Process socket timeouts if (getSoTimeout() > 0 && maintain++ > 1000 && pollerRunning) { // 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; private volatile boolean sendfileRunning = true; /** * 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() { sendfileRunning = false; // 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.notify(); 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); closeSocket(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++) { closeSocket(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 (sendfileRunning) { // Loop if endpoint is paused while (sendfileRunning && paused) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } } // Loop if poller is empty while (sendfileRunning && sendfileCount < 1 && addS.size() < 1) { // Reset maintain time. maintainTime = 0; try { synchronized (this) { this.wait(); } } catch (InterruptedException e) { // Ignore } } // Don't add or poll if the poller has been stopped if (!sendfileRunning) { break; } 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 closeSocket(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 closeSocket(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. closeSocket(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, getKeepAliveTimeout(), true, false); } else { // Close the socket since this is // the end of not keep-alive request. closeSocket(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 && sendfileRunning) { 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 closeSocket(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 closeSocket(socket.getSocket().longValue()); socket = null; } } else { // Process the request from this socket if (!setSocketOptions(socket.getSocket().longValue())) { // Close socket and pool closeSocket(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 closeSocket(socket.getSocket().longValue()); socket = null; } else if (state == Handler.SocketState.LONG) { socket.access(); if (socket.isAsync()) { 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() && SocketStatus.OPEN_WRITE == status) { synchronized (socket.getWriteThreadLock()) { doRun(); } } else { synchronized (socket) { doRun(); } } } private void doRun() { // Process the request from this socket if (socket.getSocket() == null) { // Closed in another thread return; } SocketState state = handler.process(socket, status); if (state == Handler.SocketState.CLOSED) { // Close socket and pool closeSocket(socket.getSocket().longValue()); socket.reset(null, 1); } else if (state == Handler.SocketState.LONG) { socket.access(); if (socket.isAsync()) { 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); } } }
55,760
Bug 55760 Tomcat SPNEGO authenticator incompatible with IBM JDK in case of Keytab based initiate and accept authentication
null
resolved fixed
0a4e847
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-11T09:45:49Z
2013-11-08T17:00:00Z
java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.io.File; import java.io.IOException; import java.security.Principal; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.regex.Pattern; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Request; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.codec.binary.Base64; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.Oid; /** * A SPNEGO authenticator that uses the SPENGO/Kerberos support built in to Java * 6. Successful Kerberos authentication depends on the correct configuration of * multiple components. If the configuration is invalid, the error messages are * often cryptic although a Google search will usually point you in the right * direction. */ public class SpnegoAuthenticator extends AuthenticatorBase { private static final Log log = LogFactory.getLog(SpnegoAuthenticator.class); private String loginConfigName = Constants.DEFAULT_LOGIN_MODULE_NAME; public String getLoginConfigName() { return loginConfigName; } public void setLoginConfigName(String loginConfigName) { this.loginConfigName = loginConfigName; } private boolean storeDelegatedCredential = true; public boolean isStoreDelegatedCredential() { return storeDelegatedCredential; } public void setStoreDelegatedCredential( boolean storeDelegatedCredential) { this.storeDelegatedCredential = storeDelegatedCredential; } private Pattern noKeepAliveUserAgents = null; public String getNoKeepAliveUserAgents() { Pattern p = noKeepAliveUserAgents; if (p == null) { return null; } else { return p.pattern(); } } public void setNoKeepAliveUserAgents(String noKeepAliveUserAgents) { if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.length() == 0) { this.noKeepAliveUserAgents = null; } else { this.noKeepAliveUserAgents = Pattern.compile(noKeepAliveUserAgents); } } @Override protected String getAuthMethod() { return Constants.SPNEGO_METHOD; } @Override protected void initInternal() throws LifecycleException { super.initInternal(); // Kerberos configuration file location String krb5Conf = System.getProperty(Constants.KRB5_CONF_PROPERTY); if (krb5Conf == null) { // System property not set, use the Tomcat default File krb5ConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_KRB5_CONF); System.setProperty(Constants.KRB5_CONF_PROPERTY, krb5ConfFile.getAbsolutePath()); } // JAAS configuration file location String jaasConf = System.getProperty(Constants.JAAS_CONF_PROPERTY); if (jaasConf == null) { // System property not set, use the Tomcat default File jaasConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_JAAS_CONF); System.setProperty(Constants.JAAS_CONF_PROPERTY, jaasConfFile.getAbsolutePath()); } // This property must be false for SPNEGO to work System.setProperty(Constants.USE_SUBJECT_CREDS_ONLY_PROPERTY, "false"); } @Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return true; } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength()); if (decoded.length == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(lc.getSubject(), action)); outToken = gssContext.acceptSecContext(decoded, 0, decoded.length); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = context.getRealm().authenticate(gssContext, isStoreDelegatedCredential()); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encodeBase64String(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); Pattern p = noKeepAliveUserAgents; if (p != null) { MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue( "user-agent"); if (ua != null && p.matcher(ua.toString()).matches()) { response.setHeader("Connection", "close"); } } return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } }
55,772
Bug 55772 Flushing AsyncContext response writer after ClientAbortException (BrokenPipe) causes request state to leak
null
resolved fixed
cb62f86
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T13:39:52Z
2013-11-13T10:53:20Z
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.ReadListener; import javax.servlet.RequestDispatcher; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServletResponse; 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.3 " + "(" + 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) { // A async read error is an IO error which means the socket // needs to be closed so set success to false to trigger a // close success = false; Throwable t = (Throwable)req.getAttribute( RequestDispatcher.ERROR_EXCEPTION); req.getAttributes().remove(RequestDispatcher.ERROR_EXCEPTION); if (req.getReadListener() != null) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); req.getReadListener().onError(t); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } if (t != null) { asyncConImpl.setErrorState(t, true); } } else if (status==SocketStatus.ASYNC_WRITE_ERROR) { // A async write error is an IO error which means the socket // needs to be closed so set success to false to trigger a // close success = false; Throwable t = (Throwable)req.getAttribute( RequestDispatcher.ERROR_EXCEPTION); req.getAttributes().remove(RequestDispatcher.ERROR_EXCEPTION); if (res.getWriteListener() != null) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); res.getWriteListener().onError(t); } finally { Thread.currentThread().setContextClassLoader(oldCL); } } if (t != null) { asyncConImpl.setErrorState(t, true); } } // Check to see if non-blocking writes or reads are being used if (!request.isAsyncDispatching() && request.isAsync()) { if (res.getWriteListener() != null && status == SocketStatus.OPEN_WRITE) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); res.onWritePossible(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); res.getWriteListener().onError(t); throw t; } finally { Thread.currentThread().setContextClassLoader(oldCL); } success = true; } else if (req.getReadListener() != null && status == SocketStatus.OPEN_READ) { ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); req.getReadListener().onDataAvailable(); if (request.isFinished()) { req.getReadListener().onAllDataRead(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); req.getReadListener().onError(t); throw t; } finally { Thread.currentThread().setContextClassLoader(oldCL); } success = true; } } 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(); 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.asyncDispatch"), t); } finally { if (!success) { res.setStatus(500); long time = 0; if (req.getStartTime() != -1) { time = System.currentTimeMillis() - req.getStartTime(); } log(req, res, time); } 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; ReadListener readListener = req.getReadListener(); if (readListener != null) { // Possible the all data may have been read during service() // method so this needs to be checked here ClassLoader oldCL = Thread.currentThread().getContextClassLoader(); ClassLoader newCL = request.getContext().getLoader().getClassLoader(); try { Thread.currentThread().setContextClassLoader(newCL); if (request.isFinished()) { req.getReadListener().onAllDataRead(); } } finally { Thread.currentThread().setContextClassLoader(oldCL); } } } 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); } } } 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, true); request.setURIConverter(conv); } else { conv.recycle(); } } catch (IOException e) { log.error("Invalid URI encoding; using HTTP default"); connector.setURIEncoding(null); } if (conv != null) { try { conv.convert(bc, cc, true); uri.setChars(cc.getBuffer(), cc.getStart(), cc.getLength()); return; } catch (IOException ioe) { // Should never happen as B2CConverter should replace // problematic characters request.getResponse().sendError( HttpServletResponse.SC_BAD_REQUEST); } } } // Default encoding: fast conversion for ISO-8859-1 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]; } } }
55,772
Bug 55772 Flushing AsyncContext response writer after ClientAbortException (BrokenPipe) causes request state to leak
null
resolved fixed
cb62f86
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T13:39:52Z
2013-11-13T10:53:20Z
java/org/apache/coyote/ActionCode.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; /** * ActionCodes represent callbacks from the servlet container to the coyote * connector. Actions are implemented by ProtocolHandler, using the ActionHook * interface. * * @see ProtocolHandler * @see ActionHook * @author Remy Maucherat */ public enum ActionCode { ACK, CLOSE, COMMIT, /** * A flush() operation originated by the client ( i.e. a flush() on the * servlet output stream or writer, called by a servlet ). Argument is the * Response. */ CLIENT_FLUSH, RESET, /** * Hook called if swallowing request input should be disabled. * Example: Cancel a large file upload. * */ DISABLE_SWALLOW_INPUT, /** * Callback for lazy evaluation - extract the remote host address. */ REQ_HOST_ATTRIBUTE, /** * Callback for lazy evaluation - extract the remote host infos (address, * name, port) and local address. */ REQ_HOST_ADDR_ATTRIBUTE, /** * Callback for lazy evaluation - extract the SSL-related attributes. */ REQ_SSL_ATTRIBUTE, /** * Callback for lazy evaluation - extract the SSL-certificate (including * forcing a re-handshake if necessary) */ REQ_SSL_CERTIFICATE, /** * Callback for lazy evaluation - socket remote port. */ REQ_REMOTEPORT_ATTRIBUTE, /** * Callback for lazy evaluation - socket local port. */ REQ_LOCALPORT_ATTRIBUTE, /** * Callback for lazy evaluation - local address. */ REQ_LOCAL_ADDR_ATTRIBUTE, /** * Callback for lazy evaluation - local address. */ REQ_LOCAL_NAME_ATTRIBUTE, /** * Callback for setting FORM auth body replay */ REQ_SET_BODY_REPLAY, /** * Callback for begin Comet processing */ COMET_BEGIN, /** * Callback for end Comet processing */ COMET_END, /** * Callback for getting the amount of available bytes */ AVAILABLE, /** * Callback for an asynchronous close of the Comet event */ COMET_CLOSE, /** * Callback for setting the timeout asynchronously */ COMET_SETTIMEOUT, /** * Callback for an async request */ ASYNC_START, /** * Callback for an async call to * {@link javax.servlet.AsyncContext#dispatch()} */ ASYNC_DISPATCH, /** * Callback to indicate the the actual dispatch has started and that the * async state needs change. */ ASYNC_DISPATCHED, /** * Callback for an async call to * {@link javax.servlet.AsyncContext#start(Runnable)} */ ASYNC_RUN, /** * Callback for an async call to * {@link javax.servlet.AsyncContext#complete()} */ ASYNC_COMPLETE, /** * Callback to trigger the processing of an async timeout */ ASYNC_TIMEOUT, /** * Callback to trigger the error processing */ ASYNC_ERROR, /** * Callback for an async call to * {@link javax.servlet.AsyncContext#setTimeout(long)} */ ASYNC_SETTIMEOUT, /** * Callback to determine if async processing is in progress */ ASYNC_IS_ASYNC, /** * Callback to determine if async dispatch is in progress */ ASYNC_IS_STARTED, /** * Callback to determine if async dispatch is in progress */ ASYNC_IS_DISPATCHING, /** * Callback to determine if async is timing out */ ASYNC_IS_TIMINGOUT, /** * Callback to determine if async is in error */ ASYNC_IS_ERROR, /** * Callback to trigger the HTTP upgrade process. */ UPGRADE, /** * Indicator that Servlet is interested in being * notified when data is available to be read */ NB_READ_INTEREST, /** *Indicator that the Servlet is interested *in being notified when it can write data */ NB_WRITE_INTEREST, /** * Indicates if the request body has been fully read. */ REQUEST_BODY_FULLY_READ, /** * Indicates that the container needs to trigger a call to onDataAvailable() * for the registered non-blocking read listener. */ DISPATCH_READ, /** * Indicates that the container needs to trigger a call to onWritePossible() * for the registered non-blocking write listener. */ DISPATCH_WRITE, /** * Execute any non-blocking dispatches that have been registered via * {@link #DISPATCH_READ} or {@link #DISPATCH_WRITE}. Typically required * when the non-blocking listeners are configured on a thread where the * processing wasn't triggered by a read or write event on the socket. */ DISPATCH_EXECUTE }
55,772
Bug 55772 Flushing AsyncContext response writer after ClientAbortException (BrokenPipe) causes request state to leak
null
resolved fixed
cb62f86
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T13:39:52Z
2013-11-13T10:53:20Z
java/org/apache/coyote/ajp/AbstractAjpProcessor.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.ajp; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.nio.ByteBuffer; import java.security.NoSuchProviderException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.util.Iterator; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUpgradeHandler; import org.apache.coyote.AbstractProcessor; import org.apache.coyote.ActionCode; import org.apache.coyote.AsyncContextCallback; import org.apache.coyote.ByteBufferHolder; 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.juli.logging.Log; import org.apache.tomcat.util.ExceptionUtils; 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.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.DispatchType; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; /** * Base class for AJP Processor implementations. */ public abstract class AbstractAjpProcessor<S> extends AbstractProcessor<S> { protected abstract Log getLog(); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * End message array. */ protected static final byte[] endMessageArray; protected static final byte[] endAndCloseMessageArray; /** * Flush message array. */ protected static final byte[] flushMessageArray; /** * Pong message array. */ protected static final byte[] pongMessageArray; static { // Allocate the end message array AjpMessage endMessage = new AjpMessage(16); endMessage.reset(); endMessage.appendByte(Constants.JK_AJP13_END_RESPONSE); endMessage.appendByte(1); endMessage.end(); endMessageArray = new byte[endMessage.getLen()]; System.arraycopy(endMessage.getBuffer(), 0, endMessageArray, 0, endMessage.getLen()); // Allocate the end and close message array AjpMessage endAndCloseMessage = new AjpMessage(16); endAndCloseMessage.reset(); endAndCloseMessage.appendByte(Constants.JK_AJP13_END_RESPONSE); endAndCloseMessage.appendByte(0); endAndCloseMessage.end(); endAndCloseMessageArray = new byte[endAndCloseMessage.getLen()]; System.arraycopy(endAndCloseMessage.getBuffer(), 0, endAndCloseMessageArray, 0, endAndCloseMessage.getLen()); // Allocate the flush message array AjpMessage flushMessage = new AjpMessage(16); flushMessage.reset(); flushMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK); flushMessage.appendInt(0); flushMessage.appendByte(0); flushMessage.end(); flushMessageArray = new byte[flushMessage.getLen()]; System.arraycopy(flushMessage.getBuffer(), 0, flushMessageArray, 0, flushMessage.getLen()); // Allocate the pong message array AjpMessage pongMessage = new AjpMessage(16); pongMessage.reset(); pongMessage.appendByte(Constants.JK_AJP13_CPONG_REPLY); pongMessage.end(); pongMessageArray = new byte[pongMessage.getLen()]; System.arraycopy(pongMessage.getBuffer(), 0, pongMessageArray, 0, pongMessage.getLen()); } // ----------------------------------------------------- Instance Variables /** * GetBody message array. Not static like the other message arrays since the * message varies with packetSize and that can vary per connector. */ protected final byte[] getBodyMessageArray; /** * AJP packet size. */ private final int outputMaxChunkSize; /** * Header message. Note that this header is merely the one used during the * processing of the first message of a "request", so it might not be a * request header. It will stay unchanged during the processing of the whole * request. */ protected final AjpMessage requestHeaderMessage; /** * Message used for response composition. */ protected final AjpMessage responseMessage; /** * Location of next write of the response message (used withnon-blocking * writes when the message may not be written in a single write). Avalue of * -1 indicates that no message has been written to the buffer. */ private int responseMsgPos = -1; /** * Body message. */ protected final AjpMessage bodyMessage; /** * Body message. */ protected final MessageBytes bodyBytes = MessageBytes.newInstance(); /** * The max size of the buffered write buffer */ private int bufferedWriteSize = 64*1024; //64k default write buffer /** * For "non-blocking" writes use an external set of buffers. Although the * API only allows one non-blocking write at a time, due to buffering and * the possible need to write HTTP headers, there may be more than one write * to the OutputBuffer. */ private final LinkedBlockingDeque<ByteBufferHolder> bufferedWrites = new LinkedBlockingDeque<>(); /** * Error flag. */ protected boolean error = false; /** * Host name (used to avoid useless B2C conversion on the host name). */ protected char[] hostNameC = new char[0]; /** * Temp message bytes used for processing. */ protected final MessageBytes tmpMB = MessageBytes.newInstance(); /** * Byte chunk for certs. */ protected final MessageBytes certificates = MessageBytes.newInstance(); /** * End of stream flag. */ protected boolean endOfStream = false; /** * Request body empty flag. */ protected boolean empty = true; /** * First read. */ protected boolean first = true; /** * Is a body present for the current request? This is determined by the * presence of the content-length header with a non-zero value. */ private boolean bodyPresent = false; /** * Indicates that a 'get body chunk' message has been sent but the body * chunk has not yet been received. */ private boolean waitingForBodyMessage = false; /** * Replay read. */ protected boolean replay = false; /** * Should any response body be swallowed and not sent to the client. */ private boolean swallowResponse = false; /** * Finished response. */ protected boolean finished = false; /** * Bytes written to client for the current request. */ protected long bytesWritten = 0; // ------------------------------------------------------------ Constructor public AbstractAjpProcessor(int packetSize, AbstractEndpoint<S> endpoint) { super(endpoint); // Calculate maximum chunk size as packetSize may have been changed from // the default (Constants.MAX_PACKET_SIZE) this.outputMaxChunkSize = Constants.MAX_SEND_SIZE + packetSize - Constants.MAX_PACKET_SIZE; request.setInputBuffer(new SocketInputBuffer()); requestHeaderMessage = new AjpMessage(packetSize); responseMessage = new AjpMessage(packetSize); bodyMessage = new AjpMessage(packetSize); // Set the getBody message buffer AjpMessage getBodyMessage = new AjpMessage(16); getBodyMessage.reset(); getBodyMessage.appendByte(Constants.JK_AJP13_GET_BODY_CHUNK); // Adjust read size if packetSize != default (Constants.MAX_PACKET_SIZE) getBodyMessage.appendInt(Constants.MAX_READ_SIZE + packetSize - Constants.MAX_PACKET_SIZE); getBodyMessage.end(); getBodyMessageArray = new byte[getBodyMessage.getLen()]; System.arraycopy(getBodyMessage.getBuffer(), 0, getBodyMessageArray, 0, getBodyMessage.getLen()); } // ------------------------------------------------------------- Properties /** * The number of milliseconds Tomcat will wait for a subsequent request * before closing the connection. The default is -1 which is an infinite * timeout. */ protected int keepAliveTimeout = -1; public int getKeepAliveTimeout() { return keepAliveTimeout; } public void setKeepAliveTimeout(int timeout) { keepAliveTimeout = timeout; } /** * Use Tomcat authentication ? */ protected boolean tomcatAuthentication = true; public boolean getTomcatAuthentication() { return tomcatAuthentication; } public void setTomcatAuthentication(boolean tomcatAuthentication) { this.tomcatAuthentication = tomcatAuthentication; } /** * Required secret. */ protected String requiredSecret = null; public void setRequiredSecret(String requiredSecret) { this.requiredSecret = requiredSecret; } /** * When client certificate information is presented in a form other than * instances of {@link java.security.cert.X509Certificate} it needs to be * converted before it can be used and this property controls which JSSE * provider is used to perform the conversion. For example it is used with * the AJP connectors, the HTTP APR connector and with the * {@link org.apache.catalina.valves.SSLValve}. If not specified, the * default provider will be used. */ protected String clientCertProvider = null; public String getClientCertProvider() { return clientCertProvider; } public void setClientCertProvider(String s) { this.clientCertProvider = s; } // --------------------------------------------------------- Public Methods /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override public final void action(ActionCode actionCode, Object param) { if (actionCode == ActionCode.CLOSE) { // End the processing of the current request, and stop any further // transactions with the client try { finish(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.COMMIT) { if (response.isCommitted()) return; // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } try { flush(false); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.ACK) { // NO_OP for AJP } else if (actionCode == ActionCode.CLIENT_FLUSH) { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; return; } } 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.RESET) { // NO-OP } 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_SSL_CERTIFICATE) { // NO-OP. Can't force a new SSL handshake with the client when using // AJP as the reverse proxy controls that connection. } 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_HOST_ADDR_ATTRIBUTE) { // NO-OP // Automatically populated during prepareRequest() } else if (actionCode == ActionCode.REQ_LOCAL_NAME_ATTRIBUTE) { // NO-OP // Automatically populated during prepareRequest() } else if (actionCode == ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE) { // Copy from local name for now, which should simply be an address request.localAddr().setString(request.localName().toString()); } else if (actionCode == ActionCode.REQ_REMOTEPORT_ATTRIBUTE) { // NO-OP // This information is not available when using the AJP protocol } else if (actionCode == ActionCode.REQ_LOCALPORT_ATTRIBUTE) { // NO-OP // Automatically populated during prepareRequest() } 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; endOfStream = false; } else if (actionCode == ActionCode.ASYNC_START) { asyncStateMachine.asyncStart((AsyncContextCallback) param); } else if (actionCode == ActionCode.ASYNC_COMPLETE) { socketWrapper.clearDispatches(); if (asyncStateMachine.asyncComplete()) { endpoint.processSocket(socketWrapper, SocketStatus.OPEN_READ, true); } } else if (actionCode == ActionCode.ASYNC_DISPATCH) { if (asyncStateMachine.asyncDispatch()) { endpoint.processSocket(socketWrapper, SocketStatus.OPEN_READ, true); } } else if (actionCode == ActionCode.ASYNC_DISPATCHED) { asyncStateMachine.asyncDispatched(); } else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) { if (param == null) return; long timeout = ((Long)param).longValue(); socketWrapper.setTimeout(timeout); } else if (actionCode == ActionCode.ASYNC_TIMEOUT) { AtomicBoolean result = (AtomicBoolean) param; result.set(asyncStateMachine.asyncTimeout()); } else if (actionCode == ActionCode.ASYNC_RUN) { asyncStateMachine.asyncRun((Runnable) param); } else if (actionCode == ActionCode.ASYNC_ERROR) { asyncStateMachine.asyncError(); } else if (actionCode == ActionCode.ASYNC_IS_STARTED) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted()); } else if (actionCode == ActionCode.ASYNC_IS_DISPATCHING) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching()); } else if (actionCode == ActionCode.ASYNC_IS_ASYNC) { ((AtomicBoolean) param).set(asyncStateMachine.isAsync()); } else if (actionCode == ActionCode.ASYNC_IS_TIMINGOUT) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut()); } else if (actionCode == ActionCode.ASYNC_IS_ERROR) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError()); } else if (actionCode == ActionCode.UPGRADE) { // HTTP connections only. Unsupported for AJP. throw new UnsupportedOperationException( sm.getString("ajpprocessor.httpupgrade.notsupported")); } else if (actionCode == ActionCode.COMET_BEGIN) { // HTTP connections only. Unsupported for AJP. throw new UnsupportedOperationException( sm.getString("ajpprocessor.comet.notsupported")); } else if (actionCode == ActionCode.COMET_END) { // HTTP connections only. Unsupported for AJP. throw new UnsupportedOperationException( sm.getString("ajpprocessor.comet.notsupported")); } else if (actionCode == ActionCode.COMET_CLOSE) { // HTTP connections only. Unsupported for AJP. throw new UnsupportedOperationException( sm.getString("ajpprocessor.comet.notsupported")); } else if (actionCode == ActionCode.COMET_SETTIMEOUT) { // HTTP connections only. Unsupported for AJP. throw new UnsupportedOperationException( sm.getString("ajpprocessor.comet.notsupported")); } else if (actionCode == ActionCode.AVAILABLE) { if (available()) { request.setAvailable(1); } else { request.setAvailable(0); } } else if (actionCode == ActionCode.NB_READ_INTEREST) { if (!endOfStream) { registerForEvent(true, false); } } else if (actionCode == ActionCode.NB_WRITE_INTEREST) { AtomicBoolean isReady = (AtomicBoolean)param; boolean result = bufferedWrites.size() == 0 && responseMsgPos == -1; isReady.set(result); if (!result) { registerForEvent(false, true); } } else if (actionCode == ActionCode.REQUEST_BODY_FULLY_READ) { AtomicBoolean result = (AtomicBoolean) param; result.set(endOfStream); } else if (actionCode == ActionCode.DISPATCH_READ) { socketWrapper.addDispatch(DispatchType.NON_BLOCKING_READ); } else if (actionCode == ActionCode.DISPATCH_WRITE) { socketWrapper.addDispatch(DispatchType.NON_BLOCKING_WRITE); } } @Override public SocketState asyncDispatch(SocketStatus status) { if (status == SocketStatus.OPEN_WRITE) { try { asyncStateMachine.asyncOperation(); try { if (hasDataToWrite()) { flushBufferedData(); if (hasDataToWrite()) { // There is data to write but go via Response to // maintain a consistent view of non-blocking state response.checkRegisterForWrite(true); return SocketState.LONG; } } } catch (IOException x) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to write async data.",x); } status = SocketStatus.ASYNC_WRITE_ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, x); } } catch (IllegalStateException x) { registerForEvent(false, true); } } else if (status == SocketStatus.OPEN_READ && request.getReadListener() != null) { try { if (available()) { asyncStateMachine.asyncOperation(); } } catch (IllegalStateException x) { registerForEvent(true, false); } } RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !getAdapter().asyncDispatch(request, response, status); resetTimeouts(); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (isAsync()) { if (error) { request.updateCounters(); return SocketState.CLOSED; } else { return SocketState.LONG; } } else { request.updateCounters(); if (error) { return SocketState.CLOSED; } else { return SocketState.OPEN; } } } /** * Process pipelined HTTP requests using the specified input and output * streams. * * @throws IOException error during an I/O operation */ @Override public SocketState process(SocketWrapper<S> socket) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the socket this.socketWrapper = socket; setupSocket(socket); int soTimeout = endpoint.getSoTimeout(); boolean cping = false; // Error flag error = false; boolean keptAlive = false; while (!error && !endpoint.isPaused()) { // Parsing the request header try { // Get first message of the request if (!readMessage(requestHeaderMessage, !keptAlive)) { break; } // Set back timeout if keep alive timeout is enabled if (keepAliveTimeout > 0) { setTimeout(socketWrapper, soTimeout); } // Check message type, process right away and break if // not regular request processing int type = requestHeaderMessage.getByte(); if (type == Constants.JK_AJP13_CPING_REQUEST) { if (endpoint.isPaused()) { recycle(true); break; } cping = true; try { output(pongMessageArray, 0, pongMessageArray.length, true); } catch (IOException e) { error = true; } recycle(false); continue; } else if(type != Constants.JK_AJP13_FORWARD_REQUEST) { // Unexpected packet type. Unread body packets should have // been swallowed in finish(). if (getLog().isDebugEnabled()) { getLog().debug("Unexpected message: " + type); } error = true; break; } keptAlive = true; request.setStartTime(System.currentTimeMillis()); } catch (IOException e) { error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().debug(sm.getString("ajpprocessor.header.error"), t); // 400 - Bad Request response.setStatus(400); getAdapter().log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().debug(sm.getString("ajpprocessor.request.prepare"), t); // 400 - Internal Server Error response.setStatus(400); getAdapter().log(request, response, 0); error = true; } } if (!error && !cping && endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); getAdapter().log(request, response, 0); error = true; } cping = false; // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); getAdapter().service(request, response); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("ajpprocessor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); error = true; } } if (isAsync() && !error) { break; } // Finish the response if not done yet if (!finished) { try { finish(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); error = true; } } // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); // Set keep alive timeout if enabled if (keepAliveTimeout > 0) { setTimeout(socketWrapper, keepAliveTimeout); } recycle(false); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (!error && !endpoint.isPaused()) { if (isAsync()) { return SocketState.LONG; } else { return SocketState.OPEN; } } else { return SocketState.CLOSED; } } @Override public void setSslSupport(SSLSupport sslSupport) { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("ajpprocessor.ssl.notsupported")); } @Override public SocketState event(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.comet.notsupported")); } @Override public SocketState upgradeDispatch(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IOException( sm.getString("ajpprocessor.httpupgrade.notsupported")); } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("ajpprocessor.httpupgrade.notsupported")); } /** * Recycle the processor, ready for the next request which may be on the * same connection or a different connection. * * @param socketClosing Indicates if the socket is about to be closed * allowing the processor to perform any additional * clean-up that may be required */ @Override public void recycle(boolean socketClosing) { asyncStateMachine.recycle(); // Recycle Request object first = true; endOfStream = false; bodyPresent = false; waitingForBodyMessage = false; empty = true; replay = false; finished = false; request.recycle(); response.recycle(); certificates.recycle(); swallowResponse = false; bytesWritten = 0; } // ------------------------------------------------------ Protected Methods // Methods called by asyncDispatch /** * Provides a mechanism for those connector implementations (currently only * NIO) that need to reset timeouts from Async timeouts to standard HTTP * timeouts once async processing completes. */ protected abstract void resetTimeouts(); // Methods called by prepareResponse() protected abstract int output(byte[] src, int offset, int length, boolean block) throws IOException; // Methods called by process() protected abstract void setupSocket(SocketWrapper<S> socketWrapper) throws IOException; protected abstract void setTimeout(SocketWrapper<S> socketWrapper, int timeout) throws IOException; // Methods used by readMessage /** * Read at least the specified amount of bytes, and place them * in the input buffer. Note that if any data is available to read then this * method will always block until at least the specified number of bytes * have been read. * * @param buf Buffer to read data into * @param pos Start position * @param n The minimum number of bytes to read * @param block If there is no data available to read when this method is * called, should this call block until data becomes available? * @return <code>true</code> if the requested number of bytes were read * else <code>false</code> * @throws IOException */ protected abstract boolean read(byte[] buf, int pos, int n, boolean block) throws IOException; // Methods used by SocketInputBuffer /** * Read an AJP body message. Used to read both the 'special' packet in ajp13 * and to receive the data after we send a GET_BODY packet. * * @param block If there is no data available to read when this method is * called, should this call block until data becomes available? * * @return <code>true</code> if at least one body byte was read, otherwise * <code>false</code> */ protected boolean receive(boolean block) throws IOException { bodyMessage.reset(); if (!readMessage(bodyMessage, block)) { return false; } waitingForBodyMessage = false; first = false; // No data received. if (bodyMessage.getLen() == 0) { // just the header // Don't mark 'end of stream' for the first chunk. return false; } int blen = bodyMessage.peekInt(); if (blen == 0) { return false; } bodyMessage.getBodyBytes(bodyBytes); empty = false; return true; } /** * Read an AJP message. * * @param message The message to populate * @param block If there is no data available to read when this method is * called, should this call block until data becomes available? * @return true if the message has been read, false if no data was read * * @throws IOException any other failure, including incomplete reads */ protected boolean readMessage(AjpMessage message, boolean block) throws IOException { byte[] buf = message.getBuffer(); int headerLength = message.getHeaderLength(); if (!read(buf, 0, headerLength, block)) { return false; } int messageLength = message.processHeader(true); if (messageLength < 0) { // Invalid AJP header signature throw new IOException(sm.getString("ajpmessage.invalidLength", Integer.valueOf(messageLength))); } else if (messageLength == 0) { // Zero length message. return true; } else { if (messageLength > message.getBuffer().length) { // Message too long for the buffer // Need to trigger a 400 response throw new IllegalArgumentException(sm.getString( "ajpprocessor.header.tooLong", Integer.valueOf(messageLength), Integer.valueOf(buf.length))); } read(buf, headerLength, messageLength, true); return true; } } @Override public final boolean isComet() { // AJP does not support Comet return false; } @Override public final boolean isUpgrade() { // AJP does not support HTTP upgrade return false; } /** * Get more request body data from the web server and store it in the * internal buffer. * * @return true if there is more data, false if not. */ protected boolean refillReadBuffer(boolean block) throws IOException { // If the server returns an empty packet, assume that that end of // the stream has been reached (yuck -- fix protocol??). // FORM support if (replay) { endOfStream = true; // we've read everything there is } if (endOfStream) { return false; } // Request more data immediately if (!first && !waitingForBodyMessage) { output(getBodyMessageArray, 0, getBodyMessageArray.length, true); waitingForBodyMessage = true; } boolean moreData = receive(block); if (!moreData && ((first && !bodyPresent) || (!first && !waitingForBodyMessage))) { endOfStream = true; } return moreData; } /** * After reading the request headers, we have to setup the request filters. */ protected void prepareRequest() { // Translate the HTTP method code to a String. byte methodCode = requestHeaderMessage.getByte(); if (methodCode != Constants.SC_M_JK_STORED) { String methodName = Constants.getMethodForCode(methodCode - 1); request.method().setString(methodName); } requestHeaderMessage.getBytes(request.protocol()); requestHeaderMessage.getBytes(request.requestURI()); requestHeaderMessage.getBytes(request.remoteAddr()); requestHeaderMessage.getBytes(request.remoteHost()); requestHeaderMessage.getBytes(request.localName()); request.setLocalPort(requestHeaderMessage.getInt()); boolean isSSL = requestHeaderMessage.getByte() != 0; if (isSSL) { request.scheme().setString("https"); } // Decode headers MimeHeaders headers = request.getMimeHeaders(); // Set this every time in case limit has been changed via JMX headers.setLimit(endpoint.getMaxHeaderCount()); boolean contentLengthSet = false; int hCount = requestHeaderMessage.getInt(); for(int i = 0 ; i < hCount ; i++) { String hName = null; // Header names are encoded as either an integer code starting // with 0xA0, or as a normal string (in which case the first // two bytes are the length). int isc = requestHeaderMessage.peekInt(); int hId = isc & 0xFF; MessageBytes vMB = null; isc &= 0xFF00; if(0xA000 == isc) { requestHeaderMessage.getInt(); // To advance the read position hName = Constants.getHeaderForCode(hId - 1); vMB = headers.addValue(hName); } else { // reset hId -- if the header currently being read // happens to be 7 or 8 bytes long, the code below // will think it's the content-type header or the // content-length header - SC_REQ_CONTENT_TYPE=7, // SC_REQ_CONTENT_LENGTH=8 - leading to unexpected // behaviour. see bug 5861 for more information. hId = -1; requestHeaderMessage.getBytes(tmpMB); ByteChunk bc = tmpMB.getByteChunk(); vMB = headers.addValue(bc.getBuffer(), bc.getStart(), bc.getLength()); } requestHeaderMessage.getBytes(vMB); if (hId == Constants.SC_REQ_CONTENT_LENGTH || (hId == -1 && tmpMB.equalsIgnoreCase("Content-Length"))) { long cl = vMB.getLong(); if (contentLengthSet) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); error = true; } else { contentLengthSet = true; // Set the content-length header for the request request.setContentLength(cl); } if (cl != 0) { bodyPresent = true; } } else if (hId == Constants.SC_REQ_CONTENT_TYPE || (hId == -1 && tmpMB.equalsIgnoreCase("Content-Type"))) { // just read the content-type header, so set it ByteChunk bchunk = vMB.getByteChunk(); request.contentType().setBytes(bchunk.getBytes(), bchunk.getOffset(), bchunk.getLength()); } } // Decode extra attributes boolean secret = false; byte attributeCode; while ((attributeCode = requestHeaderMessage.getByte()) != Constants.SC_A_ARE_DONE) { switch (attributeCode) { case Constants.SC_A_REQ_ATTRIBUTE : requestHeaderMessage.getBytes(tmpMB); String n = tmpMB.toString(); requestHeaderMessage.getBytes(tmpMB); String v = tmpMB.toString(); /* * AJP13 misses to forward the remotePort. * Allow the AJP connector to add this info via * a private request attribute. * We will accept the forwarded data as the remote port, * and remove it from the public list of request attributes. */ if(n.equals(Constants.SC_A_REQ_REMOTE_PORT)) { try { request.setRemotePort(Integer.parseInt(v)); } catch (NumberFormatException nfe) { // Ignore invalid value } } else { request.setAttribute(n, v ); } break; case Constants.SC_A_CONTEXT : requestHeaderMessage.getBytes(tmpMB); // nothing break; case Constants.SC_A_SERVLET_PATH : requestHeaderMessage.getBytes(tmpMB); // nothing break; case Constants.SC_A_REMOTE_USER : if (tomcatAuthentication) { // ignore server requestHeaderMessage.getBytes(tmpMB); } else { requestHeaderMessage.getBytes(request.getRemoteUser()); } break; case Constants.SC_A_AUTH_TYPE : if (tomcatAuthentication) { // ignore server requestHeaderMessage.getBytes(tmpMB); } else { requestHeaderMessage.getBytes(request.getAuthType()); } break; case Constants.SC_A_QUERY_STRING : requestHeaderMessage.getBytes(request.queryString()); break; case Constants.SC_A_JVM_ROUTE : requestHeaderMessage.getBytes(request.instanceId()); break; case Constants.SC_A_SSL_CERT : // SSL certificate extraction is lazy, moved to JkCoyoteHandler requestHeaderMessage.getBytes(certificates); break; case Constants.SC_A_SSL_CIPHER : requestHeaderMessage.getBytes(tmpMB); request.setAttribute(SSLSupport.CIPHER_SUITE_KEY, tmpMB.toString()); break; case Constants.SC_A_SSL_SESSION : requestHeaderMessage.getBytes(tmpMB); request.setAttribute(SSLSupport.SESSION_ID_KEY, tmpMB.toString()); break; case Constants.SC_A_SSL_KEY_SIZE : request.setAttribute(SSLSupport.KEY_SIZE_KEY, Integer.valueOf(requestHeaderMessage.getInt())); break; case Constants.SC_A_STORED_METHOD: requestHeaderMessage.getBytes(request.method()); break; case Constants.SC_A_SECRET: requestHeaderMessage.getBytes(tmpMB); if (requiredSecret != null) { secret = true; if (!tmpMB.equals(requiredSecret)) { response.setStatus(403); error = true; } } break; default: // Ignore unknown attribute for backward compatibility break; } } // Check if secret was submitted if required if ((requiredSecret != null) && !secret) { response.setStatus(403); error = true; } // Check for a full URI (including protocol://host:port/) ByteChunk uriBC = request.requestURI().getByteChunk(); if (uriBC.startsWithIgnoreCase("http", 0)) { int pos = uriBC.indexOf("://", 0, 3, 4); int uriBCStart = uriBC.getStart(); int slashPos = -1; if (pos != -1) { byte[] uriB = uriBC.getBytes(); slashPos = uriBC.indexOf('/', pos + 3); if (slashPos == -1) { slashPos = uriBC.getLength(); // Set URI as "/" request.requestURI().setBytes (uriB, uriBCStart + pos + 1, 1); } else { request.requestURI().setBytes (uriB, uriBCStart + slashPos, uriBC.getLength() - slashPos); } MessageBytes hostMB = headers.setValue("host"); hostMB.setBytes(uriB, uriBCStart + pos + 3, slashPos - pos - 3); } } MessageBytes valueMB = request.getMimeHeaders().getValue("host"); parseHost(valueMB); if (error) { getAdapter().log(request, response, 0); } } /** * Parse host. */ protected void parseHost(MessageBytes valueMB) { if (valueMB == null || valueMB.isNull()) { // HTTP/1.0 request.setServerPort(request.getLocalPort()); try { request.serverName().duplicate(request.localName()); } catch (IOException e) { response.setStatus(400); error = true; } return; } ByteChunk valueBC = valueMB.getByteChunk(); byte[] valueB = valueBC.getBytes(); int valueL = valueBC.getLength(); int valueS = valueBC.getStart(); int colonPos = -1; if (hostNameC.length < valueL) { hostNameC = new char[valueL]; } boolean ipv6 = (valueB[valueS] == '['); boolean bracketClosed = false; for (int i = 0; i < valueL; i++) { char b = (char) valueB[i + valueS]; hostNameC[i] = b; if (b == ']') { bracketClosed = true; } else if (b == ':') { if (!ipv6 || bracketClosed) { colonPos = i; break; } } } if (colonPos < 0) { if (request.scheme().equalsIgnoreCase("https")) { // 443 - Default HTTPS port request.setServerPort(443); } else { // 80 - Default HTTTP port request.setServerPort(80); } request.serverName().setChars(hostNameC, 0, valueL); } else { request.serverName().setChars(hostNameC, 0, colonPos); int port = 0; int mult = 1; for (int i = valueL - 1; i > colonPos; i--) { int charValue = HexUtils.getDec(valueB[i + valueS]); if (charValue == -1) { // Invalid character error = true; // 400 - Bad request response.setStatus(400); break; } port = port + (charValue * mult); mult = 10 * mult; } request.setServerPort(port); } } /** * When committing the response, we have to validate the set of headers, as * well as setup the response filters. */ protected void prepareResponse() throws IOException { response.setCommitted(true); responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_HEADERS); // Responses with certain status codes are not permitted to include a // response body. int statusCode = response.getStatus(); if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304) { // No entity body swallowResponse = true; } // Responses to HEAD requests are not permitted to include a response // body. MessageBytes methodMB = request.method(); if (methodMB.equals("HEAD")) { // No entity body swallowResponse = true; } // HTTP header contents responseMessage.appendInt(statusCode); 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.getInstance( response.getLocale()).getMessage(response.getStatus()); } if (message == null) { // mod_jk + httpd 2.x fails with a null status message - bug 45026 message = Integer.toString(response.getStatus()); } tmpMB.setString(message); responseMessage.appendBytes(tmpMB); // 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); } // Other headers int numHeaders = headers.size(); responseMessage.appendInt(numHeaders); for (int i = 0; i < numHeaders; i++) { MessageBytes hN = headers.getName(i); int hC = Constants.getResponseAjpIndex(hN.toString()); if (hC > 0) { responseMessage.appendInt(hC); } else { responseMessage.appendBytes(hN); } MessageBytes hV=headers.getValue(i); responseMessage.appendBytes(hV); } // Write to buffer responseMessage.end(); output(responseMessage.getBuffer(), 0, responseMessage.getLen(), true); } /** * Callback to write data from the buffer. */ protected void flush(boolean explicit) throws IOException { // Calling code should ensure that there is no data in the buffers for // non-blocking writes. // TODO Validate the assertion above if (explicit && !finished) { // Send the flush message output(flushMessageArray, 0, flushMessageArray.length, true); } } /** * Finish AJP response. */ protected void finish() throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } if (finished) return; finished = true; // Swallow the unread body packet if present if (first && request.getContentLengthLong() > 0 || waitingForBodyMessage) { receive(true); } // Add the end message if (error) { output(endAndCloseMessageArray, 0, endAndCloseMessageArray.length, true); } else { output(endMessageArray, 0, endMessageArray.length, true); } } private boolean available() { if (endOfStream) { return false; } if (empty) { try { refillReadBuffer(false); } catch (IOException e) { // Not ideal. This will indicate that data is available // which should trigger a read which in turn will trigger // another IOException and that one can be thrown. return true; } } return !empty; } private void writeData(ByteChunk chunk) throws IOException { // Prevent timeout socketWrapper.access(); boolean blocking = (response.getWriteListener() == null); if (!blocking) { flushBufferedData(); } int len = chunk.getLength(); int off = 0; // Write this chunk while (responseMsgPos == -1 && len > 0) { int thisTime = len; if (thisTime > outputMaxChunkSize) { thisTime = outputMaxChunkSize; } responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK); responseMessage.appendBytes(chunk.getBytes(), chunk.getOffset() + off, thisTime); responseMessage.end(); writeResponseMessage(blocking); len -= thisTime; off += thisTime; } bytesWritten += off; if (len > 0) { // Add this chunk to the buffer addToBuffers(chunk.getBuffer(), off, len); } } private void addToBuffers(byte[] buf, int offset, int length) { ByteBufferHolder holder = bufferedWrites.peekLast(); if (holder == null || holder.isFlipped() || holder.getBuf().remaining() < length) { ByteBuffer buffer = ByteBuffer.allocate(Math.max(bufferedWriteSize,length)); holder = new ByteBufferHolder(buffer, false); bufferedWrites.add(holder); } holder.getBuf().put(buf, offset, length); } private boolean hasDataToWrite() { return responseMsgPos != -1 || bufferedWrites.size() > 0; } private void flushBufferedData() throws IOException { if (responseMsgPos > -1) { // Must be using non-blocking IO // Partially written response message. Try and complete it. writeResponseMessage(false); } while (responseMsgPos == -1 && bufferedWrites.size() > 0) { // Try and write any remaining buffer data Iterator<ByteBufferHolder> holders = bufferedWrites.iterator(); ByteBufferHolder holder = holders.next(); holder.flip(); ByteBuffer buffer = holder.getBuf(); int initialBufferSize = buffer.remaining(); while (responseMsgPos == -1 && buffer.remaining() > 0) { transferToResponseMsg(buffer); writeResponseMessage(false); } bytesWritten += (initialBufferSize - buffer.remaining()); if (buffer.remaining() == 0) { holders.remove(); } } } private void transferToResponseMsg(ByteBuffer buffer) { int thisTime = buffer.remaining(); if (thisTime > outputMaxChunkSize) { thisTime = outputMaxChunkSize; } responseMessage.reset(); responseMessage.appendByte(Constants.JK_AJP13_SEND_BODY_CHUNK); buffer.get(responseMessage.getBuffer(), responseMessage.pos, thisTime); responseMessage.end(); } private void writeResponseMessage(boolean block) throws IOException { int len = responseMessage.getLen(); int written = 1; if (responseMsgPos == -1) { // New message. Advance the write position to the beginning responseMsgPos = 0; } while (written > 0 && responseMsgPos < len) { written = output( responseMessage.getBuffer(), responseMsgPos, len, block); responseMsgPos += written; } if (responseMsgPos == len) { responseMsgPos = -1; } } // ------------------------------------- InputStreamInputBuffer Inner Class /** * This class is an input buffer which will read its data from an input * stream. */ protected class SocketInputBuffer implements InputBuffer { /** * Read bytes into the specified chunk. */ @Override public int doRead(ByteChunk chunk, Request req) throws IOException { if (endOfStream) { return -1; } if (first && req.getContentLengthLong() > 0) { // Handle special first-body-chunk if (!receive(true)) { return 0; } } else if (empty) { if (!refillReadBuffer(true)) { return -1; } } ByteChunk bc = bodyBytes.getByteChunk(); chunk.setBytes(bc.getBuffer(), bc.getStart(), bc.getLength()); empty = true; return chunk.getLength(); } } // ----------------------------------- OutputStreamOutputBuffer Inner Class /** * This class is an output buffer which will write data to an output * stream. */ protected class SocketOutputBuffer implements OutputBuffer { /** * Write chunk. */ @Override public int doWrite(ByteChunk chunk, Response res) throws IOException { if (!response.isCommitted()) { // Validate and write response headers try { prepareResponse(); } catch (IOException e) { // Set error flag error = true; } } if (!swallowResponse) { writeData(chunk); } return chunk.getLength(); } @Override public long getBytesWritten() { return bytesWritten; } } }
55,772
Bug 55772 Flushing AsyncContext response writer after ClientAbortException (BrokenPipe) causes request state to leak
null
resolved fixed
cb62f86
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T13:39:52Z
2013-11-13T10:53:20Z
java/org/apache/coyote/http11/AbstractHttp11Processor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.IOException; import java.io.InterruptedIOException; import java.util.Locale; import java.util.StringTokenizer; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import javax.servlet.RequestDispatcher; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUpgradeHandler; import org.apache.coyote.AbstractProcessor; import org.apache.coyote.ActionCode; import org.apache.coyote.AsyncContextCallback; import org.apache.coyote.RequestInfo; import org.apache.coyote.http11.filters.BufferedInputFilter; import org.apache.coyote.http11.filters.ChunkedInputFilter; import org.apache.coyote.http11.filters.ChunkedOutputFilter; import org.apache.coyote.http11.filters.GzipOutputFilter; import org.apache.coyote.http11.filters.IdentityInputFilter; import org.apache.coyote.http11.filters.IdentityOutputFilter; import org.apache.coyote.http11.filters.SavedRequestInputFilter; import org.apache.coyote.http11.filters.VoidInputFilter; import org.apache.coyote.http11.filters.VoidOutputFilter; import org.apache.juli.logging.Log; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.Ascii; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.HexUtils; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.log.UserDataHelper; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.DispatchType; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractHttp11Processor<S> extends AbstractProcessor<S> { protected abstract Log getLog(); private final UserDataHelper userDataHelper; /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Input. */ protected AbstractInputBuffer<S> inputBuffer ; /** * Output. */ protected AbstractOutputBuffer<S> outputBuffer; /* * Tracks how many internal filters are in the filter library so they * are skipped when looking for pluggable filters. */ private int pluggableFilterIndex = Integer.MAX_VALUE; /** * Error flag. */ protected boolean error = false; /** * Keep-alive. */ protected boolean keepAlive = true; /** * Flag used to indicate that the socket should be kept open (e.g. for keep * alive or send file. */ protected boolean openSocket = false; /** * Flag used to indicate that the socket should treat the next request * processed like a keep-alive connection - i.e. one where there may not be * any data to process. The initial value of this flag on entering the * process method is different for connectors that use polling (NIO / APR - * data is always expected) compared to those that use blocking (BIO - data * is only expected if the connection isn't in the keep-alive state). */ protected boolean keptAlive; /** * Flag that indicates that send file processing is in progress and that the * socket should not be returned to the poller (where a poller is used). */ protected boolean sendfileInProgress = false; /** * Flag that indicates if the request headers have been completely read. */ protected boolean readComplete = true; /** * HTTP/1.1 flag. */ protected boolean http11 = true; /** * HTTP/0.9 flag. */ protected boolean http09 = false; /** * Content delimiter for the request (if false, the connection will * be closed at the end of the request). */ protected boolean contentDelimitation = true; /** * Is there an expectation ? */ protected boolean expectation = false; /** * Comet used. */ protected boolean comet = false; /** * Regular expression that defines the restricted user agents. */ protected Pattern restrictedUserAgents = null; /** * Maximum number of Keep-Alive requests to honor. */ protected int maxKeepAliveRequests = -1; /** * The number of seconds Tomcat will wait for a subsequent request * before closing the connection. */ protected int keepAliveTimeout = -1; /** * Maximum timeout on uploads. 5 minutes as in Apache HTTPD server. */ protected int connectionUploadTimeout = 300000; /** * Flag to disable setting a different time-out on uploads. */ protected boolean disableUploadTimeout = false; /** * Allowed compression level. */ protected int compressionLevel = 0; /** * Minimum content size to make compression. */ protected int compressionMinSize = 2048; /** * Max saved post size. */ protected int maxSavePostSize = 4 * 1024; /** * Regular expression that defines the user agents to not use gzip with */ protected Pattern noCompressionUserAgents = null; /** * List of MIMES which could be gzipped */ protected String[] compressableMimeTypes = { "text/html", "text/xml", "text/plain" }; /** * Host name (used to avoid useless B2C conversion on the host name). */ protected char[] hostNameC = new char[0]; /** * Allow a customized the server header for the tin-foil hat folks. */ protected String server = null; /** * Instance of the new protocol to use after the HTTP connection has been * upgraded. */ protected HttpUpgradeHandler httpUpgradeHandler = null; public AbstractHttp11Processor(AbstractEndpoint<S> endpoint) { super(endpoint); userDataHelper = new UserDataHelper(getLog()); } /** * Set compression level. */ public void setCompression(String compression) { if (compression.equals("on")) { this.compressionLevel = 1; } else if (compression.equals("force")) { this.compressionLevel = 2; } else if (compression.equals("off")) { this.compressionLevel = 0; } else { try { // Try to parse compression as an int, which would give the // minimum compression size compressionMinSize = Integer.parseInt(compression); this.compressionLevel = 1; } catch (Exception e) { this.compressionLevel = 0; } } } /** * Set Minimum size to trigger compression. */ public void setCompressionMinSize(int compressionMinSize) { this.compressionMinSize = compressionMinSize; } /** * Set no compression user agent pattern. Regular expression as supported * by {@link Pattern}. * * ie: "gorilla|desesplorer|tigrus" */ public void setNoCompressionUserAgents(String noCompressionUserAgents) { if (noCompressionUserAgents == null || noCompressionUserAgents.length() == 0) { this.noCompressionUserAgents = null; } else { this.noCompressionUserAgents = Pattern.compile(noCompressionUserAgents); } } /** * Add a mime-type which will be compressible * The mime-type String will be exactly matched * in the response mime-type header . * * @param mimeType mime-type string */ public void addCompressableMimeType(String mimeType) { compressableMimeTypes = addStringArray(compressableMimeTypes, mimeType); } /** * Set compressible mime-type list (this method is best when used with * a large number of connectors, where it would be better to have all of * them referenced a single array). */ public void setCompressableMimeTypes(String[] compressableMimeTypes) { this.compressableMimeTypes = compressableMimeTypes; } /** * Set compressable mime-type list * List contains users agents separated by ',' : * * ie: "text/html,text/xml,text/plain" */ public void setCompressableMimeTypes(String compressableMimeTypes) { if (compressableMimeTypes != null) { this.compressableMimeTypes = null; StringTokenizer st = new StringTokenizer(compressableMimeTypes, ","); while (st.hasMoreTokens()) { addCompressableMimeType(st.nextToken().trim()); } } } /** * Return compression level. */ public String getCompression() { switch (compressionLevel) { case 0: return "off"; case 1: return "on"; case 2: return "force"; } return "off"; } /** * General use method * * @param sArray the StringArray * @param value string */ private String[] addStringArray(String sArray[], String value) { String[] result = null; if (sArray == null) { result = new String[1]; result[0] = value; } else { result = new String[sArray.length + 1]; for (int i = 0; i < sArray.length; i++) { result[i] = sArray[i]; } result[sArray.length] = value; } return result; } /** * Checks if any entry in the string array starts with the specified value * * @param sArray the StringArray * @param value string */ private boolean startsWithStringArray(String sArray[], String value) { if (value == null) { return false; } for (int i = 0; i < sArray.length; i++) { if (value.startsWith(sArray[i])) { return true; } } return false; } /** * Set restricted user agent list (which will downgrade the connector * to HTTP/1.0 mode). Regular expression as supported by {@link Pattern}. * * ie: "gorilla|desesplorer|tigrus" */ public void setRestrictedUserAgents(String restrictedUserAgents) { if (restrictedUserAgents == null || restrictedUserAgents.length() == 0) { this.restrictedUserAgents = null; } else { this.restrictedUserAgents = Pattern.compile(restrictedUserAgents); } } /** * Set the maximum number of Keep-Alive requests to honor. * This is to safeguard from DoS attacks. Setting to a negative * value disables the check. */ public void setMaxKeepAliveRequests(int mkar) { maxKeepAliveRequests = mkar; } /** * Return the number of Keep-Alive requests that we will honor. */ public int getMaxKeepAliveRequests() { return maxKeepAliveRequests; } /** * Set the Keep-Alive timeout. */ public void setKeepAliveTimeout(int timeout) { keepAliveTimeout = timeout; } /** * Return the number Keep-Alive timeout. */ public int getKeepAliveTimeout() { return keepAliveTimeout; } /** * Set the maximum size of a POST which will be buffered in SSL mode. */ public void setMaxSavePostSize(int msps) { maxSavePostSize = msps; } /** * Return the maximum size of a POST which will be buffered in SSL mode. */ public int getMaxSavePostSize() { return maxSavePostSize; } /** * Set the flag to control upload time-outs. */ public void setDisableUploadTimeout(boolean isDisabled) { disableUploadTimeout = isDisabled; } /** * Get the flag that controls upload time-outs. */ public boolean getDisableUploadTimeout() { return disableUploadTimeout; } /** * Set the socket buffer flag. */ public void setSocketBuffer(int socketBuffer) { outputBuffer.setSocketBuffer(socketBuffer); } /** * Get the socket buffer flag. */ public int getSocketBuffer() { return outputBuffer.getSocketBuffer(); } /** * Set the upload timeout. */ public void setConnectionUploadTimeout(int timeout) { connectionUploadTimeout = timeout ; } /** * Get the upload timeout. */ public int getConnectionUploadTimeout() { return connectionUploadTimeout; } /** * Set the server header name. */ public void setServer( String server ) { if (server==null || server.equals("")) { this.server = null; } else { this.server = server; } } /** * Get the server header name. */ public String getServer() { return server; } /** * Check if the resource could be compressed, if the client supports it. */ private boolean isCompressable() { // Check if content is not already gzipped MessageBytes contentEncodingMB = response.getMimeHeaders().getValue("Content-Encoding"); if ((contentEncodingMB != null) && (contentEncodingMB.indexOf("gzip") != -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check if sufficient length to trigger the compression long contentLength = response.getContentLengthLong(); if ((contentLength == -1) || (contentLength > compressionMinSize)) { // Check for compatible MIME-TYPE if (compressableMimeTypes != null) { return (startsWithStringArray(compressableMimeTypes, response.getContentType())); } } return false; } /** * Check if compression should be used for this resource. Already checked * that the resource could be compressed if the client supports it. */ private boolean useCompression() { // Check if browser support gzip encoding MessageBytes acceptEncodingMB = request.getMimeHeaders().getValue("accept-encoding"); if ((acceptEncodingMB == null) || (acceptEncodingMB.indexOf("gzip") == -1)) { return false; } // If force mode, always compress (test purposes only) if (compressionLevel == 2) { return true; } // Check for incompatible Browser if (noCompressionUserAgents != null) { MessageBytes userAgentValueMB = request.getMimeHeaders().getValue("user-agent"); if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (noCompressionUserAgents != null && noCompressionUserAgents.matcher(userAgentValue).matches()) { return false; } } } return true; } /** * Specialized utility method: find a sequence of lower case bytes inside * a ByteChunk. */ protected int findBytes(ByteChunk bc, byte[] b) { byte first = b[0]; byte[] buff = bc.getBuffer(); int start = bc.getStart(); int end = bc.getEnd(); // Look for first char int srcEnd = b.length; for (int i = start; i <= (end - srcEnd); i++) { if (Ascii.toLower(buff[i]) != first) { continue; } // found first char, now look for a match int myPos = i+1; for (int srcPos = 1; srcPos < srcEnd;) { if (Ascii.toLower(buff[myPos++]) != b[srcPos++]) { break; } if (srcPos == srcEnd) { return i - start; // found it } } } return -1; } /** * Determine if we must drop the connection because of the HTTP status * code. Use the same list of codes as Apache/httpd. */ protected boolean statusDropsConnection(int status) { return status == 400 /* SC_BAD_REQUEST */ || status == 408 /* SC_REQUEST_TIMEOUT */ || status == 411 /* SC_LENGTH_REQUIRED */ || status == 413 /* SC_REQUEST_ENTITY_TOO_LARGE */ || status == 414 /* SC_REQUEST_URI_TOO_LONG */ || status == 500 /* SC_INTERNAL_SERVER_ERROR */ || status == 503 /* SC_SERVICE_UNAVAILABLE */ || status == 501 /* SC_NOT_IMPLEMENTED */; } /** * Exposes input buffer to super class to allow better code re-use. * @return The input buffer used by the processor. */ protected abstract AbstractInputBuffer<S> getInputBuffer(); /** * Exposes output buffer to super class to allow better code re-use. * @return The output buffer used by the processor. */ protected abstract AbstractOutputBuffer<S> getOutputBuffer(); /** * Initialize standard input and output filters. */ protected void initializeFilters(int maxTrailerSize, int maxExtensionSize) { // Create and add the identity filters. getInputBuffer().addFilter(new IdentityInputFilter()); getOutputBuffer().addFilter(new IdentityOutputFilter()); // Create and add the chunked filters. getInputBuffer().addFilter( new ChunkedInputFilter(maxTrailerSize, maxExtensionSize)); getOutputBuffer().addFilter(new ChunkedOutputFilter()); // Create and add the void filters. getInputBuffer().addFilter(new VoidInputFilter()); getOutputBuffer().addFilter(new VoidOutputFilter()); // Create and add buffered input filter getInputBuffer().addFilter(new BufferedInputFilter()); // Create and add the chunked filters. //getInputBuffer().addFilter(new GzipInputFilter()); getOutputBuffer().addFilter(new GzipOutputFilter()); pluggableFilterIndex = getInputBuffer().getFilters().length; } /** * Add an input filter to the current request. * * @return false if the encoding was not found (which would mean it is * unsupported) */ protected boolean addInputFilter(InputFilter[] inputFilters, String encodingName) { if (encodingName.equals("identity")) { // Skip } else if (encodingName.equals("chunked")) { getInputBuffer().addActiveFilter (inputFilters[Constants.CHUNKED_FILTER]); contentDelimitation = true; } else { for (int i = pluggableFilterIndex; i < inputFilters.length; i++) { if (inputFilters[i].getEncodingName() .toString().equals(encodingName)) { getInputBuffer().addActiveFilter(inputFilters[i]); return true; } } return false; } return true; } /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override public final void action(ActionCode actionCode, Object param) { if (actionCode == ActionCode.CLOSE) { // End the processing of the current request try { getOutputBuffer().endRequest(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.COMMIT) { // Commit current response if (response.isCommitted()) { return; } // Validate and write response headers try { prepareResponse(); getOutputBuffer().commit(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.ACK) { // Acknowledge request // Send a 100 status back if it makes sense (response not committed // yet, and client specified an expectation for 100-continue) if ((response.isCommitted()) || !expectation) { return; } getInputBuffer().setSwallowInput(true); try { getOutputBuffer().sendAck(); } catch (IOException e) { // Set error flag error = true; } } else if (actionCode == ActionCode.CLIENT_FLUSH) { try { getOutputBuffer().flush(); } catch (IOException e) { // Set error flag error = true; response.setErrorException(e); } } else if (actionCode == ActionCode.DISABLE_SWALLOW_INPUT) { // Do not swallow request input but // make sure we are closing the connection error = true; getInputBuffer().setSwallowInput(false); } else if (actionCode == ActionCode.RESET) { // Reset response // Note: This must be called before the response is committed getOutputBuffer().reset(); } else if (actionCode == ActionCode.REQ_SET_BODY_REPLAY) { ByteChunk body = (ByteChunk) param; InputFilter savedBody = new SavedRequestInputFilter(body); savedBody.setRequest(request); @SuppressWarnings("unchecked") AbstractInputBuffer<S> internalBuffer = (AbstractInputBuffer<S>) request.getInputBuffer(); internalBuffer.addActiveFilter(savedBody); } else if (actionCode == ActionCode.ASYNC_START) { asyncStateMachine.asyncStart((AsyncContextCallback) param); } else if (actionCode == ActionCode.ASYNC_DISPATCHED) { asyncStateMachine.asyncDispatched(); } else if (actionCode == ActionCode.ASYNC_TIMEOUT) { AtomicBoolean result = (AtomicBoolean) param; result.set(asyncStateMachine.asyncTimeout()); } else if (actionCode == ActionCode.ASYNC_RUN) { asyncStateMachine.asyncRun((Runnable) param); } else if (actionCode == ActionCode.ASYNC_ERROR) { asyncStateMachine.asyncError(); } else if (actionCode == ActionCode.ASYNC_IS_STARTED) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncStarted()); } else if (actionCode == ActionCode.ASYNC_IS_DISPATCHING) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncDispatching()); } else if (actionCode == ActionCode.ASYNC_IS_ASYNC) { ((AtomicBoolean) param).set(asyncStateMachine.isAsync()); } else if (actionCode == ActionCode.ASYNC_IS_TIMINGOUT) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncTimingOut()); } else if (actionCode == ActionCode.ASYNC_IS_ERROR) { ((AtomicBoolean) param).set(asyncStateMachine.isAsyncError()); } else if (actionCode == ActionCode.UPGRADE) { httpUpgradeHandler = (HttpUpgradeHandler) param; // Stop further HTTP output getOutputBuffer().finished = true; } else if (actionCode == ActionCode.AVAILABLE) { request.setAvailable(inputBuffer.available()); } else if (actionCode == ActionCode.NB_WRITE_INTEREST) { AtomicBoolean isReady = (AtomicBoolean)param; try { isReady.set(getOutputBuffer().isReady()); } catch (IOException e) { getLog().debug("isReady() failed", e); error = true; } } else if (actionCode == ActionCode.NB_READ_INTEREST) { registerForEvent(true, false); } else if (actionCode == ActionCode.REQUEST_BODY_FULLY_READ) { AtomicBoolean result = (AtomicBoolean) param; result.set(getInputBuffer().isFinished()); } else if (actionCode == ActionCode.DISPATCH_READ) { socketWrapper.addDispatch(DispatchType.NON_BLOCKING_READ); } else if (actionCode == ActionCode.DISPATCH_WRITE) { socketWrapper.addDispatch(DispatchType.NON_BLOCKING_WRITE); } else if (actionCode == ActionCode.DISPATCH_EXECUTE) { getEndpoint().executeNonBlockingDispatches(socketWrapper); } else { actionInternal(actionCode, param); } } abstract void actionInternal(ActionCode actionCode, Object param); /** * Processors (currently only HTTP BIO) may elect to disable HTTP keep-alive * in some circumstances. This method allows the processor implementation to * determine if keep-alive should be disabled or not. */ protected abstract boolean disableKeepAlive(); /** * Configures the timeout to be used for reading the request line. */ protected abstract void setRequestLineReadTimeout() throws IOException; /** * Defines how a connector handles an incomplete request line read. * * @return <code>true</code> if the processor should break out of the * processing loop, otherwise <code>false</code>. */ protected abstract boolean handleIncompleteRequestLineRead(); /** * Set the socket timeout. */ protected abstract void setSocketTimeout(int timeout) throws IOException; /** * Process pipelined HTTP requests using the specified input and output * streams. * * @param socketWrapper Socket from which the HTTP requests will be read * and the HTTP responses will be written. * * @throws IOException error during an I/O operation */ @Override public SocketState process(SocketWrapper<S> socketWrapper) throws IOException { RequestInfo rp = request.getRequestProcessor(); rp.setStage(org.apache.coyote.Constants.STAGE_PARSE); // Setting up the I/O setSocketWrapper(socketWrapper); getInputBuffer().init(socketWrapper, endpoint); getOutputBuffer().init(socketWrapper, endpoint); // Flags error = false; keepAlive = true; comet = false; openSocket = false; sendfileInProgress = false; readComplete = true; if (endpoint.getUsePolling()) { keptAlive = false; } else { keptAlive = socketWrapper.isKeptAlive(); } if (disableKeepAlive()) { socketWrapper.setKeepAliveLeft(0); } while (!error && keepAlive && !comet && !isAsync() && httpUpgradeHandler == null && !endpoint.isPaused()) { // Parsing the request header try { setRequestLineReadTimeout(); if (!getInputBuffer().parseRequestLine(keptAlive)) { if (handleIncompleteRequestLineRead()) { break; } } if (endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); error = true; } else { // Make sure that connectors that are non-blocking during // header processing (NIO) only set the start time the first // time a request is processed. if (request.getStartTime() < 0) { request.setStartTime(System.currentTimeMillis()); } keptAlive = true; // Set this every time in case limit has been changed via JMX request.getMimeHeaders().setLimit(endpoint.getMaxHeaderCount()); // Currently only NIO will ever return false here if (!getInputBuffer().parseHeaders()) { // We've read part of the request, don't recycle it // instead associate it with the socket openSocket = true; readComplete = false; break; } if (!disableUploadTimeout) { setSocketTimeout(connectionUploadTimeout); } } } catch (IOException e) { if (getLog().isDebugEnabled()) { getLog().debug( sm.getString("http11processor.header.parse"), e); } error = true; break; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); UserDataHelper.Mode logMode = userDataHelper.getNextMode(); if (logMode != null) { String message = sm.getString( "http11processor.header.parse"); switch (logMode) { case INFO_THEN_DEBUG: message += sm.getString( "http11processor.fallToDebug"); //$FALL-THROUGH$ case INFO: getLog().info(message); break; case DEBUG: getLog().debug(message); } } // 400 - Bad Request response.setStatus(400); getAdapter().log(request, response, 0); error = true; } if (!error) { // Setting up filters, and parse some request headers rp.setStage(org.apache.coyote.Constants.STAGE_PREPARE); try { prepareRequest(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); if (getLog().isDebugEnabled()) { getLog().debug(sm.getString( "http11processor.request.prepare"), t); } // 400 - Internal Server Error response.setStatus(400); getAdapter().log(request, response, 0); error = true; } } if (maxKeepAliveRequests == 1) { keepAlive = false; } else if (maxKeepAliveRequests > 0 && socketWrapper.decrementKeepAlive() <= 0) { keepAlive = false; } // Process the request in the adapter if (!error) { try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); getAdapter().service(request, response); // Handle when the response was committed before a serious // error occurred. Throwing a ServletException should both // set the status to 500 and set the errorException. // If we fail here, then the response is likely already // committed, so we can't try and set headers. if(keepAlive && !error) { // Avoid checking twice. error = response.getErrorException() != null || (!isAsync() && statusDropsConnection(response.getStatus())); } setCometTimeouts(socketWrapper); } catch (InterruptedIOException e) { error = true; } catch (HeadersTooLargeException e) { error = true; // The response should not have been committed but check it // anyway to be safe if (!response.isCommitted()) { response.reset(); response.setStatus(500); response.setHeader("Connection", "close"); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString( "http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); error = true; } } // Finish the handling of the request rp.setStage(org.apache.coyote.Constants.STAGE_ENDINPUT); if (!isAsync() && !comet) { if (error) { // If we know we are closing the connection, don't drain // input. This way uploading a 100GB file doesn't tie up the // thread if the servlet has rejected it. getInputBuffer().setSwallowInput(false); } if (response.getStatus() < 200 || response.getStatus() > 299) { if (expectation) { // Client sent Expect: 100-continue but received a // non-2xx response. Disable keep-alive (if enabled) to // ensure the connection is closed. Some clients may // still send the body, some may send the next request. // No way to differentiate, so close the connection to // force the client to send the next request. getInputBuffer().setSwallowInput(false); keepAlive = false; } } endRequest(); } rp.setStage(org.apache.coyote.Constants.STAGE_ENDOUTPUT); // If there was an error, make sure the request is counted as // and error, and update the statistics counter if (error) { response.setStatus(500); } request.updateCounters(); if (!isAsync() && !comet || error) { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); } if (!disableUploadTimeout) { if(endpoint.getSoTimeout() > 0) { setSocketTimeout(endpoint.getSoTimeout()); } else { setSocketTimeout(0); } } rp.setStage(org.apache.coyote.Constants.STAGE_KEEPALIVE); if (breakKeepAliveLoop(socketWrapper)) { break; } } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || endpoint.isPaused()) { return SocketState.CLOSED; } else if (isAsync() || comet) { return SocketState.LONG; } else if (isUpgrade()) { return SocketState.UPGRADING; } else { if (sendfileInProgress) { return SocketState.SENDFILE; } else { if (openSocket) { if (readComplete) { return SocketState.OPEN; } else { return SocketState.LONG; } } else { return SocketState.CLOSED; } } } } /** * After reading the request headers, we have to setup the request filters. */ protected void prepareRequest() { http11 = true; http09 = false; contentDelimitation = false; expectation = false; prepareRequestInternal(); if (endpoint.isSSLEnabled()) { request.scheme().setString("https"); } MessageBytes protocolMB = request.protocol(); if (protocolMB.equals(Constants.HTTP_11)) { http11 = true; protocolMB.setString(Constants.HTTP_11); } else if (protocolMB.equals(Constants.HTTP_10)) { http11 = false; keepAlive = false; protocolMB.setString(Constants.HTTP_10); } else if (protocolMB.equals("")) { // HTTP/0.9 http09 = true; http11 = false; keepAlive = false; } else { // Unsupported protocol http11 = false; error = true; // Send 505; Unsupported HTTP version if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " Unsupported HTTP version \""+protocolMB+"\""); } response.setStatus(505); } MessageBytes methodMB = request.method(); if (methodMB.equals(Constants.GET)) { methodMB.setString(Constants.GET); } else if (methodMB.equals(Constants.POST)) { methodMB.setString(Constants.POST); } MimeHeaders headers = request.getMimeHeaders(); // Check connection header MessageBytes connectionValueMB = headers.getValue(Constants.CONNECTION); if (connectionValueMB != null) { ByteChunk connectionValueBC = connectionValueMB.getByteChunk(); if (findBytes(connectionValueBC, Constants.CLOSE_BYTES) != -1) { keepAlive = false; } else if (findBytes(connectionValueBC, Constants.KEEPALIVE_BYTES) != -1) { keepAlive = true; } } MessageBytes expectMB = null; if (http11) { expectMB = headers.getValue("expect"); } if ((expectMB != null) && (expectMB.indexOfIgnoreCase("100-continue", 0) != -1)) { getInputBuffer().setSwallowInput(false); expectation = true; } // Check user-agent header if ((restrictedUserAgents != null) && ((http11) || (keepAlive))) { MessageBytes userAgentValueMB = headers.getValue("user-agent"); // Check in the restricted list, and adjust the http11 // and keepAlive flags accordingly if(userAgentValueMB != null) { String userAgentValue = userAgentValueMB.toString(); if (restrictedUserAgents != null && restrictedUserAgents.matcher(userAgentValue).matches()) { http11 = false; keepAlive = false; } } } // Check for a full URI (including protocol://host:port/) ByteChunk uriBC = request.requestURI().getByteChunk(); if (uriBC.startsWithIgnoreCase("http", 0)) { int pos = uriBC.indexOf("://", 0, 3, 4); int uriBCStart = uriBC.getStart(); int slashPos = -1; if (pos != -1) { byte[] uriB = uriBC.getBytes(); slashPos = uriBC.indexOf('/', pos + 3); if (slashPos == -1) { slashPos = uriBC.getLength(); // Set URI as "/" request.requestURI().setBytes (uriB, uriBCStart + pos + 1, 1); } else { request.requestURI().setBytes (uriB, uriBCStart + slashPos, uriBC.getLength() - slashPos); } MessageBytes hostMB = headers.setValue("host"); hostMB.setBytes(uriB, uriBCStart + pos + 3, slashPos - pos - 3); } } // Input filter setup InputFilter[] inputFilters = getInputBuffer().getFilters(); // Parse transfer-encoding header MessageBytes transferEncodingValueMB = null; if (http11) { transferEncodingValueMB = headers.getValue("transfer-encoding"); } if (transferEncodingValueMB != null) { String transferEncodingValue = transferEncodingValueMB.toString(); // Parse the comma separated list. "identity" codings are ignored int startPos = 0; int commaPos = transferEncodingValue.indexOf(','); String encodingName = null; while (commaPos != -1) { encodingName = transferEncodingValue.substring (startPos, commaPos).toLowerCase(Locale.ENGLISH).trim(); if (!addInputFilter(inputFilters, encodingName)) { // Unsupported transfer encoding error = true; // 501 - Unimplemented response.setStatus(501); } startPos = commaPos + 1; commaPos = transferEncodingValue.indexOf(',', startPos); } encodingName = transferEncodingValue.substring(startPos) .toLowerCase(Locale.ENGLISH).trim(); if (!addInputFilter(inputFilters, encodingName)) { // Unsupported transfer encoding error = true; // 501 - Unimplemented if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " Unsupported transfer encoding \""+encodingName+"\""); } response.setStatus(501); } } // Parse content-length header long contentLength = request.getContentLengthLong(); if (contentLength >= 0) { if (contentDelimitation) { // contentDelimitation being true at this point indicates that // chunked encoding is being used but chunked encoding should // not be used with a content length. RFC 2616, section 4.4, // bullet 3 states Content-Length must be ignored in this case - // so remove it. headers.removeHeader("content-length"); request.setContentLength(-1); } else { getInputBuffer().addActiveFilter (inputFilters[Constants.IDENTITY_FILTER]); contentDelimitation = true; } } MessageBytes valueMB = headers.getValue("host"); // Check host header if (http11 && (valueMB == null)) { error = true; // 400 - Bad request if (getLog().isDebugEnabled()) { getLog().debug(sm.getString("http11processor.request.prepare")+ " host header missing"); } response.setStatus(400); } parseHost(valueMB); if (!contentDelimitation) { // If there's no content length // (broken HTTP/1.0 or HTTP/1.1), assume // the client is not broken and didn't send a body getInputBuffer().addActiveFilter (inputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } if (error) { getAdapter().log(request, response, 0); } } /** * Connector implementation specific request preparation. Ideally, this will * go away in the future. */ protected abstract void prepareRequestInternal(); /** * When committing the response, we have to validate the set of headers, as * well as setup the response filters. */ private void prepareResponse() { boolean entityBody = true; contentDelimitation = false; OutputFilter[] outputFilters = getOutputBuffer().getFilters(); if (http09 == true) { // HTTP/0.9 getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); return; } int statusCode = response.getStatus(); if (statusCode < 200 || statusCode == 204 || statusCode == 205 || statusCode == 304) { // No entity body getOutputBuffer().addActiveFilter (outputFilters[Constants.VOID_FILTER]); entityBody = false; contentDelimitation = true; } MessageBytes methodMB = request.method(); if (methodMB.equals("HEAD")) { // No entity body getOutputBuffer().addActiveFilter (outputFilters[Constants.VOID_FILTER]); contentDelimitation = true; } // Sendfile support boolean sendingWithSendfile = false; if (getEndpoint().getUseSendfile()) { sendingWithSendfile = prepareSendfile(outputFilters); } // Check for compression boolean isCompressable = false; boolean useCompression = false; if (entityBody && (compressionLevel > 0) && !sendingWithSendfile) { isCompressable = isCompressable(); if (isCompressable) { useCompression = useCompression(); } // Change content-length to -1 to force chunking if (useCompression) { response.setContentLength(-1); } } MimeHeaders headers = response.getMimeHeaders(); if (!entityBody) { response.setContentLength(-1); } // A SC_NO_CONTENT response may include entity headers if (entityBody || statusCode == HttpServletResponse.SC_NO_CONTENT) { String contentType = response.getContentType(); if (contentType != null) { headers.setValue("Content-Type").setString(contentType); } String contentLanguage = response.getContentLanguage(); if (contentLanguage != null) { headers.setValue("Content-Language") .setString(contentLanguage); } } long contentLength = response.getContentLengthLong(); boolean connectionClosePresent = false; if (contentLength != -1) { headers.setValue("Content-Length").setLong(contentLength); getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); contentDelimitation = true; } else { // If the response code supports an entity body and we're on // HTTP 1.1 then we chunk unless we have a Connection: close header connectionClosePresent = isConnectionClose(headers); if (entityBody && http11 && !connectionClosePresent) { getOutputBuffer().addActiveFilter (outputFilters[Constants.CHUNKED_FILTER]); contentDelimitation = true; headers.addValue(Constants.TRANSFERENCODING).setString(Constants.CHUNKED); } else { getOutputBuffer().addActiveFilter (outputFilters[Constants.IDENTITY_FILTER]); } } if (useCompression) { getOutputBuffer().addActiveFilter(outputFilters[Constants.GZIP_FILTER]); headers.setValue("Content-Encoding").setString("gzip"); } // If it might be compressed, set the Vary header if (isCompressable) { // Make Proxies happy via Vary (from mod_deflate) MessageBytes vary = headers.getValue("Vary"); if (vary == null) { // Add a new Vary header headers.setValue("Vary").setString("Accept-Encoding"); } else if (vary.equals("*")) { // No action required } else { // Merge into current header headers.setValue("Vary").setString( vary.getString() + ",Accept-Encoding"); } } // Add date header unless application has already set one (e.g. in a // Caching Filter) if (headers.getValue("Date") == null) { headers.setValue("Date").setString( FastHttpDateFormat.getCurrentDate()); } // FIXME: Add transfer encoding header if ((entityBody) && (!contentDelimitation)) { // Mark as close the connection after the request, and add the // connection: close header keepAlive = false; } // If we know that the request is bad this early, add the // Connection: close header. keepAlive = keepAlive && !statusDropsConnection(statusCode); if (!keepAlive) { // Avoid adding the close header twice if (!connectionClosePresent) { headers.addValue(Constants.CONNECTION).setString( Constants.CLOSE); } } else if (!http11 && !error) { headers.addValue(Constants.CONNECTION).setString(Constants.KEEPALIVE); } // Build the response header getOutputBuffer().sendStatus(); // Add server header if (server != null) { // Always overrides anything the app might set headers.setValue("Server").setString(server); } else if (headers.getValue("Server") == null) { // If app didn't set the header, use the default getOutputBuffer().write(Constants.SERVER_BYTES); } int size = headers.size(); for (int i = 0; i < size; i++) { getOutputBuffer().sendHeader(headers.getName(i), headers.getValue(i)); } getOutputBuffer().endHeaders(); } private boolean isConnectionClose(MimeHeaders headers) { MessageBytes connection = headers.getValue(Constants.CONNECTION); if (connection == null) { return false; } return connection.equals(Constants.CLOSE); } abstract boolean prepareSendfile(OutputFilter[] outputFilters); /** * Parse host. */ protected void parseHost(MessageBytes valueMB) { if (valueMB == null || valueMB.isNull()) { // HTTP/1.0 // If no host header, use the port info from the endpoint // The host will be obtained lazily from the socket if required // using ActionCode#REQ_LOCAL_NAME_ATTRIBUTE request.setServerPort(endpoint.getPort()); return; } ByteChunk valueBC = valueMB.getByteChunk(); byte[] valueB = valueBC.getBytes(); int valueL = valueBC.getLength(); int valueS = valueBC.getStart(); int colonPos = -1; if (hostNameC.length < valueL) { hostNameC = new char[valueL]; } boolean ipv6 = (valueB[valueS] == '['); boolean bracketClosed = false; for (int i = 0; i < valueL; i++) { char b = (char) valueB[i + valueS]; hostNameC[i] = b; if (b == ']') { bracketClosed = true; } else if (b == ':') { if (!ipv6 || bracketClosed) { colonPos = i; break; } } } if (colonPos < 0) { if (!endpoint.isSSLEnabled()) { // 80 - Default HTTP port request.setServerPort(80); } else { // 443 - Default HTTPS port request.setServerPort(443); } request.serverName().setChars(hostNameC, 0, valueL); } else { request.serverName().setChars(hostNameC, 0, colonPos); int port = 0; int mult = 1; for (int i = valueL - 1; i > colonPos; i--) { int charValue = HexUtils.getDec(valueB[i + valueS]); if (charValue == -1 || charValue > 9) { // Invalid character error = true; // 400 - Bad request response.setStatus(400); break; } port = port + (charValue * mult); mult = 10 * mult; } request.setServerPort(port); } } @Override public SocketState asyncDispatch(SocketStatus status) { if (status == SocketStatus.OPEN_WRITE) { try { asyncStateMachine.asyncOperation(); try { if (outputBuffer.hasDataToWrite()) { if (outputBuffer.flushBuffer(false)) { // There is data to write but go via Response to // maintain a consistent view of non-blocking state response.checkRegisterForWrite(true); return SocketState.LONG; } } } catch (IOException x) { if (getLog().isDebugEnabled()) { getLog().debug("Unable to write async data.",x); } status = SocketStatus.ASYNC_WRITE_ERROR; request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, x); } } catch (IllegalStateException x) { registerForEvent(false, true); } } else if (status == SocketStatus.OPEN_READ && request.getReadListener() != null) { try { if (inputBuffer.available() > 0) { asyncStateMachine.asyncOperation(); } } catch (IllegalStateException x) { registerForEvent(true, false); } } RequestInfo rp = request.getRequestProcessor(); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !getAdapter().asyncDispatch(request, response, status); resetTimeouts(); } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.process"), t); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error) { return SocketState.CLOSED; } else if (isAsync()) { return SocketState.LONG; } else { if (!keepAlive) { return SocketState.CLOSED; } else { getInputBuffer().nextRequest(); getOutputBuffer().nextRequest(); return SocketState.OPEN; } } } @Override public boolean isComet() { return comet; } @Override public boolean isUpgrade() { return httpUpgradeHandler != null; } @Override public SocketState upgradeDispatch(SocketStatus status) throws IOException { // Should never reach this code but in case we do... throw new IllegalStateException( sm.getString("http11Processor.upgrade")); } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { return httpUpgradeHandler; } /** * Provides a mechanism for those connector implementations (currently only * NIO) that need to reset timeouts from Async timeouts to standard HTTP * timeouts once async processing completes. */ protected abstract void resetTimeouts(); /** * Provides a mechanism for those connectors (currently only NIO) that need * that need to set comet timeouts. */ protected abstract void setCometTimeouts(SocketWrapper<S> socketWrapper); public void endRequest() { // Finish the handling of the request try { getInputBuffer().endRequest(); } catch (IOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.request.finish"), t); // 500 - Internal Server Error // Can't add a 500 to the access log since that has already been // written in the Adapter.service method. response.setStatus(500); error = true; } try { getOutputBuffer().endRequest(); } catch (IOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); getLog().error(sm.getString("http11processor.response.finish"), t); error = true; } } /** * Checks to see if the keep-alive loop should be broken, performing any * processing (e.g. sendfile handling) that may have an impact on whether * or not the keep-alive loop should be broken. * @return true if the keep-alive loop should be broken */ protected abstract boolean breakKeepAliveLoop( SocketWrapper<S> socketWrapper); @Override public final void recycle(boolean isSocketClosing) { if (getInputBuffer() != null) { getInputBuffer().recycle(); } if (getOutputBuffer() != null) { getOutputBuffer().recycle(); } if (asyncStateMachine != null) { asyncStateMachine.recycle(); } httpUpgradeHandler = null; comet = false; recycleInternal(); } protected abstract void recycleInternal(); }
55,772
Bug 55772 Flushing AsyncContext response writer after ClientAbortException (BrokenPipe) causes request state to leak
null
resolved fixed
cb62f86
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T13:39:52Z
2013-11-13T10:53: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<S> extends AbstractProcessor<S> 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<S> 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_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.getInstance( response.getLocale()).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<S> 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; } @Override protected void registerForEvent(boolean read, boolean write) { // NO-OP } 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.unparsedURI().setBytes(frame.data, frame.off, valueLen); int questionPos = -1; int end = frame.off + valueLen; for(int k = frame.off; k < end; k ++) { if (frame.data[k] == '?') { questionPos = k; break; } } if (questionPos >= 0) { request.queryString().setBytes(frame.data, questionPos + 1, end - questionPos - 1); request.requestURI().setBytes(frame.data, frame.off, questionPos - frame.off); } else { 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; } }
55,772
Bug 55772 Flushing AsyncContext response writer after ClientAbortException (BrokenPipe) causes request state to leak
null
resolved fixed
cb62f86
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T13:39:52Z
2013-11-13T10:53:20Z
test/org/apache/coyote/http11/TestAbstractHttp11Processor.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.File; import java.io.IOException; import java.nio.CharBuffer; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.startup.SimpleHttpClient; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; public class TestAbstractHttp11Processor extends TomcatBaseTest { @Test public void testWithTEVoid() throws Exception { Tomcat tomcat = getTomcatInstance(); // Use the normal Tomcat ROOT context File root = new File("test/webapp"); tomcat.addWebapp("", root.getAbsolutePath()); tomcat.start(); String request = "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + "Transfer-encoding: void" + SimpleHttpClient.CRLF + "Content-Length: 9" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "test=data"; Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {request}); client.connect(); client.processRequest(); assertTrue(client.isResponse501()); } @Test public void testWithTEBuffered() throws Exception { Tomcat tomcat = getTomcatInstance(); // Use the normal Tomcat ROOT context File root = new File("test/webapp"); tomcat.addWebapp("", root.getAbsolutePath()); tomcat.start(); String request = "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + "Transfer-encoding: buffered" + SimpleHttpClient.CRLF + "Content-Length: 9" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "test=data"; Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {request}); client.connect(); client.processRequest(); assertTrue(client.isResponse501()); } @Test public void testWithTEChunked() throws Exception { doTestWithTEChunked(false); } @Test public void testWithTEChunkedWithCL() throws Exception { // Should be ignored doTestWithTEChunked(true); } private void doTestWithTEChunked(boolean withCL) throws Exception { Tomcat tomcat = getTomcatInstance(); // Use the normal Tomcat ROOT context File root = new File("test/webapp"); tomcat.addWebapp("", root.getAbsolutePath()); tomcat.start(); String request = "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + (withCL ? "Content-length: 1" + SimpleHttpClient.CRLF : "") + "Transfer-encoding: chunked" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + "Connection: close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "9" + SimpleHttpClient.CRLF + "test=data" + SimpleHttpClient.CRLF + "0" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF; Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {request}); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); assertTrue(client.getResponseBody().contains("test - data")); } @Test public void testWithTEIdentity() throws Exception { Tomcat tomcat = getTomcatInstance(); // Use the normal Tomcat ROOT context File root = new File("test/webapp"); tomcat.addWebapp("", root.getAbsolutePath()); tomcat.start(); String request = "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + "Transfer-encoding: identity" + SimpleHttpClient.CRLF + "Content-Length: 9" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + "Connection: close" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "test=data"; Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {request}); client.connect(); client.processRequest(); assertTrue(client.isResponse200()); assertTrue(client.getResponseBody().contains("test - data")); } @Test public void testWithTESavedRequest() throws Exception { Tomcat tomcat = getTomcatInstance(); // Use the normal Tomcat ROOT context File root = new File("test/webapp"); tomcat.addWebapp("", root.getAbsolutePath()); tomcat.start(); String request = "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + "Transfer-encoding: savedrequest" + SimpleHttpClient.CRLF + "Content-Length: 9" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "test=data"; Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {request}); client.connect(); client.processRequest(); assertTrue(client.isResponse501()); } @Test public void testWithTEUnsupported() throws Exception { Tomcat tomcat = getTomcatInstance(); // Use the normal Tomcat ROOT context File root = new File("test/webapp"); tomcat.addWebapp("", root.getAbsolutePath()); tomcat.start(); String request = "POST /echo-params.jsp HTTP/1.1" + SimpleHttpClient.CRLF + "Host: any" + SimpleHttpClient.CRLF + "Transfer-encoding: unsupported" + SimpleHttpClient.CRLF + "Content-Length: 9" + SimpleHttpClient.CRLF + "Content-Type: application/x-www-form-urlencoded" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF + "test=data"; Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {request}); client.connect(); client.processRequest(); assertTrue(client.isResponse501()); } @Test public void testPipelining() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctxt = tomcat.addContext("", System.getProperty("java.io.tmpdir")); // Add protected servlet Tomcat.addServlet(ctxt, "TesterServlet", new TesterServlet()); ctxt.addServletMapping("/foo", "TesterServlet"); tomcat.start(); String requestPart1 = "GET /foo HTTP/1.1" + SimpleHttpClient.CRLF; String requestPart2 = "Host: any" + SimpleHttpClient.CRLF + SimpleHttpClient.CRLF; final Client client = new Client(tomcat.getConnector().getLocalPort()); client.setRequest(new String[] {requestPart1, requestPart2}); client.setRequestPause(1000); client.setUseContentLength(true); client.connect(); Runnable send = new Runnable() { @Override public void run() { try { client.sendRequest(); client.sendRequest(); } catch (InterruptedException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } }; Thread t = new Thread(send); t.start(); // Sleep for 1500 ms which should mean the all of request 1 has been // sent and half of request 2 Thread.sleep(1500); // Now read the first response client.readResponse(true); assertFalse(client.isResponse50x()); assertTrue(client.isResponse200()); assertEquals("OK", client.getResponseBody()); // Read the second response. No need to sleep, read will block until // there is data to process client.readResponse(true); assertFalse(client.isResponse50x()); assertTrue(client.isResponse200()); assertEquals("OK", client.getResponseBody()); } @Test public void testChunking11NoContentLength() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctxt = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctxt, "NoContentLengthFlushingServlet", new NoContentLengthFlushingServlet()); ctxt.addServletMapping("/test", "NoContentLengthFlushingServlet"); tomcat.start(); ByteChunk responseBody = new ByteChunk(); Map<String,List<String>> responseHeaders = new HashMap<>(); int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody, responseHeaders); assertEquals(HttpServletResponse.SC_OK, rc); assertTrue(responseHeaders.containsKey("Transfer-Encoding")); List<String> encodings = responseHeaders.get("Transfer-Encoding"); assertEquals(1, encodings.size()); assertEquals("chunked", encodings.get(0)); } @Test public void testNoChunking11NoContentLengthConnectionClose() throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctxt = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctxt, "NoContentLengthConnectionCloseFlushingServlet", new NoContentLengthConnectionCloseFlushingServlet()); ctxt.addServletMapping("/test", "NoContentLengthConnectionCloseFlushingServlet"); tomcat.start(); ByteChunk responseBody = new ByteChunk(); Map<String,List<String>> responseHeaders = new HashMap<>(); int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody, responseHeaders); assertEquals(HttpServletResponse.SC_OK, rc); assertTrue(responseHeaders.containsKey("Connection")); List<String> connections = responseHeaders.get("Connection"); assertEquals(1, connections.size()); assertEquals("close", connections.get(0)); assertFalse(responseHeaders.containsKey("Transfer-Encoding")); assertEquals("OK", responseBody.toString()); } @Test public void testBug53677a() throws Exception { doTestBug53677(false); } @Test public void testBug53677b() throws Exception { doTestBug53677(true); } private void doTestBug53677(boolean flush) throws Exception { Tomcat tomcat = getTomcatInstance(); // Must have a real docBase - just use temp Context ctxt = tomcat.addContext("", System.getProperty("java.io.tmpdir")); Tomcat.addServlet(ctxt, "LargeHeaderServlet", new LargeHeaderServlet(flush)); ctxt.addServletMapping("/test", "LargeHeaderServlet"); tomcat.start(); ByteChunk responseBody = new ByteChunk(); Map<String,List<String>> responseHeaders = new HashMap<>(); int rc = getUrl("http://localhost:" + getPort() + "/test", responseBody, responseHeaders); assertEquals(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, rc); if (responseBody.getLength() > 0) { // It will be >0 if the standard error page handlign has been // triggered assertFalse(responseBody.toString().contains("FAIL")); } } private static final class LargeHeaderServlet extends HttpServlet { private static final long serialVersionUID = 1L; boolean flush = false; public LargeHeaderServlet(boolean flush) { this.flush = flush; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String largeValue = CharBuffer.allocate(10000).toString().replace('\0', 'x'); resp.setHeader("x-Test", largeValue); if (flush) { resp.flushBuffer(); } resp.setContentType("text/plain"); resp.getWriter().print("FAIL"); } } // flushes with no content-length set // should result in chunking on HTTP 1.1 private static final class NoContentLengthFlushingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/plain"); resp.getWriter().write("OK"); resp.flushBuffer(); } } // flushes with no content-length set but sets Connection: close header // should no result in chunking on HTTP 1.1 private static final class NoContentLengthConnectionCloseFlushingServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("text/event-stream"); resp.addHeader("Connection", "close"); resp.flushBuffer(); resp.getWriter().write("OK"); resp.flushBuffer(); } } private static final class Client extends SimpleHttpClient { public Client(int port) { setPort(port); } @Override public boolean isResponseBodyOK() { return getResponseBody().contains("test - data"); } } }
55,776
Bug 55776 if path include relative char, eg: ../, classloader will not find zhe file
I use ibatis in my project, config file path include '..', tomcat can not find the file, command line show: Could not find resource ../ibatis/code/sendType.xml
resolved fixed
a1ad6ce
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T15:04:52Z
2013-11-14T11:53:20Z
java/org/apache/catalina/webresources/StandardRoot.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.webresources; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Locale; import java.util.Set; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.WebResourceSet; import org.apache.catalina.WebResourceTraceWrapper; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.res.StringManager; /** * <p> * Provides the resources implementation for a web application. The * {@link org.apache.catalina.Lifecycle} of this class should be aligned with * that of the associated {@link Context}. * </p><p> * This implementation assumes that the base attribute supplied to {@link * StandardRoot#createWebResourceSet( * org.apache.catalina.WebResourceRoot.ResourceSetType, String, String, String, * String)} represents the absolute path to a file. * </p> */ public class StandardRoot extends LifecycleMBeanBase implements WebResourceRoot { private static final Log log = LogFactory.getLog(Cache.class); protected static final StringManager sm = StringManager.getManager(Constants.Package); private Context context; private boolean allowLinking = false; private final ArrayList<WebResourceSet> preResources = new ArrayList<>(); private WebResourceSet main; private final ArrayList<WebResourceSet> classResources = new ArrayList<>(); private final ArrayList<WebResourceSet> jarResources = new ArrayList<>(); private final ArrayList<WebResourceSet> postResources = new ArrayList<>(); private final Cache cache = new Cache(this); private boolean cachingAllowed = true; private boolean traceLockedFiles = false; private final Set<WebResourceTraceWrapper> tracedResources = new HashSet<>(); // Constructs to make iteration over all WebResourceSets simpler private final ArrayList<WebResourceSet> mainResources = new ArrayList<>(); private final ArrayList<ArrayList<WebResourceSet>> allResources = new ArrayList<>(); { allResources.add(preResources); allResources.add(mainResources); allResources.add(classResources); allResources.add(jarResources); allResources.add(postResources); } /** * Creates a new standard implementation of {@link WebResourceRoot}. A no * argument constructor is required for this to work with the digester. * {@link #setContext(Context)} must be called before this component is * initialized. */ public StandardRoot() { // NO-OP } public StandardRoot(Context context) { this.context = context; } @Override public String[] list(String path) { return list(path, true); } private String[] list(String path, boolean doStateCheck) { if (doStateCheck) { checkState(); } // Set because we don't want duplicates // LinkedHashSet to retain the order. It is the order of the // WebResourceSet that matters but it is simpler to retain the order // over all of the JARs. HashSet<String> result = new LinkedHashSet<>(); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (!webResourceSet.getClassLoaderOnly()) { String[] entries = webResourceSet.list(path); for (String entry : entries) { result.add(entry); } } } } return result.toArray(new String[result.size()]); } @Override public Set<String> listWebAppPaths(String path) { checkState(); // Set because we don't want duplicates HashSet<String> result = new HashSet<>(); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (!webResourceSet.getClassLoaderOnly()) { result.addAll(webResourceSet.listWebAppPaths(path)); } } } if (result.size() == 0) { return null; } return result; } @Override public boolean mkdir(String path) { checkState(); if (preResourceExists(path)) { return false; } return main.mkdir(path); } @Override public boolean write(String path, InputStream is, boolean overwrite) { checkState(); if (!overwrite && preResourceExists(path)) { return false; } return main.write(path, is, overwrite); } private boolean preResourceExists(String path) { for (WebResourceSet webResourceSet : preResources) { WebResource webResource = webResourceSet.getResource(path); if (webResource.exists()) { return true; } } return false; } @Override public WebResource getResource(String path) { return getResource(path, true, false); } private WebResource getResource(String path, boolean doStateCheck, boolean useClassLoaderResources) { if (doStateCheck) { checkState(); } if (isCachingAllowed()) { return cache.getResource(path, useClassLoaderResources); } else { return getResourceInternal(path, useClassLoaderResources); } } @Override public WebResource getClassLoaderResource(String path) { checkPath(path); return getResource("/WEB-INF/classes" + path, true, true); } @Override public WebResource[] getClassLoaderResources(String path) { checkPath(path); return getResources("/WEB-INF/classes" + path, true); } private void checkPath(String path) { if (path == null || path.length() == 0 || !path.startsWith("/")) { throw new IllegalArgumentException( sm.getString("standardRoot.invalidPath", path)); } } protected final WebResource getResourceInternal(String path, boolean useClassLoaderResources) { WebResource result = null; WebResource virtual = null; for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (useClassLoaderResources || !webResourceSet.getClassLoaderOnly()) { result = webResourceSet.getResource(path); if (result.exists()) { return result; } if (virtual == null && result.isVirtual()) { virtual = result; } } } } // Use the first virtual result if no real result was found if (virtual != null) { return virtual; } // Default is empty resource in main resources return new EmptyResource(this, path); } @Override public WebResource[] getResources(String path) { return getResources(path, false); } private WebResource[] getResources(String path, boolean useClassLoaderResources) { checkState(); ArrayList<WebResource> result = new ArrayList<>(); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (useClassLoaderResources || !webResourceSet.getClassLoaderOnly()) { WebResource webResource = webResourceSet.getResource(path); if (webResource.exists()) { result.add(webResource); } } } } if (result.size() == 0) { result.add(main.getResource(path)); } return result.toArray(new WebResource[result.size()]); } @Override public WebResource[] listResources(String path) { return listResources(path, true); } private WebResource[] listResources(String path, boolean doStateCheck) { if (doStateCheck) { checkState(); } String[] resources = list(path, false); WebResource[] result = new WebResource[resources.length]; for (int i = 0; i < resources.length; i++) { if (path.charAt(path.length() - 1) == '/') { result[i] = getResource(path + resources[i], false, false); } else { result[i] = getResource(path + '/' + resources[i], false, false); } } return result; } @Override public void createWebResourceSet(ResourceSetType type, String webAppMount, URL url, String internalPath) { BaseLocation baseLocation = new BaseLocation(url); createWebResourceSet(type, webAppMount, baseLocation.getBasePath(), baseLocation.getArchivePath(), internalPath); } @Override public void createWebResourceSet(ResourceSetType type, String webAppMount, String base, String archivePath, String internalPath) { ArrayList<WebResourceSet> resourceList; WebResourceSet resourceSet; switch (type) { case PRE: resourceList = preResources; break; case CLASSES_JAR: resourceList = classResources; break; case RESOURCE_JAR: resourceList = jarResources; break; case POST: resourceList = postResources; break; default: throw new IllegalArgumentException( sm.getString("standardRoot.createUnknownType", type)); } // This implementation assumes that the base for all resources will be a // file. File file = new File(base); if (file.isFile()) { if (archivePath != null) { // Must be a JAR nested inside a WAR if archivePath is non-null resourceSet = new JarWarResourceSet(this, webAppMount, base, archivePath, internalPath); } else if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { resourceSet = new JarResourceSet(this, webAppMount, base, internalPath); } else { resourceSet = new FileResourceSet(this, webAppMount, base, internalPath); } } else if (file.isDirectory()) { resourceSet = new DirResourceSet(this, webAppMount, base, internalPath); } else { throw new IllegalArgumentException( sm.getString("standardRoot.createInvalidFile", file)); } if (type.equals(ResourceSetType.CLASSES_JAR)) { resourceSet.setClassLoaderOnly(true); } resourceList.add(resourceSet); } @Override public void addPreResources(WebResourceSet webResourceSet) { webResourceSet.setRoot(this); preResources.add(webResourceSet); } @Override public WebResourceSet[] getPreResources() { return preResources.toArray(new WebResourceSet[0]); } @Override public void addJarResources(WebResourceSet webResourceSet) { webResourceSet.setRoot(this); jarResources.add(webResourceSet); } @Override public WebResourceSet[] getJarResources() { return jarResources.toArray(new WebResourceSet[0]); } @Override public void addPostResources(WebResourceSet webResourceSet) { webResourceSet.setRoot(this); postResources.add(webResourceSet); } @Override public WebResourceSet[] getPostResources() { return postResources.toArray(new WebResourceSet[0]); } @Override public void setAllowLinking(boolean allowLinking) { this.allowLinking = allowLinking; } @Override public boolean getAllowLinking() { return allowLinking; } @Override public void setCachingAllowed(boolean cachingAllowed) { this.cachingAllowed = cachingAllowed; } @Override public boolean isCachingAllowed() { return cachingAllowed; } @Override public long getCacheTtl() { return cache.getTtl(); } @Override public void setCacheTtl(long cacheTtl) { cache.setTtl(cacheTtl); } @Override public long getCacheMaxSize() { return cache.getMaxSize(); } @Override public void setCacheMaxSize(long cacheMaxSize) { cache.setMaxSize(cacheMaxSize); } @Override public void setCacheMaxObjectSize(long cacheMaxObjectSize) { cache.setMaxObjectSize(cacheMaxObjectSize); } @Override public long getCacheMaxObjectSize() { return cache.getMaxObjectSize(); } @Override public void setTraceLockedFiles(boolean traceLockedFiles) { this.traceLockedFiles = traceLockedFiles; } @Override public boolean getTraceLockedFiles() { return traceLockedFiles; } @Override public Context getContext() { return context; } @Override public void setContext(Context context) { this.context = context; } private void checkState() { if (!getState().isAvailable()) { throw new IllegalStateException( sm.getString("standardRoot.checkStateNotStarted")); } } /* * Class loader resources are handled by treating JARs in WEB-INF/lib as * resource JARs (without the internal META-INF/resources/ prefix) mounted * at WEB-INF/claasses (rather than the web app root). This enables reuse * of the resource handling plumbing. * * These resources are marked as class loader only so they are only used in * the methods that are explicitly defined to return class loader resources. * This prevents calls to getResource("/WEB-INF/classes") returning from one * or more of the JAR files. */ private void processWebInfLib() { WebResource[] possibleJars = listResources("/WEB-INF/lib", false); for (WebResource possibleJar : possibleJars) { if (possibleJar.isFile() && possibleJar.getName().endsWith(".jar")) { createWebResourceSet(ResourceSetType.CLASSES_JAR, "/WEB-INF/classes", possibleJar.getURL(), "/"); } } } /** * For unit testing */ protected final void setMainResources(WebResourceSet main) { this.main = main; mainResources.clear(); mainResources.add(main); } @Override public void backgroundProcess() { cache.backgroundProcess(); } @Override public void registerTracedResource(WebResourceTraceWrapper traceResource) { tracedResources.add(traceResource); } @Override public void deregisterTracedResource(WebResourceTraceWrapper traceResource) { tracedResources.remove(traceResource); } // ----------------------------------------------------------- JMX Lifecycle @Override protected String getDomainInternal() { return context.getDomain(); } @Override protected String getObjectNameKeyProperties() { StringBuilder keyProperties = new StringBuilder("type=WebResourceRoot"); keyProperties.append(context.getMBeanKeyProperties()); return keyProperties.toString(); } // --------------------------------------------------------------- Lifecycle @Override protected void initInternal() throws LifecycleException { super.initInternal(); // Ensure support for jar:war:file:/ URLs will be available (required // for resource JARs in packed WAR files). TomcatURLStreamHandlerFactory.register(); if (context == null) { throw new IllegalStateException( sm.getString("standardRoot.noContext")); } for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.init(); } } } @Override protected void startInternal() throws LifecycleException { String docBase = context.getDocBase(); File f = new File(docBase); if (!f.isAbsolute()) { f = new File(((Host)context.getParent()).getAppBaseFile(), f.getName()); } if (f.isDirectory()) { main = new DirResourceSet(this, "/", f.getAbsolutePath(), "/"); } else if(f.isFile() && docBase.endsWith(".war")) { main = new JarResourceSet(this, "/", f.getAbsolutePath(), "/"); } else { throw new IllegalArgumentException( sm.getString("standardRoot.startInvalidMain", f.getAbsolutePath())); } mainResources.clear(); mainResources.add(main); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.start(); } } // This has to be called after the other resources have been started // else it won't find all the matching resources processWebInfLib(); // Need to start the newly found resources for (WebResourceSet classResource : classResources) { classResource.start(); } setState(LifecycleState.STARTING); } @Override protected void stopInternal() throws LifecycleException { for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.stop(); } } if (main != null) { main.destroy(); } mainResources.clear(); for (WebResourceSet webResourceSet : jarResources) { webResourceSet.destroy(); } jarResources.clear(); for (WebResourceSet webResourceSet : classResources) { webResourceSet.destroy(); } classResources.clear(); for (WebResourceTraceWrapper tracedResource : tracedResources) { log.error(sm.getString("standardRoot.lockedFile", context.getName(), tracedResource.getName()), tracedResource.getCreatedBy()); try { tracedResource.close(); } catch (IOException e) { // Ignore } } cache.clear(); setState(LifecycleState.STOPPING); } @Override protected void destroyInternal() throws LifecycleException { for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.destroy(); } } super.destroyInternal(); } // Unit tests need to access this class static class BaseLocation { private final String basePath; private final String archivePath; BaseLocation(URL url) { File f = null; if ("jar".equals(url.getProtocol())) { String jarUrl = url.toString(); int endOfFileUrl = jarUrl.indexOf("!/"); String fileUrl = jarUrl.substring(4, endOfFileUrl); try { f = new File(new URL(fileUrl).toURI()); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException(e); } int startOfArchivePath = endOfFileUrl + 2; if (jarUrl.length() > startOfArchivePath) { archivePath = jarUrl.substring(startOfArchivePath); } else { archivePath = null; } } else if ("file".equals(url.getProtocol())){ try { f = new File(url.toURI()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } archivePath = null; } else { throw new IllegalArgumentException(sm.getString( "standardRoot.unsupportedProtocol", url.getProtocol())); } basePath = f.getAbsolutePath(); } String getBasePath() { return basePath; } String getArchivePath() { return archivePath; } } }
55,778
Bug 55778 JNDIRealm: Authentication with GSSAPI to LDAP with SSL connection causes an exception
Whenever i try to authenticate with GSSAPI to a LDAP server with a SSL connection (ldaps), the following exception is thrown: javax.naming.ServiceUnavailableException: myserver.at:636; socket closed; remaining name 'dc=example,dc=org' at com.sun.jndi.ldap.Connection.readReply(Connection.java:452) at com.sun.jndi.ldap.LdapClient.getSearchReply(LdapClient.java:631) at com.sun.jndi.ldap.LdapClient.search(LdapClient.java:554) at com.sun.jndi.ldap.LdapCtx.doSearch(LdapCtx.java:1985) at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1847) at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1772) ... Steps to reproduce: 1. Configure the valve org.apache.catalina.authenticator.SpnegoAuthenticator in the server.xml with storeDelegatedCredential="true". 2. Configure the realm org.apache.catalina.realm.JNDIRealm in the server.xml with an SSL connection url (e.g. ldaps://myserver.at:636) 3. Configure an auth-method with SPNEGO, security-constraints and security-roles in the web.xml 4. Add required keystores to the jdk for the ldaps connection. 5. Try to authenticate I debugged into the JNDIRealm and figured out, that changing line 2082 from "context.addToEnvironment("javax.security.sasl.qop", "auth-conf");" to "context.addToEnvironment("javax.security.sasl.qop", "auth");" would solve the problem. I also tested the fix with a new written JNDIRealm. But i'm not sure, if this fix causes other security issues.
resolved fixed
27806aa
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-15T17:39:05Z
2013-11-14T20:13:20Z
java/org/apache/catalina/realm/JNDIRealm.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.net.URI; import java.net.URISyntaxException; import java.nio.charset.StandardCharsets; import java.security.Principal; import java.text.MessageFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; 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 javax.naming.AuthenticationException; import javax.naming.CommunicationException; import javax.naming.CompositeName; import javax.naming.Context; import javax.naming.InvalidNameException; import javax.naming.Name; import javax.naming.NameNotFoundException; import javax.naming.NameParser; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.PartialResultException; import javax.naming.ServiceUnavailableException; import javax.naming.directory.Attribute; import javax.naming.directory.Attributes; import javax.naming.directory.DirContext; import javax.naming.directory.InitialDirContext; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import org.apache.catalina.LifecycleException; import org.apache.tomcat.util.codec.binary.Base64; import org.ietf.jgss.GSSCredential; /** * <p>Implementation of <strong>Realm</strong> that works with a directory * server accessed via the Java Naming and Directory Interface (JNDI) APIs. * The following constraints are imposed on the data structure in the * underlying directory server:</p> * <ul> * * <li>Each user that can be authenticated is represented by an individual * element in the top level <code>DirContext</code> that is accessed * via the <code>connectionURL</code> property.</li> * * <li>If a socket connection can not be made to the <code>connectURL</code> * an attempt will be made to use the <code>alternateURL</code> if it * exists.</li> * * <li>Each user element has a distinguished name that can be formed by * substituting the presented username into a pattern configured by the * <code>userPattern</code> property.</li> * * <li>Alternatively, if the <code>userPattern</code> property is not * specified, a unique element can be located by searching the directory * context. In this case: * <ul> * <li>The <code>userSearch</code> pattern specifies the search filter * after substitution of the username.</li> * <li>The <code>userBase</code> property can be set to the element that * is the base of the subtree containing users. If not specified, * the search base is the top-level context.</li> * <li>The <code>userSubtree</code> property can be set to * <code>true</code> if you wish to search the entire subtree of the * directory context. The default value of <code>false</code> * requests a search of only the current level.</li> * </ul> * </li> * * <li>The user may be authenticated by binding to the directory with the * username and password presented. This method is used when the * <code>userPassword</code> property is not specified.</li> * * <li>The user may be authenticated by retrieving the value of an attribute * from the directory and comparing it explicitly with the value presented * by the user. This method is used when the <code>userPassword</code> * property is specified, in which case: * <ul> * <li>The element for this user must contain an attribute named by the * <code>userPassword</code> property. * <li>The value of the user password attribute is either a cleartext * String, or the result of passing a cleartext String through the * <code>RealmBase.digest()</code> method (using the standard digest * support included in <code>RealmBase</code>). * <li>The user is considered to be authenticated if the presented * credentials (after being passed through * <code>RealmBase.digest()</code>) are equal to the retrieved value * for the user password attribute.</li> * </ul></li> * * <li>Each group of users that has been assigned a particular role may be * represented by an individual element in the top level * <code>DirContext</code> that is accessed via the * <code>connectionURL</code> property. This element has the following * characteristics: * <ul> * <li>The set of all possible groups of interest can be selected by a * search pattern configured by the <code>roleSearch</code> * property.</li> * <li>The <code>roleSearch</code> pattern optionally includes pattern * replacements "{0}" for the distinguished name, and/or "{1}" for * the username, and/or "{2}" the value of an attribute from the * user's directory entry (the attribute is specified by the * <code>userRoleAttribute</code> property), of the authenticated user * for which roles will be retrieved.</li> * <li>The <code>roleBase</code> property can be set to the element that * is the base of the search for matching roles. If not specified, * the entire context will be searched.</li> * <li>The <code>roleSubtree</code> property can be set to * <code>true</code> if you wish to search the entire subtree of the * directory context. The default value of <code>false</code> * requests a search of only the current level.</li> * <li>The element includes an attribute (whose name is configured by * the <code>roleName</code> property) containing the name of the * role represented by this element.</li> * </ul></li> * * <li>In addition, roles may be represented by the values of an attribute * in the user's element whose name is configured by the * <code>userRoleName</code> property.</li> * * <li>A default role can be assigned to each user that was successfully * authenticated by setting the <code>commonRole</code> property to the * name of this role. The role doesn't have to exist in the directory.</li> * * <li>If the directory server contains nested roles, you can search for them * by setting <code>roleNested</code> to <code>true</code>. * The default value is <code>false</code>, so role searches will not find * nested roles.</li> * * <li>Note that the standard <code>&lt;security-role-ref&gt;</code> element in * the web application deployment descriptor allows applications to refer * to roles programmatically by names other than those used in the * directory server itself.</li> * </ul> * * <p><strong>TODO</strong> - Support connection pooling (including message * format objects) so that <code>authenticate()</code> does not have to be * synchronized.</p> * * <p><strong>WARNING</strong> - There is a reported bug against the Netscape * provider code (com.netscape.jndi.ldap.LdapContextFactory) with respect to * successfully authenticated a non-existing user. The * report is here: http://issues.apache.org/bugzilla/show_bug.cgi?id=11210 . * With luck, Netscape has updated their provider code and this is not an * issue. </p> * * @author John Holman * @author Craig R. McClanahan * @version $Id$ */ public class JNDIRealm extends RealmBase { // ----------------------------------------------------- Instance Variables /** * The type of authentication to use */ protected String authentication = null; /** * The connection username for the server we will contact. */ protected String connectionName = null; /** * The connection password for the server we will contact. */ protected String connectionPassword = null; /** * The connection URL for the server we will contact. */ protected String connectionURL = null; /** * The directory context linking us to our directory server. */ protected DirContext context = null; /** * The JNDI context factory used to acquire our InitialContext. By * default, assumes use of an LDAP server using the standard JNDI LDAP * provider. */ protected String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory"; /** * How aliases should be dereferenced during search operations. */ protected String derefAliases = null; /** * Constant that holds the name of the environment property for specifying * the manner in which aliases should be dereferenced. */ public static final String DEREF_ALIASES = "java.naming.ldap.derefAliases"; /** * Descriptive information about this Realm implementation. */ protected static final String name = "JNDIRealm"; /** * The protocol that will be used in the communication with the * directory server. */ protected String protocol = null; /** * Should we ignore PartialResultExceptions when iterating over NamingEnumerations? * Microsoft Active Directory often returns referrals, which lead * to PartialResultExceptions. Unfortunately there's no stable way to detect, * if the Exceptions really come from an AD referral. * Set to true to ignore PartialResultExceptions. */ protected boolean adCompat = false; /** * How should we handle referrals? Microsoft Active Directory often returns * referrals. If you need to follow them set referrals to "follow". * Caution: if your DNS is not part of AD, the LDAP client lib might try * to resolve your domain name in DNS to find another LDAP server. */ protected String referrals = null; /** * The base element for user searches. */ protected String userBase = ""; /** * The message format used to search for a user, with "{0}" marking * the spot where the username goes. */ protected String userSearch = null; /** * The MessageFormat object associated with the current * <code>userSearch</code>. */ protected MessageFormat userSearchFormat = null; /** * Should we search the entire subtree for matching users? */ protected boolean userSubtree = false; /** * The attribute name used to retrieve the user password. */ protected String userPassword = null; /** * The name of the attribute inside the users * directory entry where the value will be * taken to search for roles * This attribute is not used during a nested search */ protected String userRoleAttribute = null; /** * A string of LDAP user patterns or paths, ":"-separated * These will be used to form the distinguished name of a * user, with "{0}" marking the spot where the specified username * goes. * This is similar to userPattern, but allows for multiple searches * for a user. */ protected String[] userPatternArray = null; /** * The message format used to form the distinguished name of a * user, with "{0}" marking the spot where the specified username * goes. */ protected String userPattern = null; /** * An array of MessageFormat objects associated with the current * <code>userPatternArray</code>. */ protected MessageFormat[] userPatternFormatArray = null; /** * The base element for role searches. */ protected String roleBase = ""; /** * The MessageFormat object associated with the current * <code>roleBase</code>. */ protected MessageFormat roleBaseFormat = null; /** * The MessageFormat object associated with the current * <code>roleSearch</code>. */ protected MessageFormat roleFormat = null; /** * The name of an attribute in the user's entry containing * roles for that user */ protected String userRoleName = null; /** * The name of the attribute containing roles held elsewhere */ protected String roleName = null; /** * The message format used to select roles for a user, with "{0}" marking * the spot where the distinguished name of the user goes. The "{1}" * and "{2}" are described in the Configuration Reference. */ protected String roleSearch = null; /** * Should we search the entire subtree for matching memberships? */ protected boolean roleSubtree = false; /** * Should we look for nested group in order to determine roles? */ protected boolean roleNested = false; /** * When searching for user roles, should the search be performed as the user * currently being authenticated? If false, {@link #connectionName} and * {@link #connectionPassword} will be used if specified, else an anonymous * connection will be used. */ protected boolean roleSearchAsUser = false; /** * An alternate URL, to which, we should connect if connectionURL fails. */ protected String alternateURL; /** * The number of connection attempts. If greater than zero we use the * alternate url. */ protected int connectionAttempt = 0; /** * Add this role to every authenticated user */ protected String commonRole = null; /** * The timeout, in milliseconds, to use when trying to create a connection * to the directory. The default is 5000 (5 seconds). */ protected String connectionTimeout = "5000"; /** * The sizeLimit (also known as the countLimit) to use when the realm is * configured with {@link #userSearch}. Zero for no limit. */ protected long sizeLimit = 0; /** * The timeLimit (in milliseconds) to use when the realm is configured with * {@link #userSearch}. Zero for no limit. */ protected int timeLimit = 0; /** * Should delegated credentials from the SPNEGO authenticator be used if * available */ protected boolean useDelegatedCredential = true; // ------------------------------------------------------------- Properties /** * Return the type of authentication to use. */ public String getAuthentication() { return authentication; } /** * Set the type of authentication to use. * * @param authentication The authentication */ public void setAuthentication(String authentication) { this.authentication = authentication; } /** * Return the connection username for this Realm. */ public String getConnectionName() { return (this.connectionName); } /** * Set the connection username for this Realm. * * @param connectionName The new connection username */ public void setConnectionName(String connectionName) { this.connectionName = connectionName; } /** * Return the connection password for this Realm. */ public String getConnectionPassword() { return (this.connectionPassword); } /** * Set the connection password for this Realm. * * @param connectionPassword The new connection password */ public void setConnectionPassword(String connectionPassword) { this.connectionPassword = connectionPassword; } /** * Return the connection URL for this Realm. */ public String getConnectionURL() { return (this.connectionURL); } /** * Set the connection URL for this Realm. * * @param connectionURL The new connection URL */ public void setConnectionURL(String connectionURL) { this.connectionURL = connectionURL; } /** * Return the JNDI context factory for this Realm. */ public String getContextFactory() { return (this.contextFactory); } /** * Set the JNDI context factory for this Realm. * * @param contextFactory The new context factory */ public void setContextFactory(String contextFactory) { this.contextFactory = contextFactory; } /** * Return the derefAliases setting to be used. */ public java.lang.String getDerefAliases() { return derefAliases; } /** * Set the value for derefAliases to be used when searching the directory. * * @param derefAliases New value of property derefAliases. */ public void setDerefAliases(java.lang.String derefAliases) { this.derefAliases = derefAliases; } /** * Return the protocol to be used. */ public String getProtocol() { return protocol; } /** * Set the protocol for this Realm. * * @param protocol The new protocol. */ public void setProtocol(String protocol) { this.protocol = protocol; } /** * Returns the current settings for handling PartialResultExceptions */ public boolean getAdCompat () { return adCompat; } /** * How do we handle PartialResultExceptions? * True: ignore all PartialResultExceptions. */ public void setAdCompat (boolean adCompat) { this.adCompat = adCompat; } /** * Returns the current settings for handling JNDI referrals. */ public String getReferrals () { return referrals; } /** * How do we handle JNDI referrals? ignore, follow, or throw * (see javax.naming.Context.REFERRAL for more information). */ public void setReferrals (String referrals) { this.referrals = referrals; } /** * Return the base element for user searches. */ public String getUserBase() { return (this.userBase); } /** * Set the base element for user searches. * * @param userBase The new base element */ public void setUserBase(String userBase) { this.userBase = userBase; } /** * Return the message format pattern for selecting users in this Realm. */ public String getUserSearch() { return (this.userSearch); } /** * Set the message format pattern for selecting users in this Realm. * * @param userSearch The new user search pattern */ public void setUserSearch(String userSearch) { this.userSearch = userSearch; if (userSearch == null) userSearchFormat = null; else userSearchFormat = new MessageFormat(userSearch); } /** * Return the "search subtree for users" flag. */ public boolean getUserSubtree() { return (this.userSubtree); } /** * Set the "search subtree for users" flag. * * @param userSubtree The new search flag */ public void setUserSubtree(boolean userSubtree) { this.userSubtree = userSubtree; } /** * Return the user role name attribute name for this Realm. */ public String getUserRoleName() { return userRoleName; } /** * Set the user role name attribute name for this Realm. * * @param userRoleName The new userRole name attribute name */ public void setUserRoleName(String userRoleName) { this.userRoleName = userRoleName; } /** * Return the base element for role searches. */ public String getRoleBase() { return (this.roleBase); } /** * Set the base element for role searches. * * @param roleBase The new base element */ public void setRoleBase(String roleBase) { this.roleBase = roleBase; if (roleBase == null) roleBaseFormat = null; else roleBaseFormat = new MessageFormat(roleBase); } /** * Return the role name attribute name for this Realm. */ public String getRoleName() { return (this.roleName); } /** * Set the role name attribute name for this Realm. * * @param roleName The new role name attribute name */ public void setRoleName(String roleName) { this.roleName = roleName; } /** * Return the message format pattern for selecting roles in this Realm. */ public String getRoleSearch() { return (this.roleSearch); } /** * Set the message format pattern for selecting roles in this Realm. * * @param roleSearch The new role search pattern */ public void setRoleSearch(String roleSearch) { this.roleSearch = roleSearch; if (roleSearch == null) roleFormat = null; else roleFormat = new MessageFormat(roleSearch); } public boolean isRoleSearchAsUser() { return roleSearchAsUser; } public void setRoleSearchAsUser(boolean roleSearchAsUser) { this.roleSearchAsUser = roleSearchAsUser; } /** * Return the "search subtree for roles" flag. */ public boolean getRoleSubtree() { return (this.roleSubtree); } /** * Set the "search subtree for roles" flag. * * @param roleSubtree The new search flag */ public void setRoleSubtree(boolean roleSubtree) { this.roleSubtree = roleSubtree; } /** * Return the "The nested group search flag" flag. */ public boolean getRoleNested() { return (this.roleNested); } /** * Set the "search subtree for roles" flag. * * @param roleNested The nested group search flag */ public void setRoleNested(boolean roleNested) { this.roleNested = roleNested; } /** * Return the password attribute used to retrieve the user password. */ public String getUserPassword() { return (this.userPassword); } /** * Set the password attribute used to retrieve the user password. * * @param userPassword The new password attribute */ public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserRoleAttribute() { return userRoleAttribute; } public void setUserRoleAttribute(String userRoleAttribute) { this.userRoleAttribute = userRoleAttribute; } /** * Return the message format pattern for selecting users in this Realm. */ public String getUserPattern() { return (this.userPattern); } /** * Set the message format pattern for selecting users in this Realm. * This may be one simple pattern, or multiple patterns to be tried, * separated by parentheses. (for example, either "cn={0}", or * "(cn={0})(cn={0},o=myorg)" Full LDAP search strings are also supported, * but only the "OR", "|" syntax, so "(|(cn={0})(cn={0},o=myorg))" is * also valid. Complex search strings with &, etc are NOT supported. * * @param userPattern The new user pattern */ public void setUserPattern(String userPattern) { this.userPattern = userPattern; if (userPattern == null) userPatternArray = null; else { userPatternArray = parseUserPatternString(userPattern); int len = this.userPatternArray.length; userPatternFormatArray = new MessageFormat[len]; for (int i=0; i < len; i++) { userPatternFormatArray[i] = new MessageFormat(userPatternArray[i]); } } } /** * Getter for property alternateURL. * * @return Value of property alternateURL. */ public String getAlternateURL() { return this.alternateURL; } /** * Setter for property alternateURL. * * @param alternateURL New value of property alternateURL. */ public void setAlternateURL(String alternateURL) { this.alternateURL = alternateURL; } /** * Return the common role */ public String getCommonRole() { return commonRole; } /** * Set the common role * * @param commonRole The common role */ public void setCommonRole(String commonRole) { this.commonRole = commonRole; } /** * Return the connection timeout. */ public String getConnectionTimeout() { return connectionTimeout; } /** * Set the connection timeout. * * @param timeout The new connection timeout */ public void setConnectionTimeout(String timeout) { this.connectionTimeout = timeout; } public long getSizeLimit() { return sizeLimit; } public void setSizeLimit(long sizeLimit) { this.sizeLimit = sizeLimit; } public int getTimeLimit() { return timeLimit; } public void setTimeLimit(int timeLimit) { this.timeLimit = timeLimit; } public boolean isUseDelegatedCredential() { return useDelegatedCredential; } public void setUseDelegatedCredential(boolean useDelegatedCredential) { this.useDelegatedCredential = useDelegatedCredential; } // ---------------------------------------------------------- Realm 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) { DirContext context = null; Principal principal = null; try { // Ensure that we have a directory context available context = open(); // Occassionally the directory context will timeout. Try one more // time before giving up. try { // Authenticate the specified username if possible principal = authenticate(context, username, credentials); } catch (NullPointerException e) { /* BZ 42449 - Kludge Sun's LDAP provider with broken SSL */ // log the exception so we know it's there. containerLog.info(sm.getString("jndiRealm.exception.retry"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); } catch (CommunicationException e) { // log the exception so we know it's there. containerLog.info(sm.getString("jndiRealm.exception.retry"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); } catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.info(sm.getString("jndiRealm.exception.retry"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = authenticate(context, username, credentials); } // Release this context release(context); // Return the authenticated Principal (if any) return (principal); } catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request if (containerLog.isDebugEnabled()) containerLog.debug("Returning null principal."); return (null); } } // -------------------------------------------------------- Package Methods // ------------------------------------------------------ Protected Methods /** * Return the Principal associated with the specified username and * credentials, if there is one; otherwise return <code>null</code>. * * @param context The directory context * @param username Username of the Principal to look up * @param credentials Password or other credentials to use in * authenticating this username * * @exception NamingException if a directory server error occurs */ public synchronized Principal authenticate(DirContext context, String username, String credentials) throws NamingException { if (username == null || username.equals("") || credentials == null || credentials.equals("")) { if (containerLog.isDebugEnabled()) containerLog.debug("username null or empty: returning null principal."); return (null); } if (userPatternArray != null) { for (int curUserPattern = 0; curUserPattern < userPatternFormatArray.length; curUserPattern++) { // Retrieve user information User user = getUser(context, username, credentials, curUserPattern); if (user != null) { try { // Check the user's credentials if (checkCredentials(context, user, credentials)) { // Search for additional roles List<String> roles = getRoles(context, user); if (containerLog.isDebugEnabled()) { Iterator<String> it = roles.iterator(); // TODO: Use a single log message while (it.hasNext()) { containerLog.debug("Found role: " + it.next()); } } return (new GenericPrincipal(username, credentials, roles)); } } catch (InvalidNameException ine) { // Log the problem for posterity containerLog.warn(sm.getString("jndiRealm.exception"), ine); // ignore; this is probably due to a name not fitting // the search path format exactly, as in a fully- // qualified name being munged into a search path // that already contains cn= or vice-versa } } } return null; } else { // Retrieve user information User user = getUser(context, username, credentials); if (user == null) return (null); // Check the user's credentials if (!checkCredentials(context, user, credentials)) return (null); // Search for additional roles List<String> roles = getRoles(context, user); if (containerLog.isDebugEnabled()) { Iterator<String> it = roles.iterator(); // TODO: Use a single log message while (it.hasNext()) { containerLog.debug("Found role: " + it.next()); } } // Create and return a suitable Principal for this user return (new GenericPrincipal(username, credentials, roles)); } } /** * Return a User object containing information about the user * with the specified username, if found in the directory; * otherwise return <code>null</code>. * * @param context The directory context * @param username Username to be looked up * * @exception NamingException if a directory server error occurs * * @see #getUser(DirContext, String, String, int) */ protected User getUser(DirContext context, String username) throws NamingException { return getUser(context, username, null, -1); } /** * Return a User object containing information about the user * with the specified username, if found in the directory; * otherwise return <code>null</code>. * * @param context The directory context * @param username Username to be looked up * @param credentials User credentials (optional) * * @exception NamingException if a directory server error occurs * * @see #getUser(DirContext, String, String, int) */ protected User getUser(DirContext context, String username, String credentials) throws NamingException { return getUser(context, username, credentials, -1); } /** * Return a User object containing information about the user * with the specified username, if found in the directory; * otherwise return <code>null</code>. * * If the <code>userPassword</code> configuration attribute is * specified, the value of that attribute is retrieved from the * user's directory entry. If the <code>userRoleName</code> * configuration attribute is specified, all values of that * attribute are retrieved from the directory entry. * * @param context The directory context * @param username Username to be looked up * @param credentials User credentials (optional) * @param curUserPattern Index into userPatternFormatArray * * @exception NamingException if a directory server error occurs */ protected User getUser(DirContext context, String username, String credentials, int curUserPattern) throws NamingException { User user = null; // Get attributes to retrieve from user entry ArrayList<String> list = new ArrayList<>(); if (userPassword != null) list.add(userPassword); if (userRoleName != null) list.add(userRoleName); if (userRoleAttribute != null) { list.add(userRoleAttribute); } String[] attrIds = new String[list.size()]; list.toArray(attrIds); // Use pattern or search for user entry if (userPatternFormatArray != null && curUserPattern >= 0) { user = getUserByPattern(context, username, credentials, attrIds, curUserPattern); } else { user = getUserBySearch(context, username, attrIds); } return user; } /** * Use the distinguished name to locate the directory * entry for the user with the specified username and * return a User object; otherwise return <code>null</code>. * * @param context The directory context * @param username The username * @param attrIds String[]containing names of attributes to * @param dn Distinguished name of the user * retrieve. * * @exception NamingException if a directory server error occurs */ protected User getUserByPattern(DirContext context, String username, String[] attrIds, String dn) throws NamingException { // If no attributes are requested, no need to look for them if (attrIds == null || attrIds.length == 0) { return new User(username, dn, null, null,null); } // Get required attributes from user entry Attributes attrs = null; try { attrs = context.getAttributes(dn, attrIds); } catch (NameNotFoundException e) { return (null); } if (attrs == null) return (null); // Retrieve value of userPassword String password = null; if (userPassword != null) password = getAttributeValue(userPassword, attrs); String userRoleAttrValue = null; if (userRoleAttribute != null) { userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs); } // Retrieve values of userRoleName attribute ArrayList<String> roles = null; if (userRoleName != null) roles = addAttributeValues(userRoleName, attrs, roles); return new User(username, dn, password, roles, userRoleAttrValue); } /** * Use the <code>UserPattern</code> configuration attribute to * locate the directory entry for the user with the specified * username and return a User object; otherwise return * <code>null</code>. * * @param context The directory context * @param username The username * @param credentials User credentials (optional) * @param attrIds String[]containing names of attributes to * @param curUserPattern Index into userPatternFormatArray * * @exception NamingException if a directory server error occurs * @see #getUserByPattern(DirContext, String, String[], String) */ protected User getUserByPattern(DirContext context, String username, String credentials, String[] attrIds, int curUserPattern) throws NamingException { User user = null; if (username == null || userPatternFormatArray[curUserPattern] == null) return (null); // Form the dn from the user pattern String dn = userPatternFormatArray[curUserPattern].format(new String[] { username }); try { user = getUserByPattern(context, username, attrIds, dn); } catch (NameNotFoundException e) { return (null); } catch (NamingException e) { // If the getUserByPattern() call fails, try it again with the // credentials of the user that we're searching for try { userCredentialsAdd(context, dn, credentials); user = getUserByPattern(context, username, attrIds, dn); } finally { userCredentialsRemove(context); } } return user; } /** * Search the directory to return a User object containing * information about the user with the specified username, if * found in the directory; otherwise return <code>null</code>. * * @param context The directory context * @param username The username * @param attrIds String[]containing names of attributes to retrieve. * * @exception NamingException if a directory server error occurs */ protected User getUserBySearch(DirContext context, String username, String[] attrIds) throws NamingException { if (username == null || userSearchFormat == null) return (null); // Form the search filter String filter = userSearchFormat.format(new String[] { username }); // Set up the search controls SearchControls constraints = new SearchControls(); if (userSubtree) { constraints.setSearchScope(SearchControls.SUBTREE_SCOPE); } else { constraints.setSearchScope(SearchControls.ONELEVEL_SCOPE); } constraints.setCountLimit(sizeLimit); constraints.setTimeLimit(timeLimit); // Specify the attributes to be retrieved if (attrIds == null) attrIds = new String[0]; constraints.setReturningAttributes(attrIds); NamingEnumeration<SearchResult> results = context.search(userBase, filter, constraints); // Fail if no entries found try { if (results == null || !results.hasMore()) { return (null); } } catch (PartialResultException ex) { if (!adCompat) throw ex; else return (null); } // Get result for the first entry found SearchResult result = results.next(); // Check no further entries were found try { if (results.hasMore()) { if(containerLog.isInfoEnabled()) containerLog.info("username " + username + " has multiple entries"); return (null); } } catch (PartialResultException ex) { if (!adCompat) throw ex; } String dn = getDistinguishedName(context, userBase, result); if (containerLog.isTraceEnabled()) containerLog.trace(" entry found for " + username + " with dn " + dn); // Get the entry's attributes Attributes attrs = result.getAttributes(); if (attrs == null) return null; // Retrieve value of userPassword String password = null; if (userPassword != null) password = getAttributeValue(userPassword, attrs); String userRoleAttrValue = null; if (userRoleAttribute != null) { userRoleAttrValue = getAttributeValue(userRoleAttribute, attrs); } // Retrieve values of userRoleName attribute ArrayList<String> roles = null; if (userRoleName != null) roles = addAttributeValues(userRoleName, attrs, roles); return new User(username, dn, password, roles, userRoleAttrValue); } /** * Check whether the given User can be authenticated with the * given credentials. If the <code>userPassword</code> * configuration attribute is specified, the credentials * previously retrieved from the directory are compared explicitly * with those presented by the user. Otherwise the presented * credentials are checked by binding to the directory as the * user. * * @param context The directory context * @param user The User to be authenticated * @param credentials The credentials presented by the user * * @exception NamingException if a directory server error occurs */ protected boolean checkCredentials(DirContext context, User user, String credentials) throws NamingException { boolean validated = false; if (userPassword == null) { validated = bindAsUser(context, user, credentials); } else { validated = compareCredentials(context, user, credentials); } if (containerLog.isTraceEnabled()) { if (validated) { containerLog.trace(sm.getString("jndiRealm.authenticateSuccess", user.getUserName())); } else { containerLog.trace(sm.getString("jndiRealm.authenticateFailure", user.getUserName())); } } return (validated); } /** * Check whether the credentials presented by the user match those * retrieved from the directory. * * @param context The directory context * @param info The User to be authenticated * @param credentials Authentication credentials * * @exception NamingException if a directory server error occurs */ protected boolean compareCredentials(DirContext context, User info, String credentials) throws NamingException { if (info == null || credentials == null) return (false); String password = info.getPassword(); if (password == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) containerLog.trace(" validating credentials"); boolean validated = false; if (hasMessageDigest()) { // Some directories prefix the password with the hash type // The string is in a format compatible with Base64.encode not // the Hex encoding of the parent class. if (password.startsWith("{MD5}") || password.startsWith("{SHA}")) { /* sync since super.digest() does this same thing */ synchronized (this) { password = password.substring(5); md.reset(); md.update(credentials.getBytes(StandardCharsets.ISO_8859_1)); byte[] encoded = Base64.encodeBase64(md.digest()); String digestedPassword = new String(encoded, StandardCharsets.ISO_8859_1); validated = password.equals(digestedPassword); } } else if (password.startsWith("{SSHA}")) { // Bugzilla 32938 /* sync since super.digest() does this same thing */ synchronized (this) { password = password.substring(6); md.reset(); md.update(credentials.getBytes(StandardCharsets.ISO_8859_1)); // Decode stored password. byte[] decoded = Base64.decodeBase64(password); // Split decoded password into hash and salt. final int saltpos = 20; byte[] hash = new byte[saltpos]; System.arraycopy(decoded, 0, hash, 0, saltpos); md.update(decoded, saltpos, decoded.length - saltpos); byte[] dp = md.digest(); validated = Arrays.equals(dp, hash); } // End synchronized(this) block } else { // Hex hashes should be compared case-insensitive validated = (digest(credentials).equalsIgnoreCase(password)); } } else validated = (digest(credentials).equals(password)); return (validated); } /** * Check credentials by binding to the directory as the user * * @param context The directory context * @param user The User to be authenticated * @param credentials Authentication credentials * * @exception NamingException if a directory server error occurs */ protected boolean bindAsUser(DirContext context, User user, String credentials) throws NamingException { if (credentials == null || user == null) return (false); String dn = user.getDN(); if (dn == null) return (false); // Validate the credentials specified by the user if (containerLog.isTraceEnabled()) { containerLog.trace(" validating credentials by binding as the user"); } userCredentialsAdd(context, dn, credentials); // Elicit an LDAP bind operation boolean validated = false; try { if (containerLog.isTraceEnabled()) { containerLog.trace(" binding as " + dn); } context.getAttributes("", null); validated = true; } catch (AuthenticationException e) { if (containerLog.isTraceEnabled()) { containerLog.trace(" bind attempt failed"); } } userCredentialsRemove(context); return (validated); } /** * Configure the context to use the provided credentials for * authentication. * * @param context DirContext to configure * @param dn Distinguished name of user * @param credentials Credentials of user */ private void userCredentialsAdd(DirContext context, String dn, String credentials) throws NamingException { // Set up security environment to bind as the user context.addToEnvironment(Context.SECURITY_PRINCIPAL, dn); context.addToEnvironment(Context.SECURITY_CREDENTIALS, credentials); } /** * Configure the context to use {@link #connectionName} and * {@link #connectionPassword} if specified or an anonymous connection if * those attributes are not specified. * * @param context DirContext to configure */ private void userCredentialsRemove(DirContext context) throws NamingException { // Restore the original security environment if (connectionName != null) { context.addToEnvironment(Context.SECURITY_PRINCIPAL, connectionName); } else { context.removeFromEnvironment(Context.SECURITY_PRINCIPAL); } if (connectionPassword != null) { context.addToEnvironment(Context.SECURITY_CREDENTIALS, connectionPassword); } else { context.removeFromEnvironment(Context.SECURITY_CREDENTIALS); } } /** * Return a List of roles associated with the given User. Any * roles present in the user's directory entry are supplemented by * a directory search. If no roles are associated with this user, * a zero-length List is returned. * * @param context The directory context we are searching * @param user The User to be checked * * @exception NamingException if a directory server error occurs */ protected List<String> getRoles(DirContext context, User user) throws NamingException { if (user == null) return (null); String dn = user.getDN(); String username = user.getUserName(); String userRoleId = user.getUserRoleId(); if (dn == null || username == null) return (null); if (containerLog.isTraceEnabled()) containerLog.trace(" getRoles(" + dn + ")"); // Start with roles retrieved from the user entry List<String> list = new ArrayList<>(); List<String> userRoles = user.getRoles(); if (userRoles != null) { list.addAll(userRoles); } if (commonRole != null) list.add(commonRole); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found " + list.size() + " user internal roles"); for (int i=0; i<list.size(); i++) containerLog.trace( " Found user internal role " + list.get(i)); } // Are we configured to do role searches? if ((roleFormat == null) || (roleName == null)) return (list); // Set up parameters for an appropriate search String filter = roleFormat.format(new String[] { doRFC2254Encoding(dn), username, userRoleId }); SearchControls controls = new SearchControls(); if (roleSubtree) controls.setSearchScope(SearchControls.SUBTREE_SCOPE); else controls.setSearchScope(SearchControls.ONELEVEL_SCOPE); controls.setReturningAttributes(new String[] {roleName}); String base = null; if (roleBaseFormat != null) { NameParser np = context.getNameParser(""); Name name = np.parse(dn); String nameParts[] = new String[name.size()]; for (int i = 0; i < name.size(); i++) { nameParts[i] = name.get(i); } base = roleBaseFormat.format(nameParts); } // Perform the configured search and process the results NamingEnumeration<SearchResult> results = null; try { if (roleSearchAsUser) { userCredentialsAdd(context, dn, user.getPassword()); } results = context.search(base, filter, controls); } finally { if (roleSearchAsUser) { userCredentialsRemove(context); } } if (results == null) return (list); // Should never happen, but just in case ... HashMap<String, String> groupMap = new HashMap<>(); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) continue; String dname = getDistinguishedName(context, roleBase, result); String name = getAttributeValue(roleName, attrs); if (name != null && dname != null) { groupMap.put(dname, name); } } } catch (PartialResultException ex) { if (!adCompat) throw ex; } Set<String> keys = groupMap.keySet(); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found " + keys.size() + " direct roles"); for (String key: keys) { containerLog.trace( " Found direct role " + key + " -> " + groupMap.get(key)); } } // if nested group search is enabled, perform searches for nested groups until no new group is found if (getRoleNested()) { // The following efficient algorithm is known as memberOf Algorithm, as described in "Practices in // Directory Groups". It avoids group slurping and handles cyclic group memberships as well. // See http://middleware.internet2.edu/dir/ for details Map<String, String> newGroups = new HashMap<>(groupMap); while (!newGroups.isEmpty()) { Map<String, String> newThisRound = new HashMap<>(); // Stores the groups we find in this iteration for (Entry<String, String> group : newGroups.entrySet()) { filter = roleFormat.format(new String[] { group.getKey(), group.getValue(), group.getValue() }); if (containerLog.isTraceEnabled()) { containerLog.trace("Perform a nested group search with base "+ roleBase + " and filter " + filter); } results = context.search(roleBase, filter, controls); try { while (results.hasMore()) { SearchResult result = results.next(); Attributes attrs = result.getAttributes(); if (attrs == null) continue; String dname = getDistinguishedName(context, roleBase, result); String name = getAttributeValue(roleName, attrs); if (name != null && dname != null && !groupMap.keySet().contains(dname)) { groupMap.put(dname, name); newThisRound.put(dname, name); if (containerLog.isTraceEnabled()) { containerLog.trace(" Found nested role " + dname + " -> " + name); } } } } catch (PartialResultException ex) { if (!adCompat) throw ex; } } newGroups = newThisRound; } } list.addAll(groupMap.values()); return list; } /** * Return a String representing the value of the specified attribute. * * @param attrId Attribute name * @param attrs Attributes containing the required value * * @exception NamingException if a directory server error occurs */ private String getAttributeValue(String attrId, Attributes attrs) throws NamingException { if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving attribute " + attrId); if (attrId == null || attrs == null) return null; Attribute attr = attrs.get(attrId); if (attr == null) return (null); Object value = attr.get(); if (value == null) return (null); String valueString = null; if (value instanceof byte[]) valueString = new String((byte[]) value); else valueString = value.toString(); return valueString; } /** * Add values of a specified attribute to a list * * @param attrId Attribute name * @param attrs Attributes containing the new values * @param values ArrayList containing values found so far * * @exception NamingException if a directory server error occurs */ private ArrayList<String> addAttributeValues(String attrId, Attributes attrs, ArrayList<String> values) throws NamingException{ if (containerLog.isTraceEnabled()) containerLog.trace(" retrieving values for attribute " + attrId); if (attrId == null || attrs == null) return values; if (values == null) values = new ArrayList<>(); Attribute attr = attrs.get(attrId); if (attr == null) return (values); NamingEnumeration<?> e = attr.getAll(); try { while(e.hasMore()) { String value = (String)e.next(); values.add(value); } } catch (PartialResultException ex) { if (!adCompat) throw ex; } return values; } /** * Close any open connection to the directory server for this Realm. * * @param context The directory context to be closed */ protected void close(DirContext context) { // Do nothing if there is no opened connection if (context == null) return; // Close our opened connection try { if (containerLog.isDebugEnabled()) containerLog.debug("Closing directory context"); context.close(); } catch (NamingException e) { containerLog.error(sm.getString("jndiRealm.close"), e); } this.context = 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) { return (null); } /** * Return the Principal associated with the given user name. */ @Override protected Principal getPrincipal(String username) { return getPrincipal(username, null); } @Override protected Principal getPrincipal(String username, GSSCredential gssCredential) { DirContext context = null; Principal principal = null; try { // Ensure that we have a directory context available context = open(); // Occasionally the directory context will timeout. Try one more // time before giving up. try { // Authenticate the specified username if possible principal = getPrincipal(context, username, gssCredential); } catch (CommunicationException e) { // log the exception so we know it's there. containerLog.info(sm.getString("jndiRealm.exception.retry"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); } catch (ServiceUnavailableException e) { // log the exception so we know it's there. containerLog.info(sm.getString("jndiRealm.exception.retry"), e); // close the connection so we know it will be reopened. if (context != null) close(context); // open a new directory context. context = open(); // Try the authentication again. principal = getPrincipal(context, username, gssCredential); } // Release this context release(context); // Return the authenticated Principal (if any) return (principal); } catch (NamingException e) { // Log the problem for posterity containerLog.error(sm.getString("jndiRealm.exception"), e); // Close the connection so that it gets reopened next time if (context != null) close(context); // Return "not authenticated" for this request return (null); } } /** * Return the Principal associated with the given user name. */ protected synchronized Principal getPrincipal(DirContext context, String username, GSSCredential gssCredential) throws NamingException { User user = null; List<String> roles = null; Hashtable<?, ?> preservedEnvironment = null; try { if (gssCredential != null && isUseDelegatedCredential()) { // Preserve the current context environment parameters preservedEnvironment = context.getEnvironment(); // Set up context context.addToEnvironment( Context.SECURITY_AUTHENTICATION, "GSSAPI"); context.addToEnvironment( "javax.security.sasl.server.authentication", "true"); context.addToEnvironment( "javax.security.sasl.qop", "auth-conf"); // Note: Subject already set in SPNEGO authenticator so no need // for Subject.doAs() here } user = getUser(context, username); if (user != null) { roles = getRoles(context, user); } } finally { restoreEnvironmentParameter(context, Context.SECURITY_AUTHENTICATION, preservedEnvironment); restoreEnvironmentParameter(context, "javax.security.sasl.server.authentication", preservedEnvironment); restoreEnvironmentParameter(context, "javax.security.sasl.qop", preservedEnvironment); } if (user != null) { return new GenericPrincipal(user.getUserName(), user.getPassword(), roles, null, null, gssCredential); } return null; } private void restoreEnvironmentParameter(DirContext context, String parameterName, Hashtable<?, ?> preservedEnvironment) { try { context.removeFromEnvironment(parameterName); if (preservedEnvironment != null && preservedEnvironment.containsKey(parameterName)) { context.addToEnvironment(parameterName, preservedEnvironment.get(parameterName)); } } catch (NamingException e) { // Ignore } } /** * Open (if necessary) and return a connection to the configured * directory server for this Realm. * * @exception NamingException if a directory server error occurs */ protected DirContext open() throws NamingException { // Do nothing if there is a directory server connection already open if (context != null) return (context); try { // Ensure that we have a directory context available context = new InitialDirContext(getDirectoryContextEnvironment()); } catch (Exception e) { connectionAttempt = 1; // log the first exception. containerLog.info(sm.getString("jndiRealm.exception.retry"), e); // Try connecting to the alternate url. context = new InitialDirContext(getDirectoryContextEnvironment()); } finally { // reset it in case the connection times out. // the primary may come back. connectionAttempt = 0; } return (context); } /** * Create our directory context configuration. * * @return java.util.Hashtable the configuration for the directory context. */ protected Hashtable<String,String> getDirectoryContextEnvironment() { Hashtable<String,String> env = new Hashtable<>(); // Configure our directory context environment. if (containerLog.isDebugEnabled() && connectionAttempt == 0) containerLog.debug("Connecting to URL " + connectionURL); else if (containerLog.isDebugEnabled() && connectionAttempt > 0) containerLog.debug("Connecting to URL " + alternateURL); env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory); if (connectionName != null) env.put(Context.SECURITY_PRINCIPAL, connectionName); if (connectionPassword != null) env.put(Context.SECURITY_CREDENTIALS, connectionPassword); if (connectionURL != null && connectionAttempt == 0) env.put(Context.PROVIDER_URL, connectionURL); else if (alternateURL != null && connectionAttempt > 0) env.put(Context.PROVIDER_URL, alternateURL); if (authentication != null) env.put(Context.SECURITY_AUTHENTICATION, authentication); if (protocol != null) env.put(Context.SECURITY_PROTOCOL, protocol); if (referrals != null) env.put(Context.REFERRAL, referrals); if (derefAliases != null) env.put(JNDIRealm.DEREF_ALIASES, derefAliases); if (connectionTimeout != null) env.put("com.sun.jndi.ldap.connect.timeout", connectionTimeout); return env; } /** * Release our use of this connection so that it can be recycled. * * @param context The directory context to release */ protected void release(DirContext context) { // NO-OP since we are not pooling anything } // ------------------------------------------------------ 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 { // Validate that we can open our connection try { open(); } catch (NamingException e) { throw new LifecycleException(sm.getString("jndiRealm.open"), e); } super.startInternal(); } /** * 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 { super.stopInternal(); // Close any open directory server connection close(this.context); } /** * Given a string containing LDAP patterns for user locations (separated by * parentheses in a pseudo-LDAP search string format - * "(location1)(location2)", returns an array of those paths. Real LDAP * search strings are supported as well (though only the "|" "OR" type). * * @param userPatternString - a string LDAP search paths surrounded by * parentheses */ protected String[] parseUserPatternString(String userPatternString) { if (userPatternString != null) { ArrayList<String> pathList = new ArrayList<>(); int startParenLoc = userPatternString.indexOf('('); if (startParenLoc == -1) { // no parens here; return whole thing return new String[] {userPatternString}; } int startingPoint = 0; while (startParenLoc > -1) { int endParenLoc = 0; // weed out escaped open parens and parens enclosing the // whole statement (in the case of valid LDAP search // strings: (|(something)(somethingelse)) while ( (userPatternString.charAt(startParenLoc + 1) == '|') || (startParenLoc != 0 && userPatternString.charAt(startParenLoc - 1) == '\\') ) { startParenLoc = userPatternString.indexOf("(", startParenLoc+1); } endParenLoc = userPatternString.indexOf(")", startParenLoc+1); // weed out escaped end-parens while (userPatternString.charAt(endParenLoc - 1) == '\\') { endParenLoc = userPatternString.indexOf(")", endParenLoc+1); } String nextPathPart = userPatternString.substring (startParenLoc+1, endParenLoc); pathList.add(nextPathPart); startingPoint = endParenLoc+1; startParenLoc = userPatternString.indexOf('(', startingPoint); } return pathList.toArray(new String[] {}); } return null; } /** * Given an LDAP search string, returns the string with certain characters * escaped according to RFC 2254 guidelines. * The character mapping is as follows: * char -> Replacement * --------------------------- * * -> \2a * ( -> \28 * ) -> \29 * \ -> \5c * \0 -> \00 * @param inString string to escape according to RFC 2254 guidelines * @return String the escaped/encoded result */ protected String doRFC2254Encoding(String inString) { StringBuilder buf = new StringBuilder(inString.length()); for (int i = 0; i < inString.length(); i++) { char c = inString.charAt(i); switch (c) { case '\\': buf.append("\\5c"); break; case '*': buf.append("\\2a"); break; case '(': buf.append("\\28"); break; case ')': buf.append("\\29"); break; case '\0': buf.append("\\00"); break; default: buf.append(c); break; } } return buf.toString(); } /** * Returns the distinguished name of a search result. * * @param context Our DirContext * @param base The base DN * @param result The search result * @return String containing the distinguished name */ protected String getDistinguishedName(DirContext context, String base, SearchResult result) throws NamingException { // Get the entry's distinguished name. For relative results, this means // we need to composite a name with the base name, the context name, and // the result name. For non-relative names, use the returned name. if (result.isRelative()) { if (containerLog.isTraceEnabled()) { containerLog.trace(" search returned relative name: " + result.getName()); } NameParser parser = context.getNameParser(""); Name contextName = parser.parse(context.getNameInNamespace()); Name baseName = parser.parse(base); // Bugzilla 32269 Name entryName = parser.parse(new CompositeName(result.getName()).get(0)); Name name = contextName.addAll(baseName); name = name.addAll(entryName); return name.toString(); } else { String absoluteName = result.getName(); if (containerLog.isTraceEnabled()) containerLog.trace(" search returned absolute name: " + result.getName()); try { // Normalize the name by running it through the name parser. NameParser parser = context.getNameParser(""); URI userNameUri = new URI(absoluteName); String pathComponent = userNameUri.getPath(); // Should not ever have an empty path component, since that is /{DN} if (pathComponent.length() < 1 ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } Name name = parser.parse(pathComponent.substring(1)); return name.toString(); } catch ( URISyntaxException e ) { throw new InvalidNameException( "Search returned unparseable absolute name: " + absoluteName ); } } } // ------------------------------------------------------ Private Classes /** * A protected class representing a User */ protected static class User { private final String username; private final String dn; private final String password; private final List<String> roles; private final String userRoleId; public User(String username, String dn, String password, List<String> roles, String userRoleId) { this.username = username; this.dn = dn; this.password = password; if (roles == null) { this.roles = Collections.emptyList(); } else { this.roles = Collections.unmodifiableList(roles); } this.userRoleId = userRoleId; } public String getUserName() { return username; } public String getDN() { return dn; } public String getPassword() { return password; } public List<String> getRoles() { return roles; } public String getUserRoleId() { return userRoleId; } } }
55,798
Bug 55798 Enabling Manager App - process and description is inadequate
null
resolved fixed
13c6551
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-20T10:07:51Z
2013-11-20T04:00:00Z
java/org/apache/catalina/users/MemoryUserDatabase.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.users; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.util.HashMap; import java.util.Iterator; import org.apache.catalina.Globals; import org.apache.catalina.Group; import org.apache.catalina.Role; import org.apache.catalina.User; import org.apache.catalina.UserDatabase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.digester.AbstractObjectCreationFactory; import org.apache.tomcat.util.digester.Digester; import org.apache.tomcat.util.res.StringManager; import org.xml.sax.Attributes; /** * <p>Concrete implementation of {@link UserDatabase} that loads all * defined users, groups, and roles into an in-memory data structure, * and uses a specified XML file for its persistent storage.</p> * * @author Craig R. McClanahan * @version $Id$ * @since 4.1 */ public class MemoryUserDatabase implements UserDatabase { private static final Log log = LogFactory.getLog(MemoryUserDatabase.class); // ----------------------------------------------------------- Constructors /** * Create a new instance with default values. */ public MemoryUserDatabase() { this(null); } /** * Create a new instance with the specified values. * * @param id Unique global identifier of this user database */ public MemoryUserDatabase(String id) { this.id = id; } // ----------------------------------------------------- Instance Variables /** * The set of {@link Group}s defined in this database, keyed by * group name. */ protected final HashMap<String,Group> groups = new HashMap<>(); /** * The unique global identifier of this user database. */ protected final String id; /** * The relative (to <code>catalina.base</code>) or absolute pathname to * the XML file in which we will save our persistent information. */ protected String pathname = "conf/tomcat-users.xml"; /** * The relative or absolute pathname to the file in which our old * information is stored while renaming is in progress. */ protected String pathnameOld = pathname + ".old"; /** * The relative or absolute pathname of the file in which we write * our new information prior to renaming. */ protected String pathnameNew = pathname + ".new"; /** * A flag, indicating if the user database is read only. */ protected boolean readonly = true; /** * The set of {@link Role}s defined in this database, keyed by * role name. */ protected final HashMap<String,Role> roles = new HashMap<>(); /** * The string manager for this package. */ private static final StringManager sm = StringManager.getManager(Constants.Package); /** * The set of {@link User}s defined in this database, keyed by * user name. */ protected final HashMap<String,User> users = new HashMap<>(); // ------------------------------------------------------------- Properties /** * Return the set of {@link Group}s defined in this user database. */ @Override public Iterator<Group> getGroups() { synchronized (groups) { return (groups.values().iterator()); } } /** * Return the unique global identifier of this user database. */ @Override public String getId() { return (this.id); } /** * Return the relative or absolute pathname to the persistent storage file. */ public String getPathname() { return (this.pathname); } /** * Set the relative or absolute pathname to the persistent storage file. * * @param pathname The new pathname */ public void setPathname(String pathname) { this.pathname = pathname; this.pathnameOld = pathname + ".old"; this.pathnameNew = pathname + ".new"; } /** * Returning the readonly status of the user database */ public boolean getReadonly() { return (this.readonly); } /** * Setting the readonly status of the user database * * @param readonly the new status */ public void setReadonly(boolean readonly) { this.readonly = readonly; } /** * Return the set of {@link Role}s defined in this user database. */ @Override public Iterator<Role> getRoles() { synchronized (roles) { return (roles.values().iterator()); } } /** * Return the set of {@link User}s defined in this user database. */ @Override public Iterator<User> getUsers() { synchronized (users) { return (users.values().iterator()); } } // --------------------------------------------------------- Public Methods /** * Finalize access to this user database. * * @exception Exception if any exception is thrown during closing */ @Override public void close() throws Exception { save(); synchronized (groups) { synchronized (users) { users.clear(); groups.clear(); } } } /** * Create and return a new {@link Group} defined in this user database. * * @param groupname The group name of the new group (must be unique) * @param description The description of this group */ @Override public Group createGroup(String groupname, String description) { if (groupname == null || groupname.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullGroup"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryGroup group = new MemoryGroup(this, groupname, description); synchronized (groups) { groups.put(group.getGroupname(), group); } return (group); } /** * Create and return a new {@link Role} defined in this user database. * * @param rolename The role name of the new group (must be unique) * @param description The description of this group */ @Override public Role createRole(String rolename, String description) { if (rolename == null || rolename.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullRole"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryRole role = new MemoryRole(this, rolename, description); synchronized (roles) { roles.put(role.getRolename(), role); } return (role); } /** * Create and return a new {@link User} defined in this user database. * * @param username The logon username of the new user (must be unique) * @param password The logon password of the new user * @param fullName The full name of the new user */ @Override public User createUser(String username, String password, String fullName) { if (username == null || username.length() == 0) { String msg = sm.getString("memoryUserDatabase.nullUser"); log.warn(msg); throw new IllegalArgumentException(msg); } MemoryUser user = new MemoryUser(this, username, password, fullName); synchronized (users) { users.put(user.getUsername(), user); } return (user); } /** * Return the {@link Group} with the specified group name, if any; * otherwise return <code>null</code>. * * @param groupname Name of the group to return */ @Override public Group findGroup(String groupname) { synchronized (groups) { return groups.get(groupname); } } /** * Return the {@link Role} with the specified role name, if any; * otherwise return <code>null</code>. * * @param rolename Name of the role to return */ @Override public Role findRole(String rolename) { synchronized (roles) { return roles.get(rolename); } } /** * Return the {@link User} with the specified user name, if any; * otherwise return <code>null</code>. * * @param username Name of the user to return */ @Override public User findUser(String username) { synchronized (users) { return users.get(username); } } /** * Initialize access to this user database. * * @exception Exception if any exception is thrown during opening */ @Override public void open() throws Exception { synchronized (groups) { synchronized (users) { // Erase any previous groups and users users.clear(); groups.clear(); roles.clear(); // Construct a reader for the XML input file (if it exists) File file = new File(pathname); if (!file.isAbsolute()) { file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (!file.exists()) { return; } // Construct a digester to read the XML input file Digester digester = new Digester(); try { digester.setFeature( "http://apache.org/xml/features/allow-java-encodings", true); } catch (Exception e) { log.warn(sm.getString("memoryUserDatabase.xmlFeatureEncoding"), e); } digester.addFactoryCreate ("tomcat-users/group", new MemoryGroupCreationFactory(this), true); digester.addFactoryCreate ("tomcat-users/role", new MemoryRoleCreationFactory(this), true); digester.addFactoryCreate ("tomcat-users/user", new MemoryUserCreationFactory(this), true); // Parse the XML input file to load this database FileInputStream fis = null; try { fis = new FileInputStream(file); digester.parse(fis); } finally { if (fis != null) { try { fis.close(); } catch (IOException ioe) { // Ignore } } } } } } /** * Remove the specified {@link Group} from this user database. * * @param group The group to be removed */ @Override public void removeGroup(Group group) { synchronized (groups) { Iterator<User> users = getUsers(); while (users.hasNext()) { User user = users.next(); user.removeGroup(group); } groups.remove(group.getGroupname()); } } /** * Remove the specified {@link Role} from this user database. * * @param role The role to be removed */ @Override public void removeRole(Role role) { synchronized (roles) { Iterator<Group> groups = getGroups(); while (groups.hasNext()) { Group group = groups.next(); group.removeRole(role); } Iterator<User> users = getUsers(); while (users.hasNext()) { User user = users.next(); user.removeRole(role); } roles.remove(role.getRolename()); } } /** * Remove the specified {@link User} from this user database. * * @param user The user to be removed */ @Override public void removeUser(User user) { synchronized (users) { users.remove(user.getUsername()); } } /** * Check for permissions to save this user database to persistent storage * location. */ public boolean isWriteable() { File file = new File(pathname); if (!file.isAbsolute()) { file = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } File dir = file.getParentFile(); return dir.exists() && dir.isDirectory() && dir.canWrite(); } /** * Save any updated information to the persistent storage location for * this user database. * * @exception Exception if any exception is thrown during saving */ @Override public void save() throws Exception { if (getReadonly()) { log.error(sm.getString("memoryUserDatabase.readOnly")); return; } if (!isWriteable()) { log.warn(sm.getString("memoryUserDatabase.notPersistable")); return; } // Write out contents to a temporary file File fileNew = new File(pathnameNew); if (!fileNew.isAbsolute()) { fileNew = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameNew); } PrintWriter writer = null; try { // Configure our PrintWriter FileOutputStream fos = new FileOutputStream(fileNew); OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF8"); writer = new PrintWriter(osw); // Print the file prolog writer.println("<?xml version='1.0' encoding='utf-8'?>"); writer.println("<tomcat-users>"); // Print entries for each defined role, group, and user Iterator<?> values = null; values = getRoles(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getGroups(); while (values.hasNext()) { writer.print(" "); writer.println(values.next()); } values = getUsers(); while (values.hasNext()) { writer.print(" "); writer.println(((MemoryUser) values.next()).toXml()); } // Print the file epilog writer.println("</tomcat-users>"); // Check for errors that occurred while printing if (writer.checkError()) { writer.close(); fileNew.delete(); throw new IOException (sm.getString("memoryUserDatabase.writeException", fileNew.getAbsolutePath())); } writer.close(); } catch (IOException e) { if (writer != null) { writer.close(); } fileNew.delete(); throw e; } // Perform the required renames to permanently save this file File fileOld = new File(pathnameOld); if (!fileOld.isAbsolute()) { fileOld = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathnameOld); } fileOld.delete(); File fileOrig = new File(pathname); if (!fileOrig.isAbsolute()) { fileOrig = new File(System.getProperty(Globals.CATALINA_BASE_PROP), pathname); } if (fileOrig.exists()) { fileOld.delete(); if (!fileOrig.renameTo(fileOld)) { throw new IOException (sm.getString("memoryUserDatabase.renameOld", fileOld.getAbsolutePath())); } } if (!fileNew.renameTo(fileOrig)) { if (fileOld.exists()) { fileOld.renameTo(fileOrig); } throw new IOException (sm.getString("memoryUserDatabase.renameNew", fileOrig.getAbsolutePath())); } fileOld.delete(); } /** * Return a String representation of this UserDatabase. */ @Override public String toString() { StringBuilder sb = new StringBuilder("MemoryUserDatabase[id="); sb.append(this.id); sb.append(",pathname="); sb.append(pathname); sb.append(",groupCount="); sb.append(this.groups.size()); sb.append(",roleCount="); sb.append(this.roles.size()); sb.append(",userCount="); sb.append(this.users.size()); sb.append("]"); return (sb.toString()); } } /** * Digester object creation factory for group instances. */ class MemoryGroupCreationFactory extends AbstractObjectCreationFactory { public MemoryGroupCreationFactory(MemoryUserDatabase database) { this.database = database; } @Override public Object createObject(Attributes attributes) { String groupname = attributes.getValue("groupname"); if (groupname == null) { groupname = attributes.getValue("name"); } String description = attributes.getValue("description"); String roles = attributes.getValue("roles"); Group group = database.createGroup(groupname, description); if (roles != null) { while (roles.length() > 0) { String rolename = null; int comma = roles.indexOf(','); if (comma >= 0) { rolename = roles.substring(0, comma).trim(); roles = roles.substring(comma + 1); } else { rolename = roles.trim(); roles = ""; } if (rolename.length() > 0) { Role role = database.findRole(rolename); if (role == null) { role = database.createRole(rolename, null); } group.addRole(role); } } } return (group); } private final MemoryUserDatabase database; } /** * Digester object creation factory for role instances. */ class MemoryRoleCreationFactory extends AbstractObjectCreationFactory { public MemoryRoleCreationFactory(MemoryUserDatabase database) { this.database = database; } @Override public Object createObject(Attributes attributes) { String rolename = attributes.getValue("rolename"); if (rolename == null) { rolename = attributes.getValue("name"); } String description = attributes.getValue("description"); Role role = database.createRole(rolename, description); return (role); } private final MemoryUserDatabase database; } /** * Digester object creation factory for user instances. */ class MemoryUserCreationFactory extends AbstractObjectCreationFactory { public MemoryUserCreationFactory(MemoryUserDatabase database) { this.database = database; } @Override public Object createObject(Attributes attributes) { String username = attributes.getValue("username"); if (username == null) { username = attributes.getValue("name"); } String password = attributes.getValue("password"); String fullName = attributes.getValue("fullName"); if (fullName == null) { fullName = attributes.getValue("fullname"); } String groups = attributes.getValue("groups"); String roles = attributes.getValue("roles"); User user = database.createUser(username, password, fullName); if (groups != null) { while (groups.length() > 0) { String groupname = null; int comma = groups.indexOf(','); if (comma >= 0) { groupname = groups.substring(0, comma).trim(); groups = groups.substring(comma + 1); } else { groupname = groups.trim(); groups = ""; } if (groupname.length() > 0) { Group group = database.findGroup(groupname); if (group == null) { group = database.createGroup(groupname, null); } user.addGroup(group); } } } if (roles != null) { while (roles.length() > 0) { String rolename = null; int comma = roles.indexOf(','); if (comma >= 0) { rolename = roles.substring(0, comma).trim(); roles = roles.substring(comma + 1); } else { rolename = roles.trim(); roles = ""; } if (rolename.length() > 0) { Role role = database.findRole(rolename); if (role == null) { role = database.createRole(rolename, null); } user.addRole(role); } } } return (user); } private final MemoryUserDatabase database; }
55,804
Bug 55804 SPNEGOAUTHENTICATOR - GSSCredential does not get renewed after RemainingLifeTime is less than zero
In SpnegoAuthenticator, we check for request.getUserPrincipal() if it returns a prinicpal we do not do a fresh authentication. This happens even when the GSSCredential returned by GenericPrincipal has remainingLife time less than zero. This causes issues in delegating the credential as the credential is not valid any more. Can we add additional check to reauthenticate when the credental has expired and put GSSCredential in the same session?
resolved fixed
8f67335
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-11-29T19:25:49Z
2013-11-20T23:26: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.lang.reflect.InvocationTargetException; import java.nio.charset.Charset; import java.security.Principal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.TreeMap; import java.util.concurrent.atomic.AtomicBoolean; import javax.naming.NamingException; import javax.security.auth.Subject; import javax.servlet.AsyncContext; import javax.servlet.DispatcherType; import javax.servlet.FilterChain; import javax.servlet.MultipartConfigElement; import javax.servlet.RequestDispatcher; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletRequest; import javax.servlet.ServletRequestAttributeEvent; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.ServletResponse; import javax.servlet.SessionTrackingMode; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.Part; import org.apache.catalina.Context; import org.apache.catalina.Globals; import org.apache.catalina.Host; import org.apache.catalina.Manager; import org.apache.catalina.Realm; import org.apache.catalina.Session; import org.apache.catalina.TomcatPrincipal; import org.apache.catalina.Wrapper; import org.apache.catalina.core.ApplicationPart; import org.apache.catalina.core.ApplicationSessionCookieConfig; import org.apache.catalina.core.AsyncContextImpl; import org.apache.catalina.mapper.MappingData; import org.apache.catalina.util.ParameterMap; import org.apache.catalina.util.StringParser; import org.apache.coyote.ActionCode; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.http.Cookies; import org.apache.tomcat.util.http.FastHttpDateFormat; import org.apache.tomcat.util.http.Parameters; import org.apache.tomcat.util.http.ServerCookie; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileUploadBase; import org.apache.tomcat.util.http.fileupload.FileUploadBase.InvalidContentTypeException; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; import org.apache.tomcat.util.res.StringManager; /** * Wrapper object for the Coyote request. * * @author Remy Maucherat * @author Craig R. McClanahan * @version $Id$ */ public class Request implements HttpServletRequest { private static final Log log = LogFactory.getLog(Request.class); // ----------------------------------------------------------- Constructors public Request() { formats[0].setTimeZone(GMT_ZONE); formats[1].setTimeZone(GMT_ZONE); formats[2].setTimeZone(GMT_ZONE); } // ------------------------------------------------------------- Properties /** * Coyote request. */ protected org.apache.coyote.Request coyoteRequest; /** * Set the Coyote request. * * @param coyoteRequest The Coyote request */ public void setCoyoteRequest(org.apache.coyote.Request coyoteRequest) { this.coyoteRequest = coyoteRequest; inputBuffer.setRequest(coyoteRequest); } /** * Get the Coyote request. */ public org.apache.coyote.Request getCoyoteRequest() { return (this.coyoteRequest); } // ----------------------------------------------------- Variables protected static final TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT"); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * The set of cookies associated with this Request. */ protected Cookie[] cookies = null; /** * The set of SimpleDateFormat formats to use in getDateHeader(). * * Notice that because SimpleDateFormat is not thread-safe, we can't * declare formats[] as a static variable. */ protected final SimpleDateFormat formats[] = { new SimpleDateFormat(FastHttpDateFormat.RFC1123_DATE, Locale.US), new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US), new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US) }; /** * The default Locale if none are specified. */ protected static final Locale defaultLocale = Locale.getDefault(); /** * The attributes associated with this Request, keyed by attribute name. */ protected final HashMap<String, Object> attributes = new HashMap<>(); /** * Flag that indicates if SSL attributes have been parsed to improve * performance for applications (usually frameworks) that make multiple * calls to {@link Request#getAttributeNames()}. */ protected boolean sslAttributesParsed = false; /** * List of read only attributes for this Request. */ private final HashMap<String,Object> readOnlyAttributes = new HashMap<>(); /** * The preferred Locales associated with this Request. */ protected final ArrayList<Locale> locales = new ArrayList<>(); /** * Internal notes associated with this request by Catalina components * and event listeners. */ private final transient HashMap<String, Object> notes = new HashMap<>(); /** * Authentication type. */ protected String authType = null; /** * Associated event. */ protected CometEventImpl event = null; /** * Comet state */ protected boolean comet = false; /** * The current dispatcher type. */ protected DispatcherType internalDispatcherType = null; /** * The associated input buffer. */ protected final InputBuffer inputBuffer = new InputBuffer(); /** * ServletInputStream. */ protected CoyoteInputStream inputStream = new CoyoteInputStream(inputBuffer); /** * Reader. */ protected CoyoteReader reader = new CoyoteReader(inputBuffer); /** * Using stream flag. */ protected boolean usingInputStream = false; /** * Using writer flag. */ protected boolean usingReader = false; /** * User principal. */ protected Principal userPrincipal = null; /** * Request parameters parsed flag. */ protected boolean parametersParsed = false; /** * Cookies parsed flag. */ protected boolean cookiesParsed = false; /** * Secure flag. */ protected boolean secure = false; /** * The Subject associated with the current AccessControlContext */ protected transient Subject subject = null; /** * Post data buffer. */ protected static final int CACHED_POST_LEN = 8192; protected byte[] postData = null; /** * Hash map used in the getParametersMap method. */ protected ParameterMap<String, String[]> parameterMap = new ParameterMap<>(); /** * The parts, if any, uploaded with this request. */ protected Collection<Part> parts = null; /** * The exception thrown, if any when parsing the parts. */ protected Exception partsParseException = null; /** * The currently active session for this request. */ protected Session session = null; /** * The current request dispatcher path. */ protected Object requestDispatcherPath = null; /** * Was the requested session ID received in a cookie? */ protected boolean requestedSessionCookie = false; /** * The requested session ID (if any) for this request. */ protected String requestedSessionId = null; /** * Was the requested session ID received in a URL? */ protected boolean requestedSessionURL = false; /** * Was the requested session ID obtained from the SSL session? */ protected boolean requestedSessionSSL = false; /** * Parse locales. */ protected boolean localesParsed = false; /** * The string parser we will use for parsing request lines. */ private final StringParser parser = new StringParser(); /** * Local port */ protected int localPort = -1; /** * Remote address. */ protected String remoteAddr = null; /** * Remote host. */ protected String remoteHost = null; /** * Remote port */ protected int remotePort = -1; /** * Local address */ protected String localAddr = null; /** * Local address */ protected String localName = null; /** * AsyncContext */ protected volatile AsyncContextImpl asyncContext = null; protected Boolean asyncSupported = null; /** * Path parameters */ protected final Map<String,String> pathParameters = new HashMap<>(); // --------------------------------------------------------- Public Methods protected void addPathParameter(String name, String value) { pathParameters.put(name, value); } protected String getPathParameter(String name) { return pathParameters.get(name); } public void setAsyncSupported(boolean asyncSupported) { this.asyncSupported = Boolean.valueOf(asyncSupported); } /** * Release all object references, and initialize instance variables, in * preparation for reuse of this object. */ public void recycle() { context = null; wrapper = null; internalDispatcherType = null; requestDispatcherPath = null; comet = false; if (event != null) { event.clear(); event = null; } authType = null; inputBuffer.recycle(); usingInputStream = false; usingReader = false; userPrincipal = null; subject = null; parametersParsed = false; if (parts != null) { for (Part part: parts) { try { part.delete(); } catch (IOException ignored) { // ApplicationPart.delete() never throws an IOEx } } parts = null; } partsParseException = null; cookiesParsed = false; locales.clear(); localesParsed = false; secure = false; remoteAddr = null; remoteHost = null; remotePort = -1; localPort = -1; localAddr = null; localName = null; attributes.clear(); sslAttributesParsed = false; notes.clear(); cookies = null; if (session != null) { try { session.endAccess(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString("coyoteRequest.sessionEndAccessFail"), t); } } session = null; requestedSessionCookie = false; requestedSessionId = null; requestedSessionURL = false; if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) { parameterMap = new ParameterMap<>(); } else { parameterMap.setLocked(false); parameterMap.clear(); } mappingData.recycle(); if (Globals.IS_SECURITY_ENABLED || Connector.RECYCLE_FACADES) { if (facade != null) { facade.clear(); facade = null; } if (inputStream != null) { inputStream.clear(); inputStream = null; } if (reader != null) { reader.clear(); reader = null; } } asyncSupported = null; if (asyncContext!=null) { asyncContext.recycle(); } asyncContext = null; pathParameters.clear(); } /** * Clear cached encoders (to save memory for Comet requests). */ public void clearEncoders() { inputBuffer.clearEncoders(); } /** * Clear cached encoders (to save memory for Comet requests). */ public boolean read() throws IOException { return (inputBuffer.realReadBytes(null, 0, 0) > 0); } // -------------------------------------------------------- Request Methods /** * Associated Catalina connector. */ protected Connector connector; /** * Return the Connector through which this Request was received. */ public Connector getConnector() { return this.connector; } /** * Set the Connector through which this Request was received. * * @param connector The new connector */ public void setConnector(Connector connector) { this.connector = connector; } /** * Associated context. */ protected Context context = null; /** * Return the Context within which this Request is being processed. */ public Context getContext() { return this.context; } /** * Set the Context within which this Request is being processed. This * must be called as soon as the appropriate Context is identified, because * it identifies the value to be returned by <code>getContextPath()</code>, * and thus enables parsing of the request URI. * * @param context The newly associated Context */ public void setContext(Context context) { this.context = context; } /** * Filter chain associated with the request. */ protected FilterChain filterChain = null; /** * Get filter chain associated with the request. */ public FilterChain getFilterChain() { return this.filterChain; } /** * Set filter chain associated with the request. * * @param filterChain new filter chain */ public void setFilterChain(FilterChain filterChain) { this.filterChain = filterChain; } /** * Return the Host within which this Request is being processed. */ public Host getHost() { return mappingData.host; } /** * Mapping data. */ protected final MappingData mappingData = new MappingData(); /** * Return mapping data. */ public MappingData getMappingData() { return mappingData; } /** * The facade associated with this request. */ protected RequestFacade facade = null; /** * Return the <code>ServletRequest</code> for which this object * is the facade. This method must be implemented by a subclass. */ public HttpServletRequest getRequest() { if (facade == null) { facade = new RequestFacade(this); } return facade; } /** * The response with which this request is associated. */ protected org.apache.catalina.connector.Response response = null; /** * Return the Response with which this Request is associated. */ public org.apache.catalina.connector.Response getResponse() { return this.response; } /** * Set the Response with which this Request is associated. * * @param response The new associated response */ public void setResponse(org.apache.catalina.connector.Response response) { this.response = response; } /** * Return the input stream associated with this Request. */ public InputStream getStream() { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * URI byte to char converter. */ protected B2CConverter URIConverter = null; /** * Return the URI converter. */ protected B2CConverter getURIConverter() { return URIConverter; } /** * Set the URI converter. * * @param URIConverter the new URI converter */ protected void setURIConverter(B2CConverter URIConverter) { this.URIConverter = URIConverter; } /** * Associated wrapper. */ protected Wrapper wrapper = null; /** * Return the Wrapper within which this Request is being processed. */ public Wrapper getWrapper() { return this.wrapper; } /** * Set the Wrapper within which this Request is being processed. This * must be called as soon as the appropriate Wrapper is identified, and * before the Request is ultimately passed to an application servlet. * @param wrapper The newly associated Wrapper */ public void setWrapper(Wrapper wrapper) { this.wrapper = wrapper; } // ------------------------------------------------- Request Public Methods /** * Create and return a ServletInputStream to read the content * associated with this Request. * * @exception IOException if an input/output error occurs */ public ServletInputStream createInputStream() throws IOException { if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * Perform whatever actions are required to flush and close the input * stream or reader, in a single operation. * * @exception IOException if an input/output error occurs */ public void finishRequest() throws IOException { // Optionally disable swallowing of additional request data. Context context = getContext(); if (context != null && response.getStatus() == HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE && !context.getSwallowAbortedUploads()) { coyoteRequest.action(ActionCode.DISABLE_SWALLOW_INPUT, null); } } /** * Return the object bound with the specified name to the internal notes * for this request, or <code>null</code> if no such binding exists. * * @param name Name of the note to be returned */ public Object getNote(String name) { return notes.get(name); } /** * Remove any object bound to the specified name in the internal notes * for this request. * * @param name Name of the note to be removed */ public void removeNote(String name) { notes.remove(name); } /** * Set the port number of the server to process this request. * * @param port The server port */ public void setLocalPort(int port) { localPort = port; } /** * Bind an object to a specified name in the internal notes associated * with this request, replacing any existing binding for this name. * * @param name Name to which the object should be bound * @param value Object to be bound to the specified name */ public void setNote(String name, Object value) { notes.put(name, value); } /** * Set the IP address of the remote client associated with this Request. * * @param remoteAddr The remote IP address */ public void setRemoteAddr(String remoteAddr) { this.remoteAddr = remoteAddr; } /** * Set the fully qualified name of the remote client associated with this * Request. * * @param remoteHost The remote host name */ public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } /** * Set the value to be returned by <code>isSecure()</code> * for this Request. * * @param secure The new isSecure value */ public void setSecure(boolean secure) { this.secure = secure; } /** * Set the port number of the server to process this request. * * @param port The server port */ public void setServerPort(int port) { coyoteRequest.setServerPort(port); } // ------------------------------------------------- ServletRequest Methods /** * Return the specified request attribute if it exists; otherwise, return * <code>null</code>. * * @param name Name of the request attribute to return */ @Override public Object getAttribute(String name) { // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { return adapter.get(this, name); } Object attr=attributes.get(name); if(attr!=null) { return(attr); } attr = coyoteRequest.getAttribute(name); if(attr != null) { return attr; } if( isSSLAttribute(name) ) { coyoteRequest.action(ActionCode.REQ_SSL_ATTRIBUTE, coyoteRequest); attr = coyoteRequest.getAttribute(Globals.CERTIFICATES_ATTR); if( attr != null) { attributes.put(Globals.CERTIFICATES_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.CIPHER_SUITE_ATTR); if(attr != null) { attributes.put(Globals.CIPHER_SUITE_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.KEY_SIZE_ATTR); if(attr != null) { attributes.put(Globals.KEY_SIZE_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_ID_ATTR); if(attr != null) { attributes.put(Globals.SSL_SESSION_ID_ATTR, attr); } attr = coyoteRequest.getAttribute(Globals.SSL_SESSION_MGR_ATTR); if(attr != null) { attributes.put(Globals.SSL_SESSION_MGR_ATTR, attr); } attr = attributes.get(name); sslAttributesParsed = true; } return attr; } @Override public long getContentLengthLong() { return coyoteRequest.getContentLengthLong(); } /** * Test if a given name is one of the special Servlet-spec SSL attributes. */ static boolean isSSLAttribute(String name) { return Globals.CERTIFICATES_ATTR.equals(name) || Globals.CIPHER_SUITE_ATTR.equals(name) || Globals.KEY_SIZE_ATTR.equals(name) || Globals.SSL_SESSION_ID_ATTR.equals(name) || Globals.SSL_SESSION_MGR_ATTR.equals(name); } /** * Return the names of all request attributes for this Request, or an * empty <code>Enumeration</code> if there are none. Note that the attribute * names returned will only be those for the attributes set via * {@link #setAttribute(String, Object)}. Tomcat internal attributes will * not be included although they are accessible via * {@link #getAttribute(String)}. The Tomcat internal attributes include: * <ul> * <li>{@link Globals#DISPATCHER_TYPE_ATTR}</li> * <li>{@link Globals#DISPATCHER_REQUEST_PATH_ATTR}</li> * <li>{@link Globals#ASYNC_SUPPORTED_ATTR}</li> * <li>{@link Globals#CERTIFICATES_ATTR} (SSL connections only)</li> * <li>{@link Globals#CIPHER_SUITE_ATTR} (SSL connections only)</li> * <li>{@link Globals#KEY_SIZE_ATTR} (SSL connections only)</li> * <li>{@link Globals#SSL_SESSION_ID_ATTR} (SSL connections only)</li> * <li>{@link Globals#SSL_SESSION_MGR_ATTR} (SSL connections only)</li> * <li>{@link Globals#PARAMETER_PARSE_FAILED_ATTR}</li> * </ul> * The underlying connector may also expose request attributes. These all * have names starting with "org.apache.tomcat" and include: * <ul> * <li>{@link Globals#SENDFILE_SUPPORTED_ATTR}</li> * <li>{@link Globals#COMET_SUPPORTED_ATTR}</li> * <li>{@link Globals#COMET_TIMEOUT_SUPPORTED_ATTR}</li> * </ul> * Connector implementations may return some, all or none of these * attributes and may also support additional attributes. */ @Override public Enumeration<String> getAttributeNames() { if (isSecure() && !sslAttributesParsed) { getAttribute(Globals.CERTIFICATES_ATTR); } // Take a copy to prevent ConncurrentModificationExceptions if used to // remove attributes Set<String> names = new HashSet<>(); names.addAll(attributes.keySet()); return Collections.enumeration(names); } /** * Return the character encoding for this Request. */ @Override public String getCharacterEncoding() { return coyoteRequest.getCharacterEncoding(); } /** * Return the content length for this Request. */ @Override public int getContentLength() { return coyoteRequest.getContentLength(); } /** * Return the content type for this Request. */ @Override public String getContentType() { return coyoteRequest.getContentType(); } /** * Set the content type for this Request. */ public void setContentType(String contentType) { coyoteRequest.setContentType(contentType); } /** * Return the servlet input stream for this Request. The default * implementation returns a servlet input stream created by * <code>createInputStream()</code>. * * @exception IllegalStateException if <code>getReader()</code> has * already been called for this request * @exception IOException if an input/output error occurs */ @Override public ServletInputStream getInputStream() throws IOException { if (usingReader) { throw new IllegalStateException (sm.getString("coyoteRequest.getInputStream.ise")); } usingInputStream = true; if (inputStream == null) { inputStream = new CoyoteInputStream(inputBuffer); } return inputStream; } /** * Return the preferred Locale that the client will accept content in, * based on the value for the first <code>Accept-Language</code> header * that was encountered. If the request did not specify a preferred * language, the server's default Locale is returned. */ @Override public Locale getLocale() { if (!localesParsed) { parseLocales(); } if (locales.size() > 0) { return locales.get(0); } return defaultLocale; } /** * Return the set of preferred Locales that the client will accept * content in, based on the values for any <code>Accept-Language</code> * headers that were encountered. If the request did not specify a * preferred language, the server's default Locale is returned. */ @Override public Enumeration<Locale> getLocales() { if (!localesParsed) { parseLocales(); } if (locales.size() > 0) { return Collections.enumeration(locales); } ArrayList<Locale> results = new ArrayList<>(); results.add(defaultLocale); return Collections.enumeration(results); } /** * Return the value of the specified request parameter, if any; otherwise, * return <code>null</code>. If there is more than one value defined, * return only the first one. * * @param name Name of the desired request parameter */ @Override public String getParameter(String name) { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameter(name); } /** * Returns a <code>Map</code> of the parameters of this request. * Request parameters are extra information sent with the request. * For HTTP servlets, parameters are contained in the query string * or posted form data. * * @return A <code>Map</code> containing parameter names as keys * and parameter values as map values. */ @Override public Map<String, String[]> getParameterMap() { if (parameterMap.isLocked()) { return parameterMap; } Enumeration<String> enumeration = getParameterNames(); while (enumeration.hasMoreElements()) { String name = enumeration.nextElement(); String[] values = getParameterValues(name); parameterMap.put(name, values); } parameterMap.setLocked(true); return parameterMap; } /** * Return the names of all defined request parameters for this request. */ @Override public Enumeration<String> getParameterNames() { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameterNames(); } /** * Return the defined values for the specified request parameter, if any; * otherwise, return <code>null</code>. * * @param name Name of the desired request parameter */ @Override public String[] getParameterValues(String name) { if (!parametersParsed) { parseParameters(); } return coyoteRequest.getParameters().getParameterValues(name); } /** * Return the protocol and version used to make this Request. */ @Override public String getProtocol() { return coyoteRequest.protocol().toString(); } /** * Read the Reader wrapping the input stream for this Request. The * default implementation wraps a <code>BufferedReader</code> around the * servlet input stream returned by <code>createInputStream()</code>. * * @exception IllegalStateException if <code>getInputStream()</code> * has already been called for this request * @exception IOException if an input/output error occurs */ @Override public BufferedReader getReader() throws IOException { if (usingInputStream) { throw new IllegalStateException (sm.getString("coyoteRequest.getReader.ise")); } usingReader = true; inputBuffer.checkConverter(); if (reader == null) { reader = new CoyoteReader(inputBuffer); } return reader; } /** * Return the real path of the specified virtual path. * * @param path Path to be translated * * @deprecated As of version 2.1 of the Java Servlet API, use * <code>ServletContext.getRealPath()</code>. */ @Override @Deprecated public String getRealPath(String path) { if (context == null) { return null; } ServletContext servletContext = context.getServletContext(); if (servletContext == null) { return null; } try { return (servletContext.getRealPath(path)); } catch (IllegalArgumentException e) { return null; } } /** * Return the remote IP address making this Request. */ @Override public String getRemoteAddr() { if (remoteAddr == null) { coyoteRequest.action (ActionCode.REQ_HOST_ADDR_ATTRIBUTE, coyoteRequest); remoteAddr = coyoteRequest.remoteAddr().toString(); } return remoteAddr; } /** * Return the remote host name making this Request. */ @Override public String getRemoteHost() { if (remoteHost == null) { if (!connector.getEnableLookups()) { remoteHost = getRemoteAddr(); } else { coyoteRequest.action (ActionCode.REQ_HOST_ATTRIBUTE, coyoteRequest); remoteHost = coyoteRequest.remoteHost().toString(); } } return remoteHost; } /** * Returns the Internet Protocol (IP) source port of the client * or last proxy that sent the request. */ @Override public int getRemotePort(){ if (remotePort == -1) { coyoteRequest.action (ActionCode.REQ_REMOTEPORT_ATTRIBUTE, coyoteRequest); remotePort = coyoteRequest.getRemotePort(); } return remotePort; } /** * Returns the host name of the Internet Protocol (IP) interface on * which the request was received. */ @Override public String getLocalName(){ if (localName == null) { coyoteRequest.action (ActionCode.REQ_LOCAL_NAME_ATTRIBUTE, coyoteRequest); localName = coyoteRequest.localName().toString(); } return localName; } /** * Returns the Internet Protocol (IP) address of the interface on * which the request was received. */ @Override public String getLocalAddr(){ if (localAddr == null) { coyoteRequest.action (ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE, coyoteRequest); localAddr = coyoteRequest.localAddr().toString(); } return localAddr; } /** * Returns the Internet Protocol (IP) port number of the interface * on which the request was received. */ @Override public int getLocalPort(){ if (localPort == -1){ coyoteRequest.action (ActionCode.REQ_LOCALPORT_ATTRIBUTE, coyoteRequest); localPort = coyoteRequest.getLocalPort(); } return localPort; } /** * Return a RequestDispatcher that wraps the resource at the specified * path, which may be interpreted as relative to the current request path. * * @param path Path of the resource to be wrapped */ @Override public RequestDispatcher getRequestDispatcher(String path) { if (context == null) { return null; } // If the path is already context-relative, just pass it through if (path == null) { return null; } else if (path.startsWith("/")) { return (context.getServletContext().getRequestDispatcher(path)); } // Convert a request-relative path to a context-relative one String servletPath = (String) getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (servletPath == null) { servletPath = getServletPath(); } // Add the path info, if there is any String pathInfo = getPathInfo(); String requestPath = null; if (pathInfo == null) { requestPath = servletPath; } else { requestPath = servletPath + pathInfo; } int pos = requestPath.lastIndexOf('/'); String relative = null; if (pos >= 0) { relative = requestPath.substring(0, pos + 1) + path; } else { relative = requestPath + path; } return context.getServletContext().getRequestDispatcher(relative); } /** * Return the scheme used to make this Request. */ @Override public String getScheme() { return coyoteRequest.scheme().toString(); } /** * Return the server name responding to this Request. */ @Override public String getServerName() { return coyoteRequest.serverName().toString(); } /** * Return the server port responding to this Request. */ @Override public int getServerPort() { return coyoteRequest.getServerPort(); } /** * Was this request received on a secure connection? */ @Override public boolean isSecure() { return secure; } /** * Remove the specified request attribute if it exists. * * @param name Name of the request attribute to remove */ @Override public void removeAttribute(String name) { // Remove the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.getAttributes().remove(name); } boolean found = attributes.containsKey(name); if (found) { Object value = attributes.get(name); attributes.remove(name); // Notify interested application event listeners notifyAttributeRemoved(name, value); } else { return; } } /** * Set the specified request attribute to the specified value. * * @param name Name of the request attribute to set * @param value The associated value */ @Override public void setAttribute(String name, Object value) { // Name cannot be null if (name == null) { throw new IllegalArgumentException (sm.getString("coyoteRequest.setAttribute.namenull")); } // Null value is the same as removeAttribute() if (value == null) { removeAttribute(name); return; } // Special attributes SpecialAttributeAdapter adapter = specialAttributes.get(name); if (adapter != null) { adapter.set(this, name, value); return; } // Add or replace the specified attribute // Check for read only attribute // requests are per thread so synchronization unnecessary if (readOnlyAttributes.containsKey(name)) { return; } // Do the security check before any updates are made if (Globals.IS_SECURITY_ENABLED && name.equals(Globals.SENDFILE_FILENAME_ATTR)) { // Use the canonical file name to avoid any possible symlink and // relative path issues String canonicalPath; try { canonicalPath = new File(value.toString()).getCanonicalPath(); } catch (IOException e) { throw new SecurityException(sm.getString( "coyoteRequest.sendfileNotCanonical", value), e); } // Sendfile is performed in Tomcat's security context so need to // check if the web app is permitted to access the file while still // in the web app's security context System.getSecurityManager().checkRead(canonicalPath); // Update the value so the canonical path is used value = canonicalPath; } Object oldValue = attributes.put(name, value); // Pass special attributes to the native layer if (name.startsWith("org.apache.tomcat.")) { coyoteRequest.setAttribute(name, value); } // Notify interested application event listeners notifyAttributeAssigned(name, value, oldValue); } /** * Notify interested listeners that attribute has been assigned a value. */ private void notifyAttributeAssigned(String name, Object value, Object oldValue) { Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) { return; } boolean replaced = (oldValue != null); ServletRequestAttributeEvent event = null; if (replaced) { event = new ServletRequestAttributeEvent( context.getServletContext(), getRequest(), name, oldValue); } else { event = new ServletRequestAttributeEvent( context.getServletContext(), getRequest(), name, value); } for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletRequestAttributeListener)) { continue; } ServletRequestAttributeListener listener = (ServletRequestAttributeListener) listeners[i]; try { if (replaced) { listener.attributeReplaced(event); } else { listener.attributeAdded(event); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); } } } /** * Notify interested listeners that attribute has been removed. */ private void notifyAttributeRemoved(String name, Object value) { Object listeners[] = context.getApplicationEventListeners(); if ((listeners == null) || (listeners.length == 0)) { return; } ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(context.getServletContext(), getRequest(), name, value); for (int i = 0; i < listeners.length; i++) { if (!(listeners[i] instanceof ServletRequestAttributeListener)) { continue; } ServletRequestAttributeListener listener = (ServletRequestAttributeListener) listeners[i]; try { listener.attributeRemoved(event); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t); // Error valve will pick this exception up and display it to user attributes.put(RequestDispatcher.ERROR_EXCEPTION, t); } } } /** * Overrides the name of the character encoding used in the body of * this request. This method must be called prior to reading request * parameters or reading input using <code>getReader()</code>. * * @param enc The character encoding to be used * * @exception UnsupportedEncodingException if the specified encoding * is not supported * * @since Servlet 2.3 */ @Override public void setCharacterEncoding(String enc) throws UnsupportedEncodingException { if (usingReader) { return; } // Ensure that the specified encoding is valid byte buffer[] = new byte[1]; buffer[0] = (byte) 'a'; // Confirm that the encoding name is valid B2CConverter.getCharset(enc); // Save the validated encoding coyoteRequest.setCharacterEncoding(enc); } @Override public ServletContext getServletContext() { return context.getServletContext(); } @Override public AsyncContext startAsync() { return startAsync(getRequest(),response.getResponse()); } @Override public AsyncContext startAsync(ServletRequest request, ServletResponse response) { if (!isAsyncSupported()) { throw new IllegalStateException("Not supported."); } if (asyncContext == null) { asyncContext = new AsyncContextImpl(this); } asyncContext.setStarted(getContext(), request, response, request==getRequest() && response==getResponse().getResponse()); asyncContext.setTimeout(getConnector().getAsyncTimeout()); return asyncContext; } @Override public boolean isAsyncStarted() { if (asyncContext == null) { return false; } return asyncContext.isStarted(); } public boolean isAsyncDispatching() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_DISPATCHING, result); return result.get(); } public boolean isAsync() { if (asyncContext == null) { return false; } AtomicBoolean result = new AtomicBoolean(false); coyoteRequest.action(ActionCode.ASYNC_IS_ASYNC, result); return result.get(); } @Override public boolean isAsyncSupported() { if (this.asyncSupported == null) { return true; } return asyncSupported.booleanValue(); } @Override public AsyncContext getAsyncContext() { return this.asyncContext; } @Override public DispatcherType getDispatcherType() { if (internalDispatcherType == null) { return DispatcherType.REQUEST; } return this.internalDispatcherType; } // ---------------------------------------------------- HttpRequest Methods /** * Add a Cookie to the set of Cookies associated with this Request. * * @param cookie The new cookie */ public void addCookie(Cookie cookie) { if (!cookiesParsed) { parseCookies(); } int size = 0; if (cookies != null) { size = cookies.length; } Cookie[] newCookies = new Cookie[size + 1]; for (int i = 0; i < size; i++) { newCookies[i] = cookies[i]; } newCookies[size] = cookie; cookies = newCookies; } /** * Add a Locale to the set of preferred Locales for this Request. The * first added Locale will be the first one returned by getLocales(). * * @param locale The new preferred Locale */ public void addLocale(Locale locale) { locales.add(locale); } /** * Clear the collection of Cookies associated with this Request. */ public void clearCookies() { cookiesParsed = true; cookies = null; } /** * Clear the collection of Locales associated with this Request. */ public void clearLocales() { locales.clear(); } /** * Set the authentication type used for this request, if any; otherwise * set the type to <code>null</code>. Typical values are "BASIC", * "DIGEST", or "SSL". * * @param type The authentication type used */ public void setAuthType(String type) { this.authType = type; } /** * Set the path information for this Request. This will normally be called * when the associated Context is mapping the Request to a particular * Wrapper. * * @param path The path information */ public void setPathInfo(String path) { mappingData.pathInfo.setString(path); } /** * Set a flag indicating whether or not the requested session ID for this * request came in through a cookie. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionCookie(boolean flag) { this.requestedSessionCookie = flag; } /** * Set the requested session ID for this request. This is normally called * by the HTTP Connector, when it parses the request headers. * * @param id The new session id */ public void setRequestedSessionId(String id) { this.requestedSessionId = id; } /** * Set a flag indicating whether or not the requested session ID for this * request came in through a URL. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionURL(boolean flag) { this.requestedSessionURL = flag; } /** * Set a flag indicating whether or not the requested session ID for this * request came in through SSL. This is normally called by the * HTTP Connector, when it parses the request headers. * * @param flag The new flag */ public void setRequestedSessionSSL(boolean flag) { this.requestedSessionSSL = flag; } /** * Get the decoded request URI. * * @return the URL decoded request URI */ public String getDecodedRequestURI() { return coyoteRequest.decodedURI().toString(); } /** * Get the decoded request URI. * * @return the URL decoded request URI */ public MessageBytes getDecodedRequestURIMB() { return coyoteRequest.decodedURI(); } /** * Set the Principal who has been authenticated for this Request. This * value is also used to calculate the value to be returned by the * <code>getRemoteUser()</code> method. * * @param principal The user Principal */ public void setUserPrincipal(Principal principal) { if (Globals.IS_SECURITY_ENABLED){ HttpSession session = getSession(false); if ( (subject != null) && (!subject.getPrincipals().contains(principal)) ){ subject.getPrincipals().add(principal); } else if (session != null && session.getAttribute(Globals.SUBJECT_ATTR) == null) { subject = new Subject(); subject.getPrincipals().add(principal); } if (session != null){ session.setAttribute(Globals.SUBJECT_ATTR, subject); } } this.userPrincipal = principal; } // --------------------------------------------- HttpServletRequest Methods /** * {@inheritDoc} * * @since Servlet 3.1 */ @SuppressWarnings("unchecked") @Override public <T extends HttpUpgradeHandler> T upgrade( Class<T> httpUpgradeHandlerClass) throws java.io.IOException, ServletException { T handler; try { handler = (T) context.getInstanceManager().newInstance(httpUpgradeHandlerClass); } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NamingException e) { throw new ServletException(e); } coyoteRequest.action(ActionCode.UPGRADE, handler); // Output required by RFC2616. Protocol specific headers should have // already been set. response.setStatus(HttpServletResponse.SC_SWITCHING_PROTOCOLS); return handler; } /** * Return the authentication type used for this Request. */ @Override public String getAuthType() { return authType; } /** * Return the portion of the request URI used to select the Context * of the Request. */ @Override public String getContextPath() { return mappingData.contextPath.toString(); } /** * Return the set of Cookies received with this Request. */ @Override public Cookie[] getCookies() { if (!cookiesParsed) { parseCookies(); } return cookies; } /** * Return the value of the specified date header, if any; otherwise * return -1. * * @param name Name of the requested date header * * @exception IllegalArgumentException if the specified header value * cannot be converted to a date */ @Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return (-1L); } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat.parseDate(value, formats); if (result != (-1L)) { return result; } throw new IllegalArgumentException(value); } /** * Return the first value of the specified header, if any; otherwise, * return <code>null</code> * * @param name Name of the requested header */ @Override public String getHeader(String name) { return coyoteRequest.getHeader(name); } /** * Return all of the values of the specified header, if any; otherwise, * return an empty enumeration. * * @param name Name of the requested header */ @Override public Enumeration<String> getHeaders(String name) { return coyoteRequest.getMimeHeaders().values(name); } /** * Return the names of all headers received with this request. */ @Override public Enumeration<String> getHeaderNames() { return coyoteRequest.getMimeHeaders().names(); } /** * Return the value of the specified header as an integer, or -1 if there * is no such header for this request. * * @param name Name of the requested header * * @exception IllegalArgumentException if the specified header value * cannot be converted to an integer */ @Override public int getIntHeader(String name) { String value = getHeader(name); if (value == null) { return (-1); } return Integer.parseInt(value); } /** * Return the HTTP request method used in this Request. */ @Override public String getMethod() { return coyoteRequest.method().toString(); } /** * Return the path information associated with this Request. */ @Override public String getPathInfo() { return mappingData.pathInfo.toString(); } /** * Return the extra path information for this request, translated * to a real path. */ @Override public String getPathTranslated() { if (context == null) { return null; } if (getPathInfo() == null) { return null; } return context.getServletContext().getRealPath(getPathInfo()); } /** * Return the query string associated with this request. */ @Override public String getQueryString() { return coyoteRequest.queryString().toString(); } /** * Return the name of the remote user that has been authenticated * for this Request. */ @Override public String getRemoteUser() { if (userPrincipal == null) { return null; } return userPrincipal.getName(); } /** * Get the request path. * * @return the request path */ public MessageBytes getRequestPathMB() { return mappingData.requestPath; } /** * Return the session identifier included in this request, if any. */ @Override public String getRequestedSessionId() { return requestedSessionId; } /** * Return the request URI for this request. */ @Override public String getRequestURI() { return coyoteRequest.requestURI().toString(); } /** * Reconstructs the URL the client used to make the request. * The returned URL contains a protocol, server name, port * number, and server path, but it does not include query * string parameters. * <p> * Because this method returns a <code>StringBuffer</code>, * not a <code>String</code>, you can modify the URL easily, * for example, to append query parameters. * <p> * This method is useful for creating redirect messages and * for reporting errors. * * @return A <code>StringBuffer</code> object containing the * reconstructed URL */ @Override public StringBuffer getRequestURL() { StringBuffer url = new StringBuffer(); String scheme = getScheme(); int port = getServerPort(); if (port < 0) { port = 80; // Work around java.net.URL bug } url.append(scheme); url.append("://"); url.append(getServerName()); if ((scheme.equals("http") && (port != 80)) || (scheme.equals("https") && (port != 443))) { url.append(':'); url.append(port); } url.append(getRequestURI()); return url; } /** * Return the portion of the request URI used to select the servlet * that will process this request. */ @Override public String getServletPath() { return (mappingData.wrapperPath.toString()); } /** * Return the session associated with this Request, creating one * if necessary. */ @Override public HttpSession getSession() { Session session = doGetSession(true); if (session == null) { return null; } return session.getSession(); } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ @Override public HttpSession getSession(boolean create) { Session session = doGetSession(create); if (session == null) { return null; } return session.getSession(); } /** * Return <code>true</code> if the session identifier included in this * request came from a cookie. */ @Override public boolean isRequestedSessionIdFromCookie() { if (requestedSessionId == null) { return false; } return requestedSessionCookie; } /** * Return <code>true</code> if the session identifier included in this * request came from the request URI. */ @Override public boolean isRequestedSessionIdFromURL() { if (requestedSessionId == null) { return false; } return requestedSessionURL; } /** * Return <code>true</code> if the session identifier included in this * request came from the request URI. * * @deprecated As of Version 2.1 of the Java Servlet API, use * <code>isRequestedSessionIdFromURL()</code> instead. */ @Override @Deprecated public boolean isRequestedSessionIdFromUrl() { return (isRequestedSessionIdFromURL()); } /** * Return <code>true</code> if the session identifier included in this * request identifies a valid session. */ @Override public boolean isRequestedSessionIdValid() { if (requestedSessionId == null) { return false; } if (context == null) { return false; } Manager manager = context.getManager(); if (manager == null) { return false; } Session session = null; try { session = manager.findSession(requestedSessionId); } catch (IOException e) { // Can't find the session } if ((session == null) || !session.isValid()) { // Check for parallel deployment contexts if (getMappingData().contexts == null) { return false; } else { for (int i = (getMappingData().contexts.length); i > 0; i--) { Context ctxt = getMappingData().contexts[i - 1]; try { if (ctxt.getManager().findSession(requestedSessionId) != null) { return true; } } catch (IOException e) { // Ignore } } return false; } } return true; } /** * Return <code>true</code> if the authenticated user principal * possesses the specified role name. * * @param role Role name to be validated */ @Override public boolean isUserInRole(String role) { // Have we got an authenticated principal at all? if (userPrincipal == null) { return false; } // Identify the Realm we will use for checking role assignments if (context == null) { return false; } // If the role is "*" then the return value must be false // Servlet 31, section 13.3 if ("*".equals(role)) { return false; } // If the role is "**" then, unless the application defines a role with // that name, only check if the user is authenticated if ("**".equals(role) && !context.findSecurityRole("**")) { return userPrincipal != null; } 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, isSecure()); response.addSessionCookieInternal(newCookie); } } /** * Changes the session ID of the session associated with this request. * * @return the old session ID before it was changed * @see javax.servlet.http.HttpSessionIdListener * @since Servlet 3.1 */ @Override public String changeSessionId() { Session session = this.getSessionInternal(false); if (session == null) { throw new IllegalStateException( sm.getString("coyoteRequest.changeSessionId")); } Manager manager = this.getContext().getManager(); manager.changeSessionId(session); String newSessionId = session.getId(); this.changeSessionId(newSessionId); return newSessionId; } /** * Return the session associated with this Request, creating one * if necessary and requested. * * @param create Create a new session if one does not exist */ public Session getSessionInternal(boolean create) { return doGetSession(create); } /** * Get the event associated with the request. * @return the event */ public CometEventImpl getEvent() { if (event == null) { event = new CometEventImpl(this, response); } return event; } /** * Return true if the current request is handling Comet traffic. */ public boolean isComet() { return comet; } /** * Set comet state. */ public void setComet(boolean comet) { this.comet = comet; } /** * return true if we have parsed parameters */ public boolean isParametersParsed() { return parametersParsed; } /** * Return true if bytes are available. */ public boolean getAvailable() { return (inputBuffer.available() > 0); } /** * Return true if an attempt has been made to read the request body and all * of the request body has been read */ public boolean isFinished() { return coyoteRequest.isFinished(); } /** * 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(true); 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(boolean explicit) { // 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 { if (explicit) { partsParseException = new IllegalStateException( sm.getString("coyoteRequest.noMultipartConfig")); return; } else { parts = Collections.emptyList(); return; } } } Parameters parameters = coyoteRequest.getParameters(); parameters.setLimit(getConnector().getMaxParameterCount()); boolean success = false; try { File location; String locationStr = mce.getLocation(); if (locationStr == null || locationStr.length() == 0) { location = ((File) context.getServletContext().getAttribute( ServletContext.TEMPDIR)); } else { // If relative, it is relative to TEMPDIR location = new File(locationStr); if (!location.isAbsolute()) { location = new File( (File) context.getServletContext().getAttribute( ServletContext.TEMPDIR), locationStr).getAbsoluteFile(); } } if (!location.isDirectory()) { partsParseException = new IOException( sm.getString("coyoteRequest.uploadLocationInvalid", location)); return; } // Create a new file upload handler DiskFileItemFactory factory = new DiskFileItemFactory(); try { factory.setRepository(location.getCanonicalFile()); } catch (IOException ioe) { partsParseException = ioe; return; } factory.setSizeThreshold(mce.getFileSizeThreshold()); ServletFileUpload upload = new ServletFileUpload(); upload.setFileItemFactory(factory); upload.setFileSizeMax(mce.getMaxFileSize()); upload.setSizeMax(mce.getMaxRequestSize()); parts = new ArrayList<>(); try { List<FileItem> items = upload.parseRequest(new ServletRequestContext(this)); int maxPostSize = getConnector().getMaxPostSize(); int postSize = 0; String enc = getCharacterEncoding(); Charset charset = null; if (enc != null) { try { charset = B2CConverter.getCharset(enc); } catch (UnsupportedEncodingException e) { // Ignore } } for (FileItem item : items) { ApplicationPart part = new ApplicationPart(item, location); parts.add(part); if (part.getSubmittedFileName() == null) { String name = part.getName(); String value = null; try { String encoding = parameters.getEncoding(); if (encoding == null) { if (enc == null) { encoding = Parameters.DEFAULT_ENCODING; } else { encoding = enc; } } value = part.getString(encoding); } catch (UnsupportedEncodingException uee) { try { value = part.getString(Parameters.DEFAULT_ENCODING); } catch (UnsupportedEncodingException e) { // Should not be possible } } if (maxPostSize > 0) { // Have to calculate equivalent size. Not completely // accurate but close enough. if (charset == null) { // Name length postSize += name.getBytes().length; } else { postSize += name.getBytes(charset).length; } if (value != null) { // Equals sign postSize++; // Value length postSize += part.getSize(); } // Value separator postSize++; if (postSize > maxPostSize) { throw new IllegalStateException(sm.getString( "coyoteRequest.maxPostSizeExceeded")); } } parameters.addParameter(name, value); } } success = true; } catch (InvalidContentTypeException e) { partsParseException = new ServletException(e); } catch (FileUploadBase.SizeException e) { checkSwallowInput(); partsParseException = new IllegalStateException(e); } catch (FileUploadException e) { partsParseException = new IOException(e); } catch (IllegalStateException e) { checkSwallowInput(); partsParseException = e; } } finally { if (partsParseException != null || !success) { parameters.setParseFailed(true); } } } /** * {@inheritDoc} */ @Override public Part getPart(String name) throws IOException, IllegalStateException, ServletException { Collection<Part> c = getParts(); Iterator<Part> iterator = c.iterator(); while (iterator.hasNext()) { Part part = iterator.next(); if (name.equals(part.getName())) { return part; } } return null; } // ------------------------------------------------------ Protected Methods protected Session doGetSession(boolean create) { // There cannot be a session if no context has been assigned yet if (context == null) { return (null); } // Return the current session if it exists and is valid if ((session != null) && !session.isValid()) { session = null; } if (session != null) { return (session); } // Return the requested session if it exists and is valid Manager manager = null; if (context != null) { manager = context.getManager(); } if (manager == null) { return (null); // Sessions are not supported } if (requestedSessionId != null) { try { session = manager.findSession(requestedSessionId); } catch (IOException e) { session = null; } if ((session != null) && !session.isValid()) { session = null; } if (session != null) { session.access(); return (session); } } // Create a new session if requested and the response is not committed if (!create) { return (null); } if ((context != null) && (response != null) && context.getServletContext().getEffectiveSessionTrackingModes(). contains(SessionTrackingMode.COOKIE) && response.getResponse().isCommitted()) { throw new IllegalStateException (sm.getString("coyoteRequest.sessionCreateCommitted")); } // Attempt to reuse session id if one was submitted in a cookie // Do not reuse the session id if it is from a URL, to prevent possible // phishing attacks // Use the SSL session ID if one is present. if (("/".equals(context.getSessionCookiePath()) && isRequestedSessionIdFromCookie()) || requestedSessionSSL ) { session = manager.createSession(getRequestedSessionId()); } else { session = manager.createSession(null); } // Creating a new session cookie based on that session if ((session != null) && (getContext() != null) && getContext().getServletContext(). getEffectiveSessionTrackingModes().contains( SessionTrackingMode.COOKIE)) { Cookie cookie = ApplicationSessionCookieConfig.createSessionCookie( context, session.getIdInternal(), isSecure()); response.addSessionCookieInternal(cookie); } if (session == null) { return null; } session.access(); return session; } protected String unescape(String s) { if (s==null) { return null; } if (s.indexOf('\\') == -1) { return s; } StringBuilder buf = new StringBuilder(); for (int i=0; i<s.length(); i++) { char c = s.charAt(i); if (c!='\\') { buf.append(c); } else { if (++i >= s.length()) { throw new IllegalArgumentException();//invalid escape, hence invalid cookie } c = s.charAt(i); buf.append(c); } } return buf.toString(); } /** * Parse cookies. */ protected void parseCookies() { cookiesParsed = true; Cookies serverCookies = coyoteRequest.getCookies(); int count = serverCookies.getCookieCount(); if (count <= 0) { return; } cookies = new Cookie[count]; int idx=0; for (int i = 0; i < count; i++) { ServerCookie scookie = serverCookies.getCookie(i); try { /* we must unescape the '\\' escape character */ Cookie cookie = new Cookie(scookie.getName().toString(),null); int version = scookie.getVersion(); cookie.setVersion(version); cookie.setValue(unescape(scookie.getValue().toString())); cookie.setPath(unescape(scookie.getPath().toString())); String domain = scookie.getDomain().toString(); if (domain!=null) { cookie.setDomain(unescape(domain));//avoid NPE } String comment = scookie.getComment().toString(); cookie.setComment(version==1?unescape(comment):null); cookies[idx++] = cookie; } catch(IllegalArgumentException e) { // Ignore bad cookie } } if( idx < count ) { Cookie [] ncookies = new Cookie[idx]; System.arraycopy(cookies, 0, ncookies, 0, idx); cookies = ncookies; } } /** * Parse request parameters. */ protected void parseParameters() { parametersParsed = true; Parameters parameters = coyoteRequest.getParameters(); boolean success = false; try { // Set this every time in case limit has been changed via JMX parameters.setLimit(getConnector().getMaxParameterCount()); // getCharacterEncoding() may have been overridden to search for // hidden form field containing request encoding String enc = getCharacterEncoding(); boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI(); if (enc != null) { parameters.setEncoding(enc); if (useBodyEncodingForURI) { parameters.setQueryStringEncoding(enc); } } else { parameters.setEncoding (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); if (useBodyEncodingForURI) { parameters.setQueryStringEncoding (org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING); } } parameters.handleQueryParameters(); if (usingInputStream || usingReader) { success = true; return; } if( !getConnector().isParseBodyMethod(getMethod()) ) { success = true; return; } String contentType = getContentType(); if (contentType == null) { contentType = ""; } int semicolon = contentType.indexOf(';'); if (semicolon >= 0) { contentType = contentType.substring(0, semicolon).trim(); } else { contentType = contentType.trim(); } if ("multipart/form-data".equals(contentType)) { parseParts(false); 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 } }); } }
55,837
Bug 55837 ServletContext.getRealPath() returns null
[code] String path = servletContext.getRealPath('/test'); if no file or folder named '/test' exist in webroot then path return null but int tomcat 5\6\7, it will return the correct value , ex /data/oschina/webapp/test
resolved fixed
a63bf3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-04T17:18:57Z
2013-12-03T14:13:20Z
java/org/apache/catalina/webresources/DirResourceSet.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.webresources; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Set; import org.apache.catalina.LifecycleException; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.WebResourceRoot.ResourceSetType; import org.apache.catalina.util.IOTools; import org.apache.catalina.util.ResourceSet; /** * Represents a {@link org.apache.catalina.WebResourceSet} based on a directory. */ public class DirResourceSet extends AbstractFileResourceSet { /** * A no argument constructor is required for this to work with the digester. */ public DirResourceSet() { super("/"); } /** * Creates a new {@link org.apache.catalina.WebResourceSet} based on a * directory. * * @param root The {@link WebResourceRoot} this new * {@link org.apache.catalina.WebResourceSet} will * be added to. * @param webAppMount The path within the web application at which this * {@link org.apache.catalina.WebResourceSet} will * be mounted. For example, to add a directory of * JARs to a web application, the directory would * be mounted at "/WEB-INF/lib/" * @param base The absolute path to the directory on the file * system from which the resources will be served. * @param internalPath The path within this new {@link * org.apache.catalina.WebResourceSet} where * resources will be served from. */ public DirResourceSet(WebResourceRoot root, String webAppMount, String base, String internalPath) { super(internalPath); setRoot(root); setWebAppMount(webAppMount); setBase(base); if (root.getContext().getAddWebinfClassesResources()) { File f = new File(base, internalPath); f = new File(f, "/WEB-INF/classes/META-INF/resources"); if (f.isDirectory()) { root.createWebResourceSet(ResourceSetType.RESOURCE_JAR, "/", f.getAbsolutePath(), null, "/"); } } if (getRoot().getState().isAvailable()) { try { start(); } catch (LifecycleException e) { throw new IllegalStateException(e); } } } @Override public WebResource getResource(String path) { checkPath(path); String webAppMount = getWebAppMount(); WebResourceRoot root = getRoot(); if (path.startsWith(webAppMount)) { File f = file(path.substring(webAppMount.length()), true); if (f == null) { return new EmptyResource(root, path); } if (f.isDirectory() && path.charAt(path.length() - 1) != '/') { path = path += '/'; } return new FileResource(root, path, f); } else { return new EmptyResource(root, path); } } @Override public String[] list(String path) { checkPath(path); String webAppMount = getWebAppMount(); if (path.startsWith(webAppMount)) { File f = file(path.substring(webAppMount.length()), true); if (f == null) { return EMPTY_STRING_ARRAY; } String[] result = f.list(); if (result == null) { return EMPTY_STRING_ARRAY; } else { return result; } } else { if (!path.endsWith("/")) { path = path + "/"; } if (webAppMount.startsWith(path)) { int i = webAppMount.indexOf('/', path.length()); if (i == -1) { return new String[] {webAppMount.substring(path.length())}; } else { return new String[] { webAppMount.substring(path.length(), i)}; } } return EMPTY_STRING_ARRAY; } } @Override public Set<String> listWebAppPaths(String path) { checkPath(path); String webAppMount = getWebAppMount(); ResourceSet<String> result = new ResourceSet<>(); if (path.startsWith(webAppMount)) { File f = file(path.substring(webAppMount.length()), true); if (f != null) { File[] list = f.listFiles(); if (list != null) { for (File entry : list) { StringBuilder sb = new StringBuilder(path); if (path.charAt(path.length() - 1) != '/') { sb.append('/'); } sb.append(entry.getName()); if (entry.isDirectory()) { sb.append('/'); } result.add(sb.toString()); } } } } else { if (!path.endsWith("/")) { path = path + "/"; } if (webAppMount.startsWith(path)) { int i = webAppMount.indexOf('/', path.length()); if (i == -1) { result.add(webAppMount + "/"); } else { result.add(webAppMount.substring(0, i + 1)); } } } result.setLocked(true); return result; } @Override public boolean mkdir(String path) { checkPath(path); String webAppMount = getWebAppMount(); if (path.startsWith(webAppMount)) { File f = file(path.substring(webAppMount.length()), false); if (f == null) { return false; } return f.mkdir(); } else { return false; } } @Override public boolean write(String path, InputStream is, boolean overwrite) { checkPath(path); if (is == null) { throw new NullPointerException( sm.getString("dirResourceSet.writeNpe")); } File dest = null; String webAppMount = getWebAppMount(); if (path.startsWith(webAppMount)) { dest = file(path.substring(webAppMount.length()), false); if (dest == null) { return false; } } else { return false; } if (dest.exists()) { if (overwrite) { if (!dest.delete()) { return false; } } else { return false; } } try (FileOutputStream fos = new FileOutputStream(dest)) { IOTools.flow(is, fos); } catch (IOException ioe) { return false; } return true; } @Override protected void checkType(File file) { if (file.isDirectory() == false) { throw new IllegalArgumentException( "TODO-i18n: base/internalPath is not a directory"); } } }
55,837
Bug 55837 ServletContext.getRealPath() returns null
[code] String path = servletContext.getRealPath('/test'); if no file or folder named '/test' exist in webroot then path return null but int tomcat 5\6\7, it will return the correct value , ex /data/oschina/webapp/test
resolved fixed
a63bf3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-04T17:18:57Z
2013-12-03T14:13:20Z
java/org/apache/catalina/webresources/EmptyResource.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.webresources; import java.io.InputStream; import java.net.URL; import java.security.cert.Certificate; import java.util.jar.Manifest; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; public class EmptyResource implements WebResource { private final WebResourceRoot root; private final String webAppPath; public EmptyResource(WebResourceRoot root, String webAppPath) { this.root = root; this.webAppPath = webAppPath; } @Override public long getLastModified() { return 0; } @Override public String getLastModifiedHttp() { return null; } @Override public boolean exists() { return false; } @Override public boolean isVirtual() { return false; } @Override public boolean isDirectory() { return false; } @Override public boolean isFile() { return false; } @Override public boolean delete() { return false; } @Override public String getName() { int index = webAppPath.lastIndexOf('/'); if (index == -1) { return webAppPath; } else { return webAppPath.substring(index + 1); } } @Override public long getContentLength() { return 0; } @Override public String getCanonicalPath() { return null; } @Override public boolean canRead() { return false; } @Override public String getWebappPath() { return webAppPath; } @Override public String getETag() { return null; } @Override public void setMimeType(String mimeType) { // NOOP } @Override public String getMimeType() { return null; } @Override public InputStream getInputStream() { return null; } @Override public byte[] getContent() { return null; } @Override public long getCreation() { return 0; } @Override public URL getURL() { return null; } @Override public Certificate[] getCertificates() { return null; } @Override public Manifest getManifest() { return null; } @Override public WebResourceRoot getWebResourceRoot() { return root; } }
55,837
Bug 55837 ServletContext.getRealPath() returns null
[code] String path = servletContext.getRealPath('/test'); if no file or folder named '/test' exist in webroot then path return null but int tomcat 5\6\7, it will return the correct value , ex /data/oschina/webapp/test
resolved fixed
a63bf3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-04T17:18:57Z
2013-12-03T14:13:20Z
java/org/apache/catalina/webresources/StandardRoot.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.webresources; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Set; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.WebResourceSet; import org.apache.catalina.WebResourceTraceWrapper; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.http.RequestUtil; import org.apache.tomcat.util.res.StringManager; /** * <p> * Provides the resources implementation for a web application. The * {@link org.apache.catalina.Lifecycle} of this class should be aligned with * that of the associated {@link Context}. * </p><p> * This implementation assumes that the base attribute supplied to {@link * StandardRoot#createWebResourceSet( * org.apache.catalina.WebResourceRoot.ResourceSetType, String, String, String, * String)} represents the absolute path to a file. * </p> */ public class StandardRoot extends LifecycleMBeanBase implements WebResourceRoot { private static final Log log = LogFactory.getLog(Cache.class); protected static final StringManager sm = StringManager.getManager(Constants.Package); private Context context; private boolean allowLinking = false; private final ArrayList<WebResourceSet> preResources = new ArrayList<>(); private WebResourceSet main; private final ArrayList<WebResourceSet> classResources = new ArrayList<>(); private final ArrayList<WebResourceSet> jarResources = new ArrayList<>(); private final ArrayList<WebResourceSet> postResources = new ArrayList<>(); private final Cache cache = new Cache(this); private boolean cachingAllowed = true; private boolean traceLockedFiles = false; private final Set<WebResourceTraceWrapper> tracedResources = new HashSet<>(); // Constructs to make iteration over all WebResourceSets simpler private final ArrayList<WebResourceSet> mainResources = new ArrayList<>(); private final ArrayList<ArrayList<WebResourceSet>> allResources = new ArrayList<>(); { allResources.add(preResources); allResources.add(mainResources); allResources.add(classResources); allResources.add(jarResources); allResources.add(postResources); } /** * Creates a new standard implementation of {@link WebResourceRoot}. A no * argument constructor is required for this to work with the digester. * {@link #setContext(Context)} must be called before this component is * initialized. */ public StandardRoot() { // NO-OP } public StandardRoot(Context context) { this.context = context; } @Override public String[] list(String path) { return list(path, true); } private String[] list(String path, boolean validate) { if (validate) { path = validate(path); } // Set because we don't want duplicates // LinkedHashSet to retain the order. It is the order of the // WebResourceSet that matters but it is simpler to retain the order // over all of the JARs. HashSet<String> result = new LinkedHashSet<>(); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (!webResourceSet.getClassLoaderOnly()) { String[] entries = webResourceSet.list(path); for (String entry : entries) { result.add(entry); } } } } return result.toArray(new String[result.size()]); } @Override public Set<String> listWebAppPaths(String path) { path = validate(path); // Set because we don't want duplicates HashSet<String> result = new HashSet<>(); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (!webResourceSet.getClassLoaderOnly()) { result.addAll(webResourceSet.listWebAppPaths(path)); } } } if (result.size() == 0) { return null; } return result; } @Override public boolean mkdir(String path) { path = validate(path); if (preResourceExists(path)) { return false; } return main.mkdir(path); } @Override public boolean write(String path, InputStream is, boolean overwrite) { path = validate(path); if (!overwrite && preResourceExists(path)) { return false; } return main.write(path, is, overwrite); } private boolean preResourceExists(String path) { for (WebResourceSet webResourceSet : preResources) { WebResource webResource = webResourceSet.getResource(path); if (webResource.exists()) { return true; } } return false; } @Override public WebResource getResource(String path) { return getResource(path, true, false); } private WebResource getResource(String path, boolean validate, boolean useClassLoaderResources) { if (validate) { path = validate(path); } if (isCachingAllowed()) { return cache.getResource(path, useClassLoaderResources); } else { return getResourceInternal(path, useClassLoaderResources); } } @Override public WebResource getClassLoaderResource(String path) { return getResource("/WEB-INF/classes" + path, true, true); } @Override public WebResource[] getClassLoaderResources(String path) { return getResources("/WEB-INF/classes" + path, true); } /** * Ensures that this object is in a valid state to serve resources, checks * that the path is a String that starts with '/' and checks that the path * can be normalized without stepping outside of the root. * * @param path * @return the normlized path */ private String validate(String path) { if (!getState().isAvailable()) { throw new IllegalStateException( sm.getString("standardRoot.checkStateNotStarted")); } if (path == null || path.length() == 0 || !path.startsWith("/")) { throw new IllegalArgumentException( sm.getString("standardRoot.invalidPath", path)); } return RequestUtil.normalize(path); } protected final WebResource getResourceInternal(String path, boolean useClassLoaderResources) { WebResource result = null; WebResource virtual = null; for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (useClassLoaderResources || !webResourceSet.getClassLoaderOnly()) { result = webResourceSet.getResource(path); if (result.exists()) { return result; } if (virtual == null && result.isVirtual()) { virtual = result; } } } } // Use the first virtual result if no real result was found if (virtual != null) { return virtual; } // Default is empty resource in main resources return new EmptyResource(this, path); } @Override public WebResource[] getResources(String path) { return getResources(path, false); } private WebResource[] getResources(String path, boolean useClassLoaderResources) { path = validate(path); ArrayList<WebResource> result = new ArrayList<>(); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (useClassLoaderResources || !webResourceSet.getClassLoaderOnly()) { WebResource webResource = webResourceSet.getResource(path); if (webResource.exists()) { result.add(webResource); } } } } if (result.size() == 0) { result.add(main.getResource(path)); } return result.toArray(new WebResource[result.size()]); } @Override public WebResource[] listResources(String path) { return listResources(path, true); } private WebResource[] listResources(String path, boolean validate) { if (validate) { path = validate(path); } String[] resources = list(path, false); WebResource[] result = new WebResource[resources.length]; for (int i = 0; i < resources.length; i++) { if (path.charAt(path.length() - 1) == '/') { result[i] = getResource(path + resources[i], false, false); } else { result[i] = getResource(path + '/' + resources[i], false, false); } } return result; } @Override public void createWebResourceSet(ResourceSetType type, String webAppMount, URL url, String internalPath) { BaseLocation baseLocation = new BaseLocation(url); createWebResourceSet(type, webAppMount, baseLocation.getBasePath(), baseLocation.getArchivePath(), internalPath); } @Override public void createWebResourceSet(ResourceSetType type, String webAppMount, String base, String archivePath, String internalPath) { ArrayList<WebResourceSet> resourceList; WebResourceSet resourceSet; switch (type) { case PRE: resourceList = preResources; break; case CLASSES_JAR: resourceList = classResources; break; case RESOURCE_JAR: resourceList = jarResources; break; case POST: resourceList = postResources; break; default: throw new IllegalArgumentException( sm.getString("standardRoot.createUnknownType", type)); } // This implementation assumes that the base for all resources will be a // file. File file = new File(base); if (file.isFile()) { if (archivePath != null) { // Must be a JAR nested inside a WAR if archivePath is non-null resourceSet = new JarWarResourceSet(this, webAppMount, base, archivePath, internalPath); } else if (file.getName().toLowerCase(Locale.ENGLISH).endsWith(".jar")) { resourceSet = new JarResourceSet(this, webAppMount, base, internalPath); } else { resourceSet = new FileResourceSet(this, webAppMount, base, internalPath); } } else if (file.isDirectory()) { resourceSet = new DirResourceSet(this, webAppMount, base, internalPath); } else { throw new IllegalArgumentException( sm.getString("standardRoot.createInvalidFile", file)); } if (type.equals(ResourceSetType.CLASSES_JAR)) { resourceSet.setClassLoaderOnly(true); } resourceList.add(resourceSet); } @Override public void addPreResources(WebResourceSet webResourceSet) { webResourceSet.setRoot(this); preResources.add(webResourceSet); } @Override public WebResourceSet[] getPreResources() { return preResources.toArray(new WebResourceSet[0]); } @Override public void addJarResources(WebResourceSet webResourceSet) { webResourceSet.setRoot(this); jarResources.add(webResourceSet); } @Override public WebResourceSet[] getJarResources() { return jarResources.toArray(new WebResourceSet[0]); } @Override public void addPostResources(WebResourceSet webResourceSet) { webResourceSet.setRoot(this); postResources.add(webResourceSet); } @Override public WebResourceSet[] getPostResources() { return postResources.toArray(new WebResourceSet[0]); } @Override public void setAllowLinking(boolean allowLinking) { this.allowLinking = allowLinking; } @Override public boolean getAllowLinking() { return allowLinking; } @Override public void setCachingAllowed(boolean cachingAllowed) { this.cachingAllowed = cachingAllowed; } @Override public boolean isCachingAllowed() { return cachingAllowed; } @Override public long getCacheTtl() { return cache.getTtl(); } @Override public void setCacheTtl(long cacheTtl) { cache.setTtl(cacheTtl); } @Override public long getCacheMaxSize() { return cache.getMaxSize(); } @Override public void setCacheMaxSize(long cacheMaxSize) { cache.setMaxSize(cacheMaxSize); } @Override public void setCacheMaxObjectSize(long cacheMaxObjectSize) { cache.setMaxObjectSize(cacheMaxObjectSize); } @Override public long getCacheMaxObjectSize() { return cache.getMaxObjectSize(); } @Override public void setTraceLockedFiles(boolean traceLockedFiles) { this.traceLockedFiles = traceLockedFiles; } @Override public boolean getTraceLockedFiles() { return traceLockedFiles; } @Override public Context getContext() { return context; } @Override public void setContext(Context context) { this.context = context; } /* * Class loader resources are handled by treating JARs in WEB-INF/lib as * resource JARs (without the internal META-INF/resources/ prefix) mounted * at WEB-INF/claasses (rather than the web app root). This enables reuse * of the resource handling plumbing. * * These resources are marked as class loader only so they are only used in * the methods that are explicitly defined to return class loader resources. * This prevents calls to getResource("/WEB-INF/classes") returning from one * or more of the JAR files. */ private void processWebInfLib() { WebResource[] possibleJars = listResources("/WEB-INF/lib", false); for (WebResource possibleJar : possibleJars) { if (possibleJar.isFile() && possibleJar.getName().endsWith(".jar")) { createWebResourceSet(ResourceSetType.CLASSES_JAR, "/WEB-INF/classes", possibleJar.getURL(), "/"); } } } /** * For unit testing */ protected final void setMainResources(WebResourceSet main) { this.main = main; mainResources.clear(); mainResources.add(main); } @Override public void backgroundProcess() { cache.backgroundProcess(); } @Override public void registerTracedResource(WebResourceTraceWrapper traceResource) { tracedResources.add(traceResource); } @Override public void deregisterTracedResource(WebResourceTraceWrapper traceResource) { tracedResources.remove(traceResource); } @Override public List<URL> getBaseUrls() { List<URL> result = new ArrayList<>(); for (List<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { if (!webResourceSet.getClassLoaderOnly()) { URL url = webResourceSet.getBaseUrl(); if (url != null) { result.add(url); } } } } return result; } // ----------------------------------------------------------- JMX Lifecycle @Override protected String getDomainInternal() { return context.getDomain(); } @Override protected String getObjectNameKeyProperties() { StringBuilder keyProperties = new StringBuilder("type=WebResourceRoot"); keyProperties.append(context.getMBeanKeyProperties()); return keyProperties.toString(); } // --------------------------------------------------------------- Lifecycle @Override protected void initInternal() throws LifecycleException { super.initInternal(); // Ensure support for jar:war:file:/ URLs will be available (required // for resource JARs in packed WAR files). TomcatURLStreamHandlerFactory.register(); if (context == null) { throw new IllegalStateException( sm.getString("standardRoot.noContext")); } for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.init(); } } } @Override protected void startInternal() throws LifecycleException { String docBase = context.getDocBase(); File f = new File(docBase); if (!f.isAbsolute()) { f = new File(((Host)context.getParent()).getAppBaseFile(), f.getName()); } if (f.isDirectory()) { main = new DirResourceSet(this, "/", f.getAbsolutePath(), "/"); } else if(f.isFile() && docBase.endsWith(".war")) { main = new JarResourceSet(this, "/", f.getAbsolutePath(), "/"); } else { throw new IllegalArgumentException( sm.getString("standardRoot.startInvalidMain", f.getAbsolutePath())); } mainResources.clear(); mainResources.add(main); for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.start(); } } // This has to be called after the other resources have been started // else it won't find all the matching resources processWebInfLib(); // Need to start the newly found resources for (WebResourceSet classResource : classResources) { classResource.start(); } setState(LifecycleState.STARTING); } @Override protected void stopInternal() throws LifecycleException { for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.stop(); } } if (main != null) { main.destroy(); } mainResources.clear(); for (WebResourceSet webResourceSet : jarResources) { webResourceSet.destroy(); } jarResources.clear(); for (WebResourceSet webResourceSet : classResources) { webResourceSet.destroy(); } classResources.clear(); for (WebResourceTraceWrapper tracedResource : tracedResources) { log.error(sm.getString("standardRoot.lockedFile", context.getName(), tracedResource.getName()), tracedResource.getCreatedBy()); try { tracedResource.close(); } catch (IOException e) { // Ignore } } cache.clear(); setState(LifecycleState.STOPPING); } @Override protected void destroyInternal() throws LifecycleException { for (ArrayList<WebResourceSet> list : allResources) { for (WebResourceSet webResourceSet : list) { webResourceSet.destroy(); } } super.destroyInternal(); } // Unit tests need to access this class static class BaseLocation { private final String basePath; private final String archivePath; BaseLocation(URL url) { File f = null; if ("jar".equals(url.getProtocol())) { String jarUrl = url.toString(); int endOfFileUrl = jarUrl.indexOf("!/"); String fileUrl = jarUrl.substring(4, endOfFileUrl); try { f = new File(new URL(fileUrl).toURI()); } catch (MalformedURLException | URISyntaxException e) { throw new IllegalArgumentException(e); } int startOfArchivePath = endOfFileUrl + 2; if (jarUrl.length() > startOfArchivePath) { archivePath = jarUrl.substring(startOfArchivePath); } else { archivePath = null; } } else if ("file".equals(url.getProtocol())){ try { f = new File(url.toURI()); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } archivePath = null; } else { throw new IllegalArgumentException(sm.getString( "standardRoot.unsupportedProtocol", url.getProtocol())); } basePath = f.getAbsolutePath(); } String getBasePath() { return basePath; } String getArchivePath() { return archivePath; } } }
55,837
Bug 55837 ServletContext.getRealPath() returns null
[code] String path = servletContext.getRealPath('/test'); if no file or folder named '/test' exist in webroot then path return null but int tomcat 5\6\7, it will return the correct value , ex /data/oschina/webapp/test
resolved fixed
a63bf3a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-04T17:18:57Z
2013-12-03T14:13:20Z
test/org/apache/catalina/webresources/AbstractTestResourceSet.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.webresources; import java.io.ByteArrayInputStream; import java.io.File; import java.io.InputStream; import java.util.HashSet; import java.util.Set; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.apache.catalina.LifecycleException; import org.apache.catalina.WebResource; import org.apache.catalina.WebResourceRoot; public abstract class AbstractTestResourceSet { protected WebResourceRoot resourceRoot; protected abstract WebResourceRoot getWebResourceRoot(); protected abstract boolean isWriteable(); public String getMount() { return ""; } public abstract String getBaseDir(); @Before public final void setup() throws LifecycleException { resourceRoot = getWebResourceRoot(); resourceRoot.start(); } @After public final void teardown() throws LifecycleException { resourceRoot.stop(); resourceRoot.destroy(); } @Test(expected = IllegalArgumentException.class) public final void testGetResourceEmpty() { resourceRoot.getResource(""); } //------------------------------------------------------------ getResource() @Test public final void testGetResourceRoot() { WebResource webResource = resourceRoot.getResource(getMount() + "/"); Assert.assertTrue(webResource.isDirectory()); String expected; if (getMount().length() > 0) { expected = getMount().substring(1); } else { expected = ""; } Assert.assertEquals(expected, webResource.getName()); Assert.assertEquals(getMount() + "/", webResource.getWebappPath()); } @Test public final void testGetResourceDirA() { WebResource webResource = resourceRoot.getResource(getMount() + "/d1"); Assert.assertTrue(webResource.isDirectory()); Assert.assertEquals("d1", webResource.getName()); Assert.assertEquals(getMount() + "/d1/", webResource.getWebappPath()); } @Test public final void testGetResourceDirB() { WebResource webResource = resourceRoot.getResource(getMount() + "/d1/"); Assert.assertTrue(webResource.isDirectory()); Assert.assertEquals("d1", webResource.getName()); Assert.assertEquals(getMount() + "/d1/", webResource.getWebappPath()); } @Test public final void testGetResourceFile() { WebResource webResource = resourceRoot.getResource(getMount() + "/d1/d1-f1.txt"); Assert.assertTrue(webResource.isFile()); Assert.assertEquals("d1-f1.txt", webResource.getName()); Assert.assertEquals( getMount() + "/d1/d1-f1.txt", webResource.getWebappPath()); } @Test public final void testGetResourceCaseSensitive() { WebResource webResource = resourceRoot.getResource(getMount() + "/d1/d1-F1.txt"); Assert.assertFalse(webResource.exists()); } @Test public final void testGetResourceTraversal() { WebResource webResource = null; try { webResource = resourceRoot.getResource(getMount() + "/../"); } catch (IllegalArgumentException iae) { // Expected if mount point is zero length Assert.assertTrue(getMount().length() == 0); return; } Assert.assertFalse(webResource.exists()); } //------------------------------------------------------------------- list() @Test(expected = IllegalArgumentException.class) public final void testListEmpty() { resourceRoot.list(""); } @Test public final void testListRoot() { String[] results = resourceRoot.list(getMount() + "/"); Set<String> expected = new HashSet<>(); expected.add("d1"); expected.add("d2"); expected.add("f1.txt"); expected.add("f2.txt"); for (String result : results) { Assert.assertTrue(result, expected.remove(result)); } Assert.assertEquals(0, expected.size()); } @Test public final void testListDirA() { String[] results = resourceRoot.list(getMount() + "/d1"); Set<String> expected = new HashSet<>(); expected.add("d1-f1.txt"); for (String result : results) { Assert.assertTrue(result, expected.remove(result)); } Assert.assertEquals(0, expected.size()); } @Test public final void testListDirB() { String[] results = resourceRoot.list(getMount() + "/d1/"); Set<String> expected = new HashSet<>(); expected.add("d1-f1.txt"); for (String result : results) { Assert.assertTrue(result, expected.remove(result)); } Assert.assertEquals(0, expected.size()); } @Test public final void testListFile() { String[] results = resourceRoot.list(getMount() + "/d1/d1-f1.txt"); Assert.assertNotNull(results); Assert.assertEquals(0, results.length); } //-------------------------------------------------------- listWebAppPaths() @Test(expected = IllegalArgumentException.class) public final void testListWebAppPathsEmpty() { resourceRoot.listWebAppPaths(""); } @Test public final void testListWebAppPathsRoot() { Set<String> results = resourceRoot.listWebAppPaths(getMount() + "/"); Set<String> expected = new HashSet<>(); expected.add(getMount() + "/d1/"); expected.add(getMount() + "/d2/"); expected.add(getMount() + "/f1.txt"); expected.add(getMount() + "/f2.txt"); for (String result : results) { Assert.assertTrue(result, expected.remove(result)); } Assert.assertEquals(0, expected.size()); } @Test public final void testListWebAppPathsDirA() { Set<String> results = resourceRoot.listWebAppPaths(getMount() + "/d1"); Set<String> expected = new HashSet<>(); expected.add(getMount() + "/d1/d1-f1.txt"); for (String result : results) { Assert.assertTrue(result, expected.remove(result)); } Assert.assertEquals(0, expected.size()); } @Test public final void testListWebAppPathsDirB() { Set<String> results = resourceRoot.listWebAppPaths(getMount() + "/d1/"); Set<String> expected = new HashSet<>(); expected.add(getMount() + "/d1/d1-f1.txt"); for (String result : results) { Assert.assertTrue(result, expected.remove(result)); } Assert.assertEquals(0, expected.size()); } @Test public final void testListWebAppPathsFile() { Set<String> results = resourceRoot.listWebAppPaths(getMount() + "/d1/d1-f1.txt"); Assert.assertNull(results); } //------------------------------------------------------------------ mkdir() @Test(expected = IllegalArgumentException.class) public final void testMkdirEmpty() { resourceRoot.mkdir(""); } @Test public final void testMkdirRoot() { Assert.assertFalse(resourceRoot.mkdir(getMount() + "/")); } @Test public final void testMkdirDirA() { WebResource d1 = resourceRoot.getResource(getMount() + "/d1"); if (d1.exists()) { Assert.assertFalse(resourceRoot.mkdir(getMount() + "/d1")); } else if (d1.isVirtual()) { Assert.assertTrue(resourceRoot.mkdir(getMount() + "/d1")); File file = new File(getBaseDir(), "d1"); Assert.assertTrue(file.isDirectory()); Assert.assertTrue(file.delete()); } else { Assert.fail("Unhandled condition in unit test"); } } @Test public final void testMkdirDirB() { WebResource d1 = resourceRoot.getResource(getMount() + "/d1/"); if (d1.exists()) { Assert.assertFalse(resourceRoot.mkdir(getMount() + "/d1/")); } else if (d1.isVirtual()) { Assert.assertTrue(resourceRoot.mkdir(getMount() + "/d1/")); File file = new File(getBaseDir(), "d1"); Assert.assertTrue(file.isDirectory()); Assert.assertTrue(file.delete()); } else { Assert.fail("Unhandled condition in unit test"); } } @Test public final void testMkdirFile() { Assert.assertFalse(resourceRoot.mkdir(getMount() + "/d1/d1-f1.txt")); } @Test public final void testMkdirNew() { if (isWriteable()) { Assert.assertTrue(resourceRoot.mkdir(getMount() + "/new-test")); File file = new File(getBaseDir(), "new-test"); Assert.assertTrue(file.isDirectory()); Assert.assertTrue(file.delete()); } else { Assert.assertFalse(resourceRoot.mkdir(getMount() + "/new-test")); } } //------------------------------------------------------------------ write() @Test(expected = IllegalArgumentException.class) public final void testWriteEmpty() { InputStream is = new ByteArrayInputStream("test".getBytes()); resourceRoot.write("", is, false); } @Test public final void testWriteRoot() { InputStream is = new ByteArrayInputStream("test".getBytes()); Assert.assertFalse(resourceRoot.write(getMount() + "/", is, false)); } @Test public final void testWriteDirA() { WebResource d1 = resourceRoot.getResource(getMount() + "/d1"); InputStream is = new ByteArrayInputStream("test".getBytes()); if (d1.exists()) { Assert.assertFalse(resourceRoot.write(getMount() + "/d1", is, false)); } else if (d1.isVirtual()) { Assert.assertTrue(resourceRoot.write( getMount() + "/d1", is, false)); File file = new File(getBaseDir(), "d1"); Assert.assertTrue(file.exists()); Assert.assertTrue(file.delete()); } else { Assert.fail("Unhandled condition in unit test"); } } @Test public final void testWriteDirB() { WebResource d1 = resourceRoot.getResource(getMount() + "/d1/"); InputStream is = new ByteArrayInputStream("test".getBytes()); if (d1.exists()) { Assert.assertFalse(resourceRoot.write(getMount() + "/d1/", is, false)); } else if (d1.isVirtual()) { Assert.assertTrue(resourceRoot.write( getMount() + "/d1/", is, false)); File file = new File(getBaseDir(), "d1"); Assert.assertTrue(file.exists()); Assert.assertTrue(file.delete()); } else { Assert.fail("Unhandled condition in unit test"); } } @Test public final void testWriteFile() { InputStream is = new ByteArrayInputStream("test".getBytes()); Assert.assertFalse(resourceRoot.write( getMount() + "/d1/d1-f1.txt", is, false)); } @Test(expected = NullPointerException.class) public final void testWriteNew() { resourceRoot.write(getMount() + "/new-test", null, false); } @Test public final void testWrite() { InputStream is = new ByteArrayInputStream("test".getBytes()); if (isWriteable()) { Assert.assertTrue(resourceRoot.write( getMount() + "/new-test", is, false)); File file = new File(getBaseDir(), "new-test"); Assert.assertTrue(file.exists()); Assert.assertTrue(file.delete()); } else { Assert.assertFalse(resourceRoot.write( getMount() + "/new-test", is, false)); } } // ------------------------------------------------------------ constructors public abstract void testNoArgConstructor(); }
55,842
Bug 55842 response.setBufferSize() does not seem to work properly
I found a problem with setting the buffer size for the ServletResponse. If I call 'response.setBufferSize(1,000,000);' and send about 20,000 characters, the response will be chunked even though it should not. The response is sent in several chunks and contains the 'Transfer-Encoding: chunked' response header. In my understanding in this case the response should be fully buffered on the server and then sent as a whole containing the Content-Length-header. This causes a problem in my application because I want to use a larger buffer to be able to redirect to an error page if an error occurs during rendering the response. I was able to reproduce this on Tomcat 7.0.39, 7.0.40, 7.0.42, 7.0.47. Tomcat 7.0.37 works fine and as expected. This is easily reproducable by using a JSP as follows: <% response.setBufferSize(1000*1000); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { response.getWriter().write("X"); } response.getWriter().write("<br />"); } %>
resolved fixed
f4970a7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-06T12:12:15Z
2013-12-04T20:46:40Z
java/org/apache/catalina/connector/OutputBuffer.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.Writer; import java.security.AccessController; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import javax.servlet.WriteListener; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.Globals; import org.apache.coyote.ActionCode; import org.apache.coyote.Response; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.C2BConverter; import org.apache.tomcat.util.buf.CharChunk; /** * The buffer used by Tomcat response. This is a derivative of the Tomcat 3.3 * OutputBuffer, with the removal of some of the state handling (which in * Coyote is mostly the Processor's responsibility). * * @author Costin Manolache * @author Remy Maucherat */ public class OutputBuffer extends Writer implements ByteChunk.ByteOutputChannel, CharChunk.CharOutputChannel { // -------------------------------------------------------------- Constants public static final String DEFAULT_ENCODING = org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING; public static final int DEFAULT_BUFFER_SIZE = 8*1024; // ----------------------------------------------------- Instance Variables /** * The byte buffer. */ private final ByteChunk bb; /** * The chunk buffer. */ private final CharChunk cb; /** * State of the output buffer. */ private boolean initial = true; /** * Number of bytes written. */ private long bytesWritten = 0; /** * Number of chars written. */ private long charsWritten = 0; /** * Flag which indicates if the output buffer is closed. */ private boolean closed = false; /** * Do a flush on the next operation. */ private boolean doFlush = false; /** * Byte chunk used to output bytes. */ private final ByteChunk outputChunk = new ByteChunk(); /** * Char chunk used to output chars. */ private CharChunk outputCharChunk = new CharChunk(); /** * Encoding to use. */ private String enc; /** * Encoder is set. */ private boolean gotEnc = false; /** * List of encoders. */ protected final HashMap<String, C2BConverter> encoders = new HashMap<>(); /** * Current char to byte converter. */ protected C2BConverter conv; /** * Associated Coyote response. */ private Response coyoteResponse; /** * Suspended flag. All output bytes will be swallowed if this is true. */ private boolean suspended = false; // ----------------------------------------------------------- Constructors /** * Default constructor. Allocate the buffer with the default buffer size. */ public OutputBuffer() { this(DEFAULT_BUFFER_SIZE); } /** * Alternate constructor which allows specifying the initial buffer size. * * @param size Buffer size to use */ public OutputBuffer(int size) { bb = new ByteChunk(size); bb.setLimit(size); bb.setByteOutputChannel(this); cb = new CharChunk(size); cb.setLimit(size); cb.setOptimizedWrite(false); cb.setCharOutputChannel(this); } // ------------------------------------------------------------- Properties /** * Associated Coyote response. * * @param coyoteResponse Associated Coyote response */ public void setResponse(Response coyoteResponse) { this.coyoteResponse = coyoteResponse; } /** * Is the response output suspended ? * * @return suspended flag value */ public boolean isSuspended() { return this.suspended; } /** * Set the suspended flag. * * @param suspended New suspended flag value */ public void setSuspended(boolean suspended) { this.suspended = suspended; } /** * Is the response output closed ? * * @return closed flag value */ public boolean isClosed() { return this.closed; } // --------------------------------------------------------- Public Methods /** * Recycle the output buffer. */ public void recycle() { initial = true; bytesWritten = 0; charsWritten = 0; bb.recycle(); cb.recycle(); outputCharChunk.setChars(null, 0, 0); closed = false; suspended = false; doFlush = false; if (conv!= null) { conv.recycle(); } gotEnc = false; enc = null; } /** * Clear cached encoders (to save memory for Comet requests). */ public void clearEncoders() { encoders.clear(); } /** * Close the output buffer. This tries to calculate the response size if * the response has not been committed yet. * * @throws IOException An underlying IOException occurred */ @Override public void close() throws IOException { if (closed) { return; } if (suspended) { return; } // If there are chars, flush all of them to the byte buffer now as bytes are used to // calculate the content-length (if everything fits into the byte buffer, of course). if (cb.getLength() > 0) { cb.flushBuffer(); } if ((!coyoteResponse.isCommitted()) && (coyoteResponse.getContentLengthLong() == -1)) { // If this didn't cause a commit of the response, the final content // length can be calculated if (!coyoteResponse.isCommitted()) { coyoteResponse.setContentLength(bb.getLength()); } } if (coyoteResponse.getStatus() == HttpServletResponse.SC_SWITCHING_PROTOCOLS) { doFlush(true); } else { doFlush(false); } closed = true; // The request should have been completely read by the time the response // is closed. Further reads of the input a) are pointless and b) really // confuse AJP (bug 50189) so close the input buffer to prevent them. Request req = (Request) coyoteResponse.getRequest().getNote( CoyoteAdapter.ADAPTER_NOTES); req.inputBuffer.close(); coyoteResponse.finish(); } /** * Flush bytes or chars contained in the buffer. * * @throws IOException An underlying IOException occurred */ @Override public void flush() throws IOException { doFlush(true); } /** * Flush bytes or chars contained in the buffer. * * @throws IOException An underlying IOException occurred */ protected void doFlush(boolean realFlush) throws IOException { if (suspended) { return; } try { doFlush = true; if (initial) { coyoteResponse.sendHeaders(); initial = false; } if (cb.getLength() > 0) { cb.flushBuffer(); } if (bb.getLength() > 0) { bb.flushBuffer(); } } finally { doFlush = false; } if (realFlush) { coyoteResponse.action(ActionCode.CLIENT_FLUSH, coyoteResponse); // If some exception occurred earlier, or if some IOE occurred // here, notify the servlet with an IOE if (coyoteResponse.isExceptionPresent()) { throw new ClientAbortException (coyoteResponse.getErrorException()); } } } // ------------------------------------------------- Bytes Handling Methods /** * Sends the buffer data to the client output, checking the * state of Response and calling the right interceptors. * * @param buf Byte buffer to be written to the response * @param off Offset * @param cnt Length * * @throws IOException An underlying IOException occurred */ @Override public void realWriteBytes(byte buf[], int off, int cnt) throws IOException { if (closed) { return; } if (coyoteResponse == null) { return; } // If we really have something to write if (cnt > 0) { // real write to the adapter outputChunk.setBytes(buf, off, cnt); try { coyoteResponse.doWrite(outputChunk); } catch (IOException e) { // An IOException on a write is almost always due to // the remote client aborting the request. Wrap this // so that it can be handled better by the error dispatcher. throw new ClientAbortException(e); } } } public void write(byte b[], int off, int len) throws IOException { if (suspended) { return; } writeBytes(b, off, len); } private void writeBytes(byte b[], int off, int len) throws IOException { if (closed) { return; } bb.append(b, off, len); bytesWritten += len; // if called from within flush(), then immediately flush // remaining bytes if (doFlush) { bb.flushBuffer(); } } public void writeByte(int b) throws IOException { if (suspended) { return; } bb.append((byte) b); bytesWritten++; } // ------------------------------------------------- Chars Handling Methods /** * Convert the chars to bytes, then send the data to the client. * * @param buf Char buffer to be written to the response * @param off Offset * @param len Length * * @throws IOException An underlying IOException occurred */ @Override public void realWriteChars(char buf[], int off, int len) throws IOException { outputCharChunk.setChars(buf, off, len); while (outputCharChunk.getLength() > 0) { conv.convert(outputCharChunk, bb); if (bb.getLength() == 0) { // Break out of the loop if more chars are needed to produce any output break; } if (outputCharChunk.getLength() > 0) { bb.flushBuffer(); } } } @Override public void write(int c) throws IOException { if (suspended) { return; } cb.append((char) c); charsWritten++; } @Override public void write(char c[]) throws IOException { if (suspended) { return; } write(c, 0, c.length); } @Override public void write(char c[], int off, int len) throws IOException { if (suspended) { return; } cb.append(c, off, len); charsWritten += len; } /** * Append a string to the buffer */ @Override public void write(String s, int off, int len) throws IOException { if (suspended) { return; } charsWritten += len; if (s == null) { s = "null"; } cb.append(s, off, len); charsWritten += len; } @Override public void write(String s) throws IOException { if (suspended) { return; } if (s == null) { s = "null"; } cb.append(s); charsWritten += s.length(); } public void setEncoding(String s) { enc = s; } public void checkConverter() throws IOException { if (!gotEnc) { setConverter(); } } protected void setConverter() throws IOException { if (coyoteResponse != null) { enc = coyoteResponse.getCharacterEncoding(); } gotEnc = true; if (enc == null) { enc = DEFAULT_ENCODING; } conv = encoders.get(enc); if (conv == null) { if (Globals.IS_SECURITY_ENABLED){ try{ conv = AccessController.doPrivileged( new PrivilegedExceptionAction<C2BConverter>(){ @Override public C2BConverter run() throws IOException{ return new C2BConverter(enc); } } ); }catch(PrivilegedActionException ex){ Exception e = ex.getException(); if (e instanceof IOException) { throw (IOException)e; } } } else { conv = new C2BConverter(enc); } encoders.put(enc, conv); } } // -------------------- BufferedOutputStream compatibility public long getContentWritten() { return bytesWritten + charsWritten; } /** * True if this buffer hasn't been used ( since recycle() ) - * i.e. no chars or bytes have been added to the buffer. */ public boolean isNew() { return (bytesWritten == 0) && (charsWritten == 0); } public void setBufferSize(int size) { if (size > bb.getLimit()) {// ?????? bb.setLimit(size); } } public void reset() { reset(false); } public void reset(boolean resetWriterStreamFlags) { bb.recycle(); cb.recycle(); bytesWritten = 0; charsWritten = 0; if (resetWriterStreamFlags) { gotEnc = false; enc = null; } initial = true; } public int getBufferSize() { return bb.getLimit(); } /* * All the non-blocking write state information is held in the Response so * it is visible / accessible to all the code that needs it. */ public boolean isReady() { return coyoteResponse.isReady(); } public void setWriteListener(WriteListener listener) { coyoteResponse.setWriteListener(listener); } public boolean isBlocking() { return coyoteResponse.getWriteListener() == null; } public void checkRegisterForWrite() { coyoteResponse.checkRegisterForWrite(true); } }
55,842
Bug 55842 response.setBufferSize() does not seem to work properly
I found a problem with setting the buffer size for the ServletResponse. If I call 'response.setBufferSize(1,000,000);' and send about 20,000 characters, the response will be chunked even though it should not. The response is sent in several chunks and contains the 'Transfer-Encoding: chunked' response header. In my understanding in this case the response should be fully buffered on the server and then sent as a whole containing the Content-Length-header. This causes a problem in my application because I want to use a larger buffer to be able to redirect to an error page if an error occurs during rendering the response. I was able to reproduce this on Tomcat 7.0.39, 7.0.40, 7.0.42, 7.0.47. Tomcat 7.0.37 works fine and as expected. This is easily reproducable by using a JSP as follows: <% response.setBufferSize(1000*1000); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { response.getWriter().write("X"); } response.getWriter().write("<br />"); } %>
resolved fixed
f4970a7
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-06T12:12:15Z
2013-12-04T20:46:40Z
java/org/apache/tomcat/util/buf/ByteChunk.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.Serializable; import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; /* * In a server it is very important to be able to operate on * the original byte[] without converting everything to chars. * Some protocols are ASCII only, and some allow different * non-UNICODE encodings. The encoding is not known beforehand, * and can even change during the execution of the protocol. * ( for example a multipart message may have parts with different * encoding ) * * For HTTP it is not very clear how the encoding of RequestURI * and mime values can be determined, but it is a great advantage * to be able to parse the request without converting to string. */ // TODO: This class could either extend ByteBuffer, or better a ByteBuffer // inside this way it could provide the search/etc on ByteBuffer, as a helper. /** * This class is used to represent a chunk of bytes, and * utilities to manipulate byte[]. * * The buffer can be modified and used for both input and output. * * There are 2 modes: The chunk can be associated with a sink - ByteInputChannel * or ByteOutputChannel, which will be used when the buffer is empty (on input) * or filled (on output). * For output, it can also grow. This operating mode is selected by calling * setLimit() or allocate(initial, limit) with limit != -1. * * Various search and append method are defined - similar with String and * StringBuffer, but operating on bytes. * * This is important because it allows processing the http headers directly on * the received bytes, without converting to chars and Strings until the strings * are needed. In addition, the charset is determined later, from headers or * user code. * * @author dac@sun.com * @author James Todd [gonzo@sun.com] * @author Costin Manolache * @author Remy Maucherat */ public final class ByteChunk implements Cloneable, Serializable { private static final long serialVersionUID = 1L; /** Input interface, used when the buffer is empty * * Same as java.nio.channel.ReadableByteChannel */ public static interface ByteInputChannel { /** * Read new bytes ( usually the internal conversion buffer ). * The implementation is allowed to ignore the parameters, * and mutate the chunk if it wishes to implement its own buffering. */ public int realReadBytes(byte cbuf[], int off, int len) throws IOException; } /** Same as java.nio.channel.WrittableByteChannel. */ public static interface ByteOutputChannel { /** * Send the bytes ( usually the internal conversion buffer ). * Expect 8k output if the buffer is full. */ public void realWriteBytes(byte cbuf[], int off, int len) throws IOException; } // -------------------- /** Default encoding used to convert to strings. It should be UTF8, as most standards seem to converge, but the servlet API requires 8859_1, and this object is used mostly for servlets. */ public static final Charset DEFAULT_CHARSET = StandardCharsets.ISO_8859_1; private int hashCode=0; // did we compute the hashcode ? private boolean hasHashCode = false; // byte[] private byte[] buff; private int start=0; private int end; private Charset charset; private boolean isSet=false; // XXX // How much can it grow, when data is added private int limit=-1; private ByteInputChannel in = null; private ByteOutputChannel out = null; /** * Creates a new, uninitialized ByteChunk object. */ public ByteChunk() { // NO-OP } public ByteChunk( int initial ) { allocate( initial, -1 ); } public boolean isNull() { return ! isSet; // buff==null; } /** * Resets the message buff to an uninitialized state. */ public void recycle() { // buff = null; charset=null; start=0; end=0; isSet=false; hasHashCode = false; } public void reset() { buff=null; } // -------------------- Setup -------------------- public void allocate( int initial, int limit ) { if( buff==null || buff.length < initial ) { buff=new byte[initial]; } this.limit=limit; start=0; end=0; isSet=true; hasHashCode = false; } /** * Sets the message bytes to the specified subarray of bytes. * * @param b the ascii bytes * @param off the start offset of the bytes * @param len the length of the bytes */ public void setBytes(byte[] b, int off, int len) { buff = b; start = off; end = start+ len; isSet=true; hasHashCode = false; } public void setCharset(Charset charset) { this.charset = charset; } public Charset getCharset() { if (charset == null) { charset = DEFAULT_CHARSET; } return charset; } /** * Returns the message bytes. */ public byte[] getBytes() { return getBuffer(); } /** * Returns the message bytes. */ public byte[] getBuffer() { return buff; } /** * Returns the start offset of the bytes. * For output this is the end of the buffer. */ public int getStart() { return start; } public int getOffset() { return start; } public void setOffset(int off) { if (end < off ) { end=off; } start=off; } /** * Returns the length of the bytes. * XXX need to clean this up */ public int getLength() { return end-start; } /** Maximum amount of data in this buffer. * * If -1 or not set, the buffer will grow indefinitely. * Can be smaller than the current buffer size ( which will not shrink ). * When the limit is reached, the buffer will be flushed ( if out is set ) * or throw exception. */ public void setLimit(int limit) { this.limit=limit; } public int getLimit() { return limit; } /** * When the buffer is empty, read the data from the input channel. */ public void setByteInputChannel(ByteInputChannel in) { this.in = in; } /** When the buffer is full, write the data to the output channel. * Also used when large amount of data is appended. * * If not set, the buffer will grow to the limit. */ public void setByteOutputChannel(ByteOutputChannel out) { this.out=out; } public int getEnd() { return end; } public void setEnd( int i ) { end=i; } // -------------------- Adding data to the buffer -------------------- public void append( byte b ) throws IOException { makeSpace( 1 ); // couldn't make space if( limit >0 && end >= limit ) { flushBuffer(); } buff[end++]=b; } public void append( ByteChunk src ) throws IOException { append( src.getBytes(), src.getStart(), src.getLength()); } /** Add data to the buffer */ public void append( byte src[], int off, int len ) throws IOException { // will grow, up to limit makeSpace( len ); // if we don't have limit: makeSpace can grow as it wants if( limit < 0 ) { // assert: makeSpace made enough space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // Optimize on a common case. // If the buffer is empty and the source is going to fill up all the // space in buffer, may as well write it directly to the output, // and avoid an extra copy if ( len == limit && end == start && out != null ) { out.realWriteBytes( src, off, len ); return; } // if we have limit and we're below if( len <= limit - end ) { // makeSpace will grow the buffer to the limit, // so we have space System.arraycopy( src, off, buff, end, len ); end+=len; return; } // need more space than we can afford, need to flush // buffer // the buffer is already at ( or bigger than ) limit // We chunk the data into slices fitting in the buffer limit, although // if the data is written directly if it doesn't fit int avail=limit-end; System.arraycopy(src, off, buff, end, avail); end += avail; flushBuffer(); int remain = len - avail; while (remain > (limit - end)) { out.realWriteBytes( src, (off + len) - remain, limit - end ); remain = remain - (limit - end); } System.arraycopy(src, (off + len) - remain, buff, end, remain); end += remain; } // -------------------- Removing data from the buffer -------------------- public int substract() throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) { return -1; } } return (buff[start++] & 0xFF); } public byte substractB() throws IOException { if ((end - start) == 0) { if (in == null) return -1; int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) return -1; } return (buff[start++]); } public int substract( byte src[], int off, int len ) throws IOException { if ((end - start) == 0) { if (in == null) { return -1; } int n = in.realReadBytes( buff, 0, buff.length ); if (n < 0) { return -1; } } int n = len; if (len > getLength()) { n = getLength(); } System.arraycopy(buff, start, src, off, n); start += n; return n; } /** * Send the buffer to the sink. Called by append() when the limit is * reached. You can also call it explicitly to force the data to be written. * * @throws IOException */ public void flushBuffer() throws IOException { //assert out!=null if( out==null ) { throw new IOException( "Buffer overflow, no sink " + limit + " " + buff.length ); } out.realWriteBytes( buff, start, end-start ); end=start; } /** Make space for len chars. If len is small, allocate * a reserve space too. Never grow bigger than limit. */ private void makeSpace(int count) { byte[] tmp = null; int newSize; int desiredSize=end + count; // Can't grow above the limit if( limit > 0 && desiredSize > limit) { desiredSize=limit; } if( buff==null ) { if( desiredSize < 256 ) { desiredSize=256; // take a minimum } buff=new byte[desiredSize]; } // limit < buf.length ( the buffer is already big ) // or we already have space XXX if( desiredSize <= buff.length ) { return; } // grow in larger chunks if( desiredSize < 2 * buff.length ) { newSize= buff.length * 2; if( limit >0 && newSize > limit ) { newSize=limit; } tmp=new byte[newSize]; } else { newSize= buff.length * 2 + count ; if( limit > 0 && newSize > limit ) { newSize=limit; } tmp=new byte[newSize]; } System.arraycopy(buff, start, tmp, 0, end-start); buff = tmp; tmp = null; end=end-start; start=0; } // -------------------- Conversion and getters -------------------- @Override public String toString() { if (null == buff) { return null; } else if (end-start == 0) { return ""; } return StringCache.toString(this); } public String toStringInternal() { if (charset == null) { charset = DEFAULT_CHARSET; } // new String(byte[], int, int, Charset) takes a defensive copy of the // entire byte array. This is expensive if only a small subset of the // bytes will be used. The code below is from Apache Harmony. CharBuffer cb; cb = charset.decode(ByteBuffer.wrap(buff, start, end-start)); return new String(cb.array(), cb.arrayOffset(), cb.length()); } public long getLong() { return Ascii.parseLong(buff, start,end-start); } // -------------------- equals -------------------- @Override public boolean equals(Object obj) { if (obj instanceof ByteChunk) { return equals((ByteChunk) obj); } return false; } /** * Compares the message bytes to the specified String object. * @param s the String to compare * @return true if the comparison succeeded, false otherwise */ public boolean equals(String s) { // XXX ENCODING - this only works if encoding is UTF8-compat // ( ok for tomcat, where we compare ascii - header names, etc )!!! byte[] b = buff; int blen = end-start; if (b == null || blen != s.length()) { return false; } int boff = start; for (int i = 0; i < blen; i++) { if (b[boff++] != s.charAt(i)) { return false; } } return true; } /** * Compares the message bytes to the specified String object. * @param s the String to compare * @return true if the comparison succeeded, false otherwise */ public boolean equalsIgnoreCase(String s) { byte[] b = buff; int blen = end-start; if (b == null || blen != s.length()) { return false; } int boff = start; for (int i = 0; i < blen; i++) { if (Ascii.toLower(b[boff++]) != Ascii.toLower(s.charAt(i))) { return false; } } return true; } public boolean equals( ByteChunk bb ) { return equals( bb.getBytes(), bb.getStart(), bb.getLength()); } public boolean equals( byte b2[], int off2, int len2) { byte b1[]=buff; if( b1==null && b2==null ) { return true; } int len=end-start; if ( len2 != len || b1==null || b2==null ) { return false; } int off1 = start; while ( len-- > 0) { if (b1[off1++] != b2[off2++]) { return false; } } return true; } public boolean equals( CharChunk cc ) { return equals( cc.getChars(), cc.getStart(), cc.getLength()); } public boolean equals( char c2[], int off2, int len2) { // XXX works only for enc compatible with ASCII/UTF !!! byte b1[]=buff; if( c2==null && b1==null ) { return true; } if (b1== null || c2==null || end-start != len2 ) { return false; } int off1 = start; int len=end-start; while ( len-- > 0) { if ( (char)b1[off1++] != c2[off2++]) { return false; } } return true; } /** * Returns true if the message bytes starts with the specified string. * @param s the string * @param pos The position */ public boolean startsWithIgnoreCase(String s, int pos) { byte[] b = buff; int len = s.length(); if (b == null || len+pos > end-start) { return false; } int off = start+pos; for (int i = 0; i < len; i++) { if (Ascii.toLower( b[off++] ) != Ascii.toLower( s.charAt(i))) { return false; } } return true; } public int indexOf( String src, int srcOff, int srcLen, int myOff ) { char first=src.charAt( srcOff ); // Look for first char int srcEnd = srcOff + srcLen; mainLoop: for( int i=myOff+start; i <= (end - srcLen); i++ ) { if( buff[i] != first ) { continue; } // found first char, now look for a match int myPos=i+1; for( int srcPos=srcOff + 1; srcPos< srcEnd;) { if( buff[myPos++] != src.charAt( srcPos++ )) { continue mainLoop; } } return i-start; // found it } return -1; } // -------------------- Hash code -------------------- @Override public int hashCode() { if (hasHashCode) { return hashCode; } int code = 0; code = hash(); hashCode = code; hasHashCode = true; return code; } // normal hash. public int hash() { return hashBytes( buff, start, end-start); } private static int hashBytes( byte buff[], int start, int bytesLen ) { int max=start+bytesLen; byte bb[]=buff; int code=0; for (int i = start; i < max ; i++) { code = code * 37 + bb[i]; } return code; } /** * Returns the first instance of the given character in this ByteChunk * starting at the specified byte. If the character is not found, -1 is * returned. * <br/> * NOTE: This only works for characters in the range 0-127. * * @param c The character * @param starting The start position * @return The position of the first instance of the character or * -1 if the character is not found. */ public int indexOf(char c, int starting) { int ret = indexOf(buff, start + starting, end, c); return (ret >= start) ? ret - start : -1; } /** * Returns the first instance of the given character in the given byte array * between the specified start and end. * <br/> * NOTE: This only works for characters in the range 0-127. * * @param bytes The byte array to search * @param start The point to start searching from in the byte array * @param end The point to stop searching in the byte array * @param c The character to search for * @return The position of the first instance of the character or -1 * if the character is not found. */ public static int indexOf(byte bytes[], int start, int end, char c) { int offset = start; while (offset < end) { byte b=bytes[offset]; if (b == c) { return offset; } offset++; } return -1; } /** * Returns the first instance of the given byte in the byte array between * the specified start and end. * * @param bytes The byte array to search * @param start The point to start searching from in the byte array * @param end The point to stop searching in the byte array * @param b The byte to search for * @return The position of the first instance of the byte or -1 if the * byte is not found. */ public static int findByte(byte bytes[], int start, int end, byte b) { int offset = start; while (offset < end) { if (bytes[offset] == b) { return offset; } offset++; } return -1; } /** * Returns the first instance of any of the given bytes in the byte array * between the specified start and end. * * @param bytes The byte array to search * @param start The point to start searching from in the byte array * @param end The point to stop searching in the byte array * @param b The array of bytes to search for * @return The position of the first instance of the byte or -1 if the * byte is not found. */ public static int findBytes(byte bytes[], int start, int end, byte b[]) { int blen = b.length; int offset = start; while (offset < end) { for (int i = 0; i < blen; i++) { if (bytes[offset] == b[i]) { return offset; } } offset++; } return -1; } /** * Convert specified String to a byte array. This ONLY WORKS for ascii, UTF * chars will be truncated. * * @param value to convert to byte array * @return the byte array value */ public static final byte[] convertToBytes(String value) { byte[] result = new byte[value.length()]; for (int i = 0; i < value.length(); i++) { result[i] = (byte) value.charAt(i); } return result; } }
55,851
Bug 55851 Tomcat SPNEGO authenticator incompatible with IBM JDK: Accept Security Context needs to be wrapped around a Privileged Action in order for server side authentication
null
resolved fixed
bba9747
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-06T19:42:43Z
2013-12-06T14:26:40Z
java/org/apache/catalina/authenticator/SpnegoAuthenticator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.authenticator; import java.io.File; import java.io.IOException; import java.security.Principal; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.regex.Pattern; import javax.security.auth.Subject; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.LifecycleException; import org.apache.catalina.connector.Request; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.codec.binary.Base64; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSException; import org.ietf.jgss.GSSManager; import org.ietf.jgss.Oid; /** * A SPNEGO authenticator that uses the SPNEGO/Kerberos support built in to Java * 6. Successful Kerberos authentication depends on the correct configuration of * multiple components. If the configuration is invalid, the error messages are * often cryptic although a Google search will usually point you in the right * direction. */ public class SpnegoAuthenticator extends AuthenticatorBase { private static final Log log = LogFactory.getLog(SpnegoAuthenticator.class); private String loginConfigName = Constants.DEFAULT_LOGIN_MODULE_NAME; public String getLoginConfigName() { return loginConfigName; } public void setLoginConfigName(String loginConfigName) { this.loginConfigName = loginConfigName; } private boolean storeDelegatedCredential = true; public boolean isStoreDelegatedCredential() { return storeDelegatedCredential; } public void setStoreDelegatedCredential( boolean storeDelegatedCredential) { this.storeDelegatedCredential = storeDelegatedCredential; } private Pattern noKeepAliveUserAgents = null; public String getNoKeepAliveUserAgents() { Pattern p = noKeepAliveUserAgents; if (p == null) { return null; } else { return p.pattern(); } } public void setNoKeepAliveUserAgents(String noKeepAliveUserAgents) { if (noKeepAliveUserAgents == null || noKeepAliveUserAgents.length() == 0) { this.noKeepAliveUserAgents = null; } else { this.noKeepAliveUserAgents = Pattern.compile(noKeepAliveUserAgents); } } @Override protected String getAuthMethod() { return Constants.SPNEGO_METHOD; } @Override protected void initInternal() throws LifecycleException { super.initInternal(); // Kerberos configuration file location String krb5Conf = System.getProperty(Constants.KRB5_CONF_PROPERTY); if (krb5Conf == null) { // System property not set, use the Tomcat default File krb5ConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_KRB5_CONF); System.setProperty(Constants.KRB5_CONF_PROPERTY, krb5ConfFile.getAbsolutePath()); } // JAAS configuration file location String jaasConf = System.getProperty(Constants.JAAS_CONF_PROPERTY); if (jaasConf == null) { // System property not set, use the Tomcat default File jaasConfFile = new File(container.getCatalinaBase(), Constants.DEFAULT_JAAS_CONF); System.setProperty(Constants.JAAS_CONF_PROPERTY, jaasConfFile.getAbsolutePath()); } } @Override public boolean authenticate(Request request, HttpServletResponse response) throws IOException { // Have we already authenticated someone? Principal principal = request.getUserPrincipal(); String ssoId = (String) request.getNote(Constants.REQ_SSOID_NOTE); if (principal != null) { if (log.isDebugEnabled()) { log.debug("Already authenticated '" + principal.getName() + "'"); } // Associate the session with any existing SSO session if (ssoId != null) { associate(ssoId, request.getSessionInternal(true)); } return true; } // Is there an SSO session against which we can try to reauthenticate? if (ssoId != null) { if (log.isDebugEnabled()) { log.debug("SSO Id " + ssoId + " set; attempting " + "reauthentication"); } /* Try to reauthenticate using data cached by SSO. If this fails, either the original SSO logon was of DIGEST or SSL (which we can't reauthenticate ourselves because there is no cached username and password), or the realm denied the user's reauthentication for some reason. In either case we have to prompt the user for a logon */ if (reauthenticateFromSSO(ssoId, request)) { return true; } } MessageBytes authorization = request.getCoyoteRequest().getMimeHeaders() .getValue("authorization"); if (authorization == null) { if (log.isDebugEnabled()) { log.debug(sm.getString("authenticator.noAuthHeader")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorization.toBytes(); ByteChunk authorizationBC = authorization.getByteChunk(); if (!authorizationBC.startsWithIgnoreCase("negotiate ", 0)) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNotNego")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } authorizationBC.setOffset(authorizationBC.getOffset() + 10); byte[] decoded = Base64.decodeBase64(authorizationBC.getBuffer(), authorizationBC.getOffset(), authorizationBC.getLength()); if (decoded.length == 0) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.authHeaderNoToken")); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } LoginContext lc = null; GSSContext gssContext = null; byte[] outToken = null; try { try { lc = new LoginContext(getLoginConfigName()); lc.login(); } catch (LoginException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return false; } // Assume the GSSContext is stateless // TODO: Confirm this assumption final GSSManager manager = GSSManager.getInstance(); final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() { @Override public GSSCredential run() throws GSSException { return manager.createCredential(null, GSSCredential.DEFAULT_LIFETIME, new Oid("1.3.6.1.5.5.2"), GSSCredential.ACCEPT_ONLY); } }; gssContext = manager.createContext(Subject.doAs(lc.getSubject(), action)); outToken = gssContext.acceptSecContext(decoded, 0, decoded.length); if (outToken == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "spnegoAuthenticator.ticketValidateFail")); } // Start again response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } principal = context.getRealm().authenticate(gssContext, isStoreDelegatedCredential()); } catch (GSSException e) { if (log.isDebugEnabled()) { log.debug(sm.getString("spnegoAuthenticator.ticketValidateFail"), e); } response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } catch (PrivilegedActionException e) { log.error(sm.getString("spnegoAuthenticator.serviceLoginFail"), e); response.setHeader("WWW-Authenticate", "Negotiate"); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } finally { if (gssContext != null) { try { gssContext.dispose(); } catch (GSSException e) { // Ignore } } if (lc != null) { try { lc.logout(); } catch (LoginException e) { // Ignore } } } // Send response token on success and failure response.setHeader("WWW-Authenticate", "Negotiate " + Base64.encodeBase64String(outToken)); if (principal != null) { register(request, response, principal, Constants.SPNEGO_METHOD, principal.getName(), null); Pattern p = noKeepAliveUserAgents; if (p != null) { MessageBytes ua = request.getCoyoteRequest().getMimeHeaders().getValue( "user-agent"); if (ua != null && p.matcher(ua.toString()).matches()) { response.setHeader("Connection", "close"); } } return true; } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return false; } }
55,801
Bug 55801 Add ability to provide custom SSLContext for websocket client
null
resolved fixed
ef3f56e
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-07T20:10:59Z
2013-11-20T15:06:40Z
java/org/apache/tomcat/websocket/WsWebSocketContainer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.websocket; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousChannelGroup; import java.nio.channels.AsynchronousSocketChannel; import java.nio.charset.StandardCharsets; import java.security.KeyStore; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLException; import javax.net.ssl.TrustManagerFactory; import javax.websocket.ClientEndpoint; import javax.websocket.ClientEndpointConfig; import javax.websocket.CloseReason; import javax.websocket.CloseReason.CloseCodes; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.Extension; import javax.websocket.HandshakeResponse; import javax.websocket.Session; import javax.websocket.WebSocketContainer; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.codec.binary.Base64; import org.apache.tomcat.util.res.StringManager; import org.apache.tomcat.util.threads.ThreadPoolExecutor; import org.apache.tomcat.websocket.pojo.PojoEndpointClient; public class WsWebSocketContainer implements WebSocketContainer, BackgroundProcess { /** * Property name to set to configure the value that is passed to * {@link SSLEngine#setEnabledProtocols(String[])}. The value should be a * comma separated string. */ public static final String SSL_PROTOCOLS_PROPERTY = "org.apache.tomcat.websocket.SSL_PROTOCOLS"; public static final String SSL_TRUSTSTORE_PROPERTY = "org.apache.tomcat.websocket.SSL_TRUSTSTORE"; public static final String SSL_TRUSTSTORE_PWD_PROPERTY = "org.apache.tomcat.websocket.SSL_TRUSTSTORE_PWD"; public static final String SSL_TRUSTSTORE_PWD_DEFAULT = "changeit"; /** * Property name to set to configure the timeout (in milliseconds) when * establishing a WebSocket connection to server. The default is * {@link #IO_TIMEOUT_MS_DEFAULT}. */ public static final String IO_TIMEOUT_MS_PROPERTY = "org.apache.tomcat.websocket.IO_TIMEOUT_MS"; public static final long IO_TIMEOUT_MS_DEFAULT = 5000; private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private static final Random random = new Random(); private static final byte[] crlf = new byte[] {13, 10}; private static final AsynchronousChannelGroup asynchronousChannelGroup; static { AsynchronousChannelGroup result = null; // Need to do this with the right thread context class loader else the // first web app to call this will trigger a leak ClassLoader original = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader( AsyncIOThreadFactory.class.getClassLoader()); // These are the same settings as the default // AsynchronousChannelGroup int initialSize = Runtime.getRuntime().availableProcessors(); ExecutorService executorService = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, Long.MAX_VALUE, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(), new AsyncIOThreadFactory()); try { result = AsynchronousChannelGroup.withCachedThreadPool( executorService, initialSize); } catch (IOException e) { // No good reason for this to happen. throw new IllegalStateException(sm.getString( "wsWebSocketContainer.asynchronousChannelGroupFail")); } } finally { Thread.currentThread().setContextClassLoader(original); } asynchronousChannelGroup = result; } private final Log log = LogFactory.getLog(WsWebSocketContainer.class); private final Map<Class<?>, Set<WsSession>> endpointSessionMap = new HashMap<>(); private final Map<WsSession,WsSession> sessions = new ConcurrentHashMap<>(); private final Object endPointSessionMapLock = new Object(); private long defaultAsyncTimeout = -1; private int maxBinaryMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private int maxTextMessageBufferSize = Constants.DEFAULT_BUFFER_SIZE; private volatile long defaultMaxSessionIdleTimeout = 0; private int backgroundProcessCount = 0; private int processPeriod = 10; @Override public Session connectToServer(Object pojo, URI path) throws DeploymentException { ClientEndpoint annotation = pojo.getClass().getAnnotation(ClientEndpoint.class); if (annotation == null) { throw new DeploymentException( sm.getString("wsWebSocketContainer.missingAnnotation", pojo.getClass().getName())); } Endpoint ep = new PojoEndpointClient(pojo, annotation.decoders()); Class<? extends ClientEndpointConfig.Configurator> configuratorClazz = pojo.getClass().getAnnotation( ClientEndpoint.class).configurator(); ClientEndpointConfig.Configurator configurator = null; if (!ClientEndpointConfig.Configurator.class.equals( configuratorClazz)) { try { configurator = configuratorClazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.defaultConfiguratorFail"), e); } } ClientEndpointConfig config = ClientEndpointConfig.Builder.create(). configurator(configurator). decoders(Arrays.asList(annotation.decoders())). encoders(Arrays.asList(annotation.encoders())). build(); return connectToServer(ep, config, path); } @Override public Session connectToServer(Class<?> annotatedEndpointClass, URI path) throws DeploymentException { Object pojo; try { pojo = annotatedEndpointClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", annotatedEndpointClass.getName()), e); } return connectToServer(pojo, path); } @Override public Session connectToServer(Class<? extends Endpoint> clazz, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { Endpoint endpoint; try { endpoint = clazz.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.endpointCreateFail", clazz.getName()), e); } return connectToServer(endpoint, clientEndpointConfiguration, path); } @Override public Session connectToServer(Endpoint endpoint, ClientEndpointConfig clientEndpointConfiguration, URI path) throws DeploymentException { boolean secure = false; String scheme = path.getScheme(); if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme))) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.pathWrongScheme", scheme)); } String host = path.getHost(); if (host == null) { throw new DeploymentException( sm.getString("wsWebSocketContainer.pathNoHost")); } int port = path.getPort(); Map<String,List<String>> reqHeaders = createRequestHeaders(host, port, clientEndpointConfiguration.getPreferredSubprotocols(), clientEndpointConfiguration.getExtensions()); clientEndpointConfiguration.getConfigurator(). beforeRequest(reqHeaders); ByteBuffer request = createRequest(path, reqHeaders); SocketAddress sa; if (port == -1) { if ("ws".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 80); } else if ("wss".equalsIgnoreCase(scheme)) { sa = new InetSocketAddress(host, 443); secure = true; } else { throw new DeploymentException( sm.getString("wsWebSocketContainer.invalidScheme")); } } else { if ("wss".equalsIgnoreCase(scheme)) { secure = true; } sa = new InetSocketAddress(host, port); } AsynchronousSocketChannel socketChannel; try { socketChannel = AsynchronousSocketChannel.open(asynchronousChannelGroup); } catch (IOException ioe) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.asynchronousSocketChannelFail"), ioe); } Future<Void> fConnect = socketChannel.connect(sa); AsyncChannelWrapper channel; if (secure) { SSLEngine sslEngine = createSSLEngine( clientEndpointConfiguration.getUserProperties()); channel = new AsyncChannelWrapperSecure(socketChannel, sslEngine); } else { channel = new AsyncChannelWrapperNonSecure(socketChannel); } // Get the connection timeout long timeout = IO_TIMEOUT_MS_DEFAULT; String timeoutValue = (String) clientEndpointConfiguration.getUserProperties().get( IO_TIMEOUT_MS_PROPERTY); if (timeoutValue != null) { timeout = Long.valueOf(timeoutValue).intValue(); } ByteBuffer response; String subProtocol; try { fConnect.get(timeout, TimeUnit.MILLISECONDS); Future<Void> fHandshake = channel.handshake(); fHandshake.get(timeout, TimeUnit.MILLISECONDS); int toWrite = request.limit(); Future<Integer> fWrite = channel.write(request); Integer thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS); toWrite -= thisWrite.intValue(); while (toWrite > 0) { fWrite = channel.write(request); thisWrite = fWrite.get(timeout, TimeUnit.MILLISECONDS); toWrite -= thisWrite.intValue(); } // Same size as the WsFrame input buffer response = ByteBuffer.allocate(maxBinaryMessageBufferSize); HandshakeResponse handshakeResponse = processResponse(response, channel, timeout); clientEndpointConfiguration.getConfigurator(). afterResponse(handshakeResponse); // Sub-protocol // Header names are always stored in lower case List<String> values = handshakeResponse.getHeaders().get( Constants.WS_PROTOCOL_HEADER_NAME_LOWER); if (values == null || values.size() == 0) { subProtocol = null; } else if (values.size() == 1) { subProtocol = values.get(0); } else { throw new DeploymentException( sm.getString("Sec-WebSocket-Protocol")); } } catch (ExecutionException | InterruptedException | SSLException | EOFException | TimeoutException e) { throw new DeploymentException( sm.getString("wsWebSocketContainer.httpRequestFailed"), e); } // Switch to WebSocket WsRemoteEndpointImplClient wsRemoteEndpointClient = new WsRemoteEndpointImplClient(channel); WsSession wsSession = new WsSession(endpoint, wsRemoteEndpointClient, this, null, null, null, null, null, subProtocol, Collections.<String, String> emptyMap(), false, clientEndpointConfiguration); endpoint.onOpen(wsSession, clientEndpointConfiguration); registerSession(endpoint, wsSession); // Object creation will trigger input processing @SuppressWarnings("unused") WsFrameClient wsFrameClient = new WsFrameClient(response, channel, wsSession); return wsSession; } protected void registerSession(Endpoint endpoint, WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); if (!wsSession.isOpen()) { // The session was closed during onOpen. No need to register it. return; } synchronized (endPointSessionMapLock) { if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().register(this); } Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions == null) { wsSessions = new HashSet<>(); endpointSessionMap.put(endpointClazz, wsSessions); } wsSessions.add(wsSession); } sessions.put(wsSession, wsSession); } protected void unregisterSession(Endpoint endpoint, WsSession wsSession) { Class<?> endpointClazz = endpoint.getClass(); synchronized (endPointSessionMapLock) { Set<WsSession> wsSessions = endpointSessionMap.get(endpointClazz); if (wsSessions != null) { wsSessions.remove(wsSession); if (wsSessions.size() == 0) { endpointSessionMap.remove(endpointClazz); } } if (endpointSessionMap.size() == 0) { BackgroundProcessManager.getInstance().unregister(this); } } sessions.remove(wsSession); } Set<Session> getOpenSessions(Class<?> endpoint) { HashSet<Session> result = new HashSet<>(); synchronized (endPointSessionMapLock) { Set<WsSession> sessions = endpointSessionMap.get(endpoint); if (sessions != null) { result.addAll(sessions); } } return result; } private Map<String,List<String>> createRequestHeaders(String host, int port, List<String> subProtocols, List<Extension> extensions) { Map<String,List<String>> headers = new HashMap<>(); // Host header List<String> hostValues = new ArrayList<>(1); if (port == -1) { hostValues.add(host); } else { hostValues.add(host + ':' + port); } headers.put(Constants.HOST_HEADER_NAME, hostValues); // Upgrade header List<String> upgradeValues = new ArrayList<>(1); upgradeValues.add(Constants.UPGRADE_HEADER_VALUE); headers.put(Constants.UPGRADE_HEADER_NAME, upgradeValues); // Connection header List<String> connectionValues = new ArrayList<>(1); connectionValues.add(Constants.CONNECTION_HEADER_VALUE); headers.put(Constants.CONNECTION_HEADER_NAME, connectionValues); // WebSocket version header List<String> wsVersionValues = new ArrayList<>(1); wsVersionValues.add(Constants.WS_VERSION_HEADER_VALUE); headers.put(Constants.WS_VERSION_HEADER_NAME, wsVersionValues); // WebSocket key List<String> wsKeyValues = new ArrayList<>(1); wsKeyValues.add(generateWsKeyValue()); headers.put(Constants.WS_KEY_HEADER_NAME, wsKeyValues); // WebSocket sub-protocols if (subProtocols != null && subProtocols.size() > 0) { headers.put(Constants.WS_PROTOCOL_HEADER_NAME, subProtocols); } // WebSocket extensions if (extensions != null && extensions.size() > 0) { headers.put(Constants.WS_EXTENSIONS_HEADER_NAME, generateExtensionHeaders(extensions)); } return headers; } private List<String> generateExtensionHeaders(List<Extension> extensions) { List<String> result = new ArrayList<>(extensions.size()); for (Extension extension : extensions) { StringBuilder header = new StringBuilder(); header.append(extension.getName()); for (Extension.Parameter param : extension.getParameters()) { header.append(';'); header.append(param.getName()); String value = param.getValue(); if (value != null && value.length() > 0) { header.append('='); header.append(value); } } } return result; } private String generateWsKeyValue() { byte[] keyBytes = new byte[16]; random.nextBytes(keyBytes); return Base64.encodeBase64String(keyBytes); } private ByteBuffer createRequest(URI uri, Map<String,List<String>> reqHeaders) { ByteBuffer result = ByteBuffer.allocate(4 * 1024); // Request line result.put("GET ".getBytes(StandardCharsets.ISO_8859_1)); result.put(uri.getRawPath().getBytes(StandardCharsets.ISO_8859_1)); String query = uri.getRawQuery(); if (query != null) { result.put((byte) '?'); result.put(query.getBytes(StandardCharsets.ISO_8859_1)); } result.put(" HTTP/1.1\r\n".getBytes(StandardCharsets.ISO_8859_1)); // 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(StandardCharsets.ISO_8859_1)); result.put(": ".getBytes(StandardCharsets.ISO_8859_1)); result.put(sb.toString().getBytes(StandardCharsets.ISO_8859_1)); result.put(crlf); } /** * Process response, blocking until HTTP response has been fully received. * @throws ExecutionException * @throws InterruptedException * @throws DeploymentException * @throws TimeoutException */ private HandshakeResponse processResponse(ByteBuffer response, AsyncChannelWrapper channel, long timeout) throws InterruptedException, ExecutionException, DeploymentException, EOFException, TimeoutException { Map<String,List<String>> headers = new HashMap<>(); boolean readStatus = false; boolean readHeaders = false; String line = null; while (!readHeaders) { // Blocking read Future<Integer> read = channel.read(response); Integer bytesRead = read.get(timeout, TimeUnit.MILLISECONDS); if (bytesRead.intValue() == -1) { throw new EOFException(); } response.flip(); while (response.hasRemaining() && !readHeaders) { if (line == null) { line = readLine(response); } else { line += readLine(response); } if ("\r\n".equals(line)) { readHeaders = true; } else if (line.endsWith("\r\n")) { if (readStatus) { parseHeaders(line, headers); } else { parseStatus(line); readStatus = true; } line = null; } } } return new WsHandshakeResponse(headers); } private void parseStatus(String line) throws DeploymentException { // This client only understands HTTP 1.1 // RFC2616 is case specific if (!line.startsWith("HTTP/1.1 101")) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.invalidStatus", line)); } } private void parseHeaders(String line, Map<String,List<String>> headers) { // Treat headers as single values by default. int index = line.indexOf(':'); if (index == -1) { log.warn(sm.getString("wsWebSocketContainer.invalidHeader", line)); return; } // Header names are case insensitive so always use lower case String headerName = line.substring(0, index).trim().toLowerCase(); // TODO handle known multi-value headers String headerValue = line.substring(index + 1).trim(); List<String> values = headers.get(headerName); if (values == null) { values = new ArrayList<>(1); headers.put(headerName, values); } values.add(headerValue); } private String readLine(ByteBuffer response) { // All ISO-8859-1 StringBuilder sb = new StringBuilder(); char c = 0; while (response.hasRemaining()) { c = (char) response.get(); sb.append(c); if (c == 10) { break; } } return sb.toString(); } private SSLEngine createSSLEngine(Map<String,Object> userProperties) throws DeploymentException { try { // Create the SSL Context SSLContext sslContext = SSLContext.getInstance("TLS"); // Trust store String sslTrustStoreValue = (String) userProperties.get(SSL_TRUSTSTORE_PROPERTY); if (sslTrustStoreValue != null) { String sslTrustStorePwdValue = (String) userProperties.get( SSL_TRUSTSTORE_PWD_PROPERTY); if (sslTrustStorePwdValue == null) { sslTrustStorePwdValue = SSL_TRUSTSTORE_PWD_DEFAULT; } File keyStoreFile = new File(sslTrustStoreValue); KeyStore ks = KeyStore.getInstance("JKS"); try (InputStream is = new FileInputStream(keyStoreFile)) { ks.load(is, sslTrustStorePwdValue.toCharArray()); } TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslContext.init(null, tmf.getTrustManagers(), null); } else { sslContext.init(null, null, null); } SSLEngine engine = sslContext.createSSLEngine(); String sslProtocolsValue = (String) userProperties.get(SSL_PROTOCOLS_PROPERTY); if (sslProtocolsValue != null) { engine.setEnabledProtocols(sslProtocolsValue.split(",")); } engine.setUseClientMode(true); return engine; } catch (Exception e) { throw new DeploymentException(sm.getString( "wsWebSocketContainer.sslEngineFail"), e); } } @Override public long getDefaultMaxSessionIdleTimeout() { return defaultMaxSessionIdleTimeout; } @Override public void setDefaultMaxSessionIdleTimeout(long timeout) { this.defaultMaxSessionIdleTimeout = timeout; } @Override public int getDefaultMaxBinaryMessageBufferSize() { return maxBinaryMessageBufferSize; } @Override public void setDefaultMaxBinaryMessageBufferSize(int max) { maxBinaryMessageBufferSize = max; } @Override public int getDefaultMaxTextMessageBufferSize() { return maxTextMessageBufferSize; } @Override public void setDefaultMaxTextMessageBufferSize(int max) { maxTextMessageBufferSize = max; } /** * {@inheritDoc} * * Currently, this implementation does not support any extensions. */ @Override public Set<Extension> getInstalledExtensions() { return Collections.emptySet(); } /** * {@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; } /** * Cleans up the resources still in use by WebSocket sessions created from * this container. This includes closing sessions and cancelling * {@link Future}s associated with blocking read/writes. */ public void destroy() { CloseReason cr = new CloseReason( CloseCodes.GOING_AWAY, sm.getString("wsWebSocketContainer.shutdown")); for (WsSession session : sessions.keySet()) { try { session.close(cr); } catch (IOException ioe) { log.debug(sm.getString( "wsWebSocketContainer.sessionCloseFail", session.getId()), ioe); } } } // ----------------------------------------------- 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.checkExpiration(); } } } @Override public void setProcessPeriod(int period) { this.processPeriod = period; } /** * {@inheritDoc} * * The default value is 10 which means session expirations are processed * every 10 seconds. */ @Override public int getProcessPeriod() { return processPeriod; } /** * Create threads for AsyncIO that have the right context class loader to * prevent memory leaks. */ private static class AsyncIOThreadFactory implements ThreadFactory { private AtomicInteger count = new AtomicInteger(0); @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setName("WebSocketClient-AsyncIO-" + count.incrementAndGet()); t.setContextClassLoader(this.getClass().getClassLoader()); t.setDaemon(true); return t; } } }
55,811
Bug 55811 Do not parse web-fragment.xml files when empty absolute-ordering
null
resolved fixed
f4da7dc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-07T20:43:46Z
2013-11-22T19:53:20Z
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.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URISyntaxException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.MultipartConfigElement; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.SessionCookieConfig; import javax.servlet.annotation.HandlesTypes; import 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.util.ContextName; import org.apache.catalina.util.Introspection; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.JarScanType; import org.apache.tomcat.JarScanner; import org.apache.tomcat.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.descriptor.XmlErrorHandler; import org.apache.tomcat.util.descriptor.web.ApplicationListener; import org.apache.tomcat.util.descriptor.web.ContextEjb; import org.apache.tomcat.util.descriptor.web.ContextEnvironment; import org.apache.tomcat.util.descriptor.web.ContextLocalEjb; import org.apache.tomcat.util.descriptor.web.ContextResource; import org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef; import org.apache.tomcat.util.descriptor.web.ContextService; import org.apache.tomcat.util.descriptor.web.ErrorPage; import org.apache.tomcat.util.descriptor.web.FilterDef; import org.apache.tomcat.util.descriptor.web.FilterMap; import org.apache.tomcat.util.descriptor.web.FragmentJarScannerCallback; import org.apache.tomcat.util.descriptor.web.JspPropertyGroup; import org.apache.tomcat.util.descriptor.web.LoginConfig; import org.apache.tomcat.util.descriptor.web.MessageDestinationRef; import org.apache.tomcat.util.descriptor.web.MultipartDef; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.apache.tomcat.util.descriptor.web.SecurityRoleRef; import org.apache.tomcat.util.descriptor.web.ServletDef; import org.apache.tomcat.util.descriptor.web.SessionConfig; import org.apache.tomcat.util.descriptor.web.WebXml; import org.apache.tomcat.util.descriptor.web.WebXmlParser; 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 ); /** * The string resources for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); protected static final LoginConfig DUMMY_LOGIN_CONFIG = new LoginConfig("NONE", null, null, null); /** * The set of Authenticators that we know how to configure. The key is * the name of the implemented authentication method, and the value is * the fully qualified Java class name of the corresponding Valve. */ protected static final Properties authenticators; static { // Load our mapping properties for the standard authenticators InputStream is = ContextConfig.class.getClassLoader().getResourceAsStream( "org/apache/catalina/startup/Authenticators.properties"); Properties props = null; props = new Properties(); if (is != null) { try { props.load(is); } catch (IOException e) { props = null; } } authenticators = props; } /** * Deployment count. */ protected static long deploymentCount = 0L; /** * Cache of default web.xml fragments per Host */ protected static final Map<Host,DefaultWebXmlCacheEntry> hostWebXmlCache = new ConcurrentHashMap<>(); // ----------------------------------------------------- Instance Variables /** * Custom mappings of login methods to authenticators */ protected Map<String,Authenticator> customAuthenticators; /** * The Context we are associated with. */ protected Context context = null; /** * The default web application's deployment descriptor location. */ protected String defaultWebXml = null; /** * Track any fatal errors during startup configuration processing. */ protected boolean ok = false; /** * Original docBase. */ protected String originalDocBase = null; /** * Anti-locking docBase. It is a path to a copy of the web application * in the java.io.tmpdir directory. This path is always an absolute one. */ private File antiLockingDocBase = null; /** * Map of ServletContainerInitializer to classes they expressed interest in. */ protected final Map<ServletContainerInitializer, Set<Class<?>>> initializerClassMap = new LinkedHashMap<>(); /** * Map of Types to ServletContainerInitializer that are interested in those * types. */ protected final Map<Class<?>, Set<ServletContainerInitializer>> typeInitializerMap = new HashMap<>(); /** * Cache of JavaClass objects (byte code) by fully qualified class name. * Only populated if it is necessary to scan the super types and interfaces * as part of the processing for {@link HandlesTypes}. */ protected final Map<String,JavaClassCacheEntry> javaClassCache = new HashMap<>(); /** * Flag that indicates if at least one {@link HandlesTypes} entry is present * that represents an annotation. */ protected boolean handlesTypesAnnotations = false; /** * Flag that indicates if at least one {@link HandlesTypes} entry is present * that represents a non-annotation. */ protected boolean handlesTypesNonAnnotations = false; private WebXmlParser webXmlParser; // ------------------------------------------------------------- Properties /** * Return the location of the default deployment descriptor */ public String getDefaultWebXml() { if( defaultWebXml == null ) { defaultWebXml=Constants.DefaultWebXml; } return (this.defaultWebXml); } /** * Set the location of the default deployment descriptor * * @param path Absolute/relative path to the default web.xml */ public void setDefaultWebXml(String path) { this.defaultWebXml = path; } /** * Sets custom mappings of login methods to authenticators. * * @param customAuthenticators Custom mappings of login methods to * authenticators */ public void setCustomAuthenticators( Map<String,Authenticator> customAuthenticators) { this.customAuthenticators = customAuthenticators; } // --------------------------------------------------------- Public Methods /** * Process events for an associated Context. * * @param event The lifecycle event that has occurred */ @Override public void lifecycleEvent(LifecycleEvent event) { // Identify the context we are associated with try { context = (Context) event.getLifecycle(); } catch (ClassCastException e) { log.error(sm.getString("contextConfig.cce", event.getLifecycle()), e); return; } // Process the event that has occurred if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) { configureStart(); } else if (event.getType().equals(Lifecycle.BEFORE_START_EVENT)) { beforeStart(); } else if (event.getType().equals(Lifecycle.AFTER_START_EVENT)) { // Restore docBase for management tools if (originalDocBase != null) { context.setDocBase(originalDocBase); } } else if (event.getType().equals(Lifecycle.CONFIGURE_STOP_EVENT)) { configureStop(); } else if (event.getType().equals(Lifecycle.AFTER_INIT_EVENT)) { init(); } else if (event.getType().equals(Lifecycle.AFTER_DESTROY_EVENT)) { destroy(); } } // -------------------------------------------------------- protected Methods /** * Process the application classes annotations, if it exists. */ protected void applicationAnnotationsConfig() { long t1=System.currentTimeMillis(); WebAnnotationSet.loadApplicationAnnotations(context); long t2=System.currentTimeMillis(); if (context instanceof StandardContext) { ((StandardContext) context).setStartupTime(t2-t1+ ((StandardContext) context).getStartupTime()); } } /** * Set up an Authenticator automatically if required, and one has not * already been configured. */ protected void authenticatorConfig() { LoginConfig loginConfig = context.getLoginConfig(); SecurityConstraint constraints[] = context.findConstraints(); if (context.getIgnoreAnnotations() && (constraints == null || constraints.length ==0) && !context.getPreemptiveAuthentication()) { return; } else { if (loginConfig == null) { // Not metadata-complete or security constraints present, need // an authenticator to support @ServletSecurity annotations // and/or constraints loginConfig = DUMMY_LOGIN_CONFIG; context.setLoginConfig(loginConfig); } } // Has an authenticator been configured already? if (context.getAuthenticator() != null) { return; } // Has a Realm been configured for us to authenticate against? if (context.getRealm() == null) { log.error(sm.getString("contextConfig.missingRealm")); ok = false; return; } /* * First check to see if there is a custom mapping for the login * method. If so, use it. Otherwise, check if there is a mapping in * org/apache/catalina/startup/Authenticators.properties. */ Valve authenticator = null; if (customAuthenticators != null) { authenticator = (Valve) customAuthenticators.get(loginConfig.getAuthMethod()); } if (authenticator == null) { if (authenticators == null) { log.error(sm.getString("contextConfig.authenticatorResources")); ok = false; return; } // Identify the class name of the Valve we should configure String authenticatorName = null; authenticatorName = authenticators.getProperty(loginConfig.getAuthMethod()); if (authenticatorName == null) { log.error(sm.getString("contextConfig.authenticatorMissing", loginConfig.getAuthMethod())); ok = false; return; } // Instantiate and install an Authenticator of the requested class try { Class<?> authenticatorClass = Class.forName(authenticatorName); authenticator = (Valve) authenticatorClass.newInstance(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString( "contextConfig.authenticatorInstantiate", authenticatorName), t); ok = false; } } if (authenticator != null) { Pipeline pipeline = context.getPipeline(); if (pipeline != null) { pipeline.addValve(authenticator); if (log.isDebugEnabled()) { log.debug(sm.getString( "contextConfig.authenticatorConfigured", loginConfig.getAuthMethod())); } } } } /** * Create (if necessary) and return a Digester configured to process the * context configuration descriptor for an application. */ protected Digester createContextDigester() { Digester digester = new Digester(); digester.setValidating(false); digester.setRulesValidation(true); HashMap<Class<?>, List<String>> fakeAttributes = new HashMap<>(); ArrayList<String> attrs = new ArrayList<>(); attrs.add("className"); fakeAttributes.put(Object.class, attrs); digester.setFakeAttributes(fakeAttributes); RuleSet contextRuleSet = new ContextRuleSet("", false); digester.addRuleSet(contextRuleSet); RuleSet namingRuleSet = new NamingRuleSet("Context/"); digester.addRuleSet(namingRuleSet); return digester; } /** * Process the default configuration file, if it exists. */ protected void contextConfig(Digester digester) { String defaultContextXml = null; // Open the default context.xml file, if it exists if (context instanceof StandardContext) { defaultContextXml = ((StandardContext)context).getDefaultContextXml(); } // set the default if we don't have any overrides if (defaultContextXml == null) { defaultContextXml = Constants.DefaultContextXml; } if (!context.getOverride()) { File defaultContextFile = new File(defaultContextXml); if (!defaultContextFile.isAbsolute()) { defaultContextFile = new File(context.getCatalinaBase(), defaultContextXml); } if (defaultContextFile.exists()) { try { URL defaultContextUrl = defaultContextFile.toURI().toURL(); processContextConfig(digester, defaultContextUrl); } catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", defaultContextFile), e); } } File hostContextFile = new File(getHostConfigBase(), Constants.HostContextXml); if (hostContextFile.exists()) { try { URL hostContextUrl = hostContextFile.toURI().toURL(); processContextConfig(digester, hostContextUrl); } catch (MalformedURLException e) { log.error(sm.getString( "contextConfig.badUrl", hostContextFile), e); } } } if (context.getConfigFile() != null) { processContextConfig(digester, context.getConfigFile()); } } /** * Process a context.xml. */ protected void processContextConfig(Digester digester, URL contextXml) { if (log.isDebugEnabled()) { log.debug("Processing context [" + context.getName() + "] configuration file [" + contextXml + "]"); } InputSource source = null; InputStream stream = null; try { source = new InputSource(contextXml.toString()); URLConnection xmlConn = contextXml.openConnection(); xmlConn.setUseCaches(false); stream = xmlConn.getInputStream(); } catch (Exception e) { log.error(sm.getString("contextConfig.contextMissing", contextXml) , e); } if (source == null) { return; } try { source.setByteStream(stream); digester.setClassLoader(this.getClass().getClassLoader()); digester.setUseContextClassLoader(false); digester.push(context.getParent()); digester.push(context); XmlErrorHandler errorHandler = new XmlErrorHandler(); digester.setErrorHandler(errorHandler); digester.parse(source); if (errorHandler.getWarnings().size() > 0 || errorHandler.getErrors().size() > 0) { errorHandler.logFindings(log, contextXml.toString()); ok = false; } if (log.isDebugEnabled()) { log.debug("Successfully processed context [" + context.getName() + "] configuration file [" + contextXml + "]"); } } catch (SAXParseException e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); log.error(sm.getString("contextConfig.defaultPosition", "" + e.getLineNumber(), "" + e.getColumnNumber())); ok = false; } catch (Exception e) { log.error(sm.getString("contextConfig.contextParse", context.getName()), e); ok = false; } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { log.error(sm.getString("contextConfig.contextClose"), e); } } } /** * Adjust docBase. */ protected void fixDocBase() throws IOException { Host host = (Host) context.getParent(); File appBase = host.getAppBaseFile(); String docBase = context.getDocBase(); if (docBase == null) { // Trying to guess the docBase according to the path String path = context.getPath(); if (path == null) { return; } ContextName cn = new ContextName(path, context.getWebappVersion()); docBase = cn.getBaseName(); } File file = new File(docBase); if (!file.isAbsolute()) { docBase = (new File(appBase, docBase)).getPath(); } else { docBase = file.getCanonicalPath(); } file = new File(docBase); String origDocBase = docBase; ContextName cn = new ContextName(context.getPath(), context.getWebappVersion()); String pathName = cn.getBaseName(); boolean unpackWARs = true; if (host instanceof StandardHost) { unpackWARs = ((StandardHost) host).isUnpackWARs(); if (unpackWARs && context instanceof StandardContext) { unpackWARs = ((StandardContext) context).getUnpackWAR(); } } if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && unpackWARs) { URL war = new URL("jar:" + (new File(docBase)).toURI().toURL() + "!/"); docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } else if (docBase.toLowerCase(Locale.ENGLISH).endsWith(".war") && !file.isDirectory() && !unpackWARs) { URL war = new URL("jar:" + (new File (docBase)).toURI().toURL() + "!/"); ExpandWar.validate(host, war, pathName); } else { File docDir = new File(docBase); if (!docDir.exists()) { File warFile = new File(docBase + ".war"); if (warFile.exists()) { URL war = new URL("jar:" + warFile.toURI().toURL() + "!/"); if (unpackWARs) { docBase = ExpandWar.expand(host, war, pathName); file = new File(docBase); docBase = file.getCanonicalPath(); } else { docBase = warFile.getCanonicalPath(); ExpandWar.validate(host, war, pathName); } } if (context instanceof StandardContext) { ((StandardContext) context).setOriginalDocBase(origDocBase); } } } if (docBase.startsWith(appBase.getPath() + File.separatorChar)) { docBase = docBase.substring(appBase.getPath().length()); docBase = docBase.replace(File.separatorChar, '/'); if (docBase.startsWith("/")) { docBase = docBase.substring(1); } } else { docBase = docBase.replace(File.separatorChar, '/'); } context.setDocBase(docBase); } protected void antiLocking() { if ((context instanceof StandardContext) && ((StandardContext) context).getAntiResourceLocking()) { Host host = (Host) context.getParent(); String docBase = context.getDocBase(); if (docBase == null) { return; } originalDocBase = docBase; File docBaseFile = new File(docBase); if (!docBaseFile.isAbsolute()) { docBaseFile = new File(host.getAppBaseFile(), docBase); } String path = context.getPath(); if (path == null) { return; } ContextName cn = new ContextName(path, context.getWebappVersion()); docBase = cn.getBaseName(); if (originalDocBase.toLowerCase(Locale.ENGLISH).endsWith(".war")) { antiLockingDocBase = new File( System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase + ".war"); } else { antiLockingDocBase = new File( System.getProperty("java.io.tmpdir"), deploymentCount++ + "-" + docBase); } antiLockingDocBase = antiLockingDocBase.getAbsoluteFile(); if (log.isDebugEnabled()) { log.debug("Anti locking context[" + context.getName() + "] setting docBase to " + antiLockingDocBase.getPath()); } // Cleanup just in case an old deployment is lying around ExpandWar.delete(antiLockingDocBase); if (ExpandWar.copy(docBaseFile, antiLockingDocBase)) { context.setDocBase(antiLockingDocBase.getPath()); } } } /** * Process a "init" event for this Context. */ protected void init() { // Called from StandardContext.init() Digester contextDigester = createContextDigester(); contextDigester.getParser(); if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.init")); } context.setConfigured(false); ok = true; contextConfig(contextDigester); webXmlParser = new WebXmlParser(context.getXmlNamespaceAware(), context.getXmlValidation()); } /** * Process a "before start" event for this Context. */ protected synchronized void beforeStart() { try { fixDocBase(); } catch (IOException e) { log.error(sm.getString( "contextConfig.fixDocBase", context.getName()), e); } antiLocking(); } /** * Process a "contextConfig" event for this Context. */ protected synchronized void configureStart() { // Called from StandardContext.start() if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.start")); } if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.xmlSettings", context.getName(), Boolean.valueOf(context.getXmlValidation()), Boolean.valueOf(context.getXmlNamespaceAware()))); } webConfig(); if (!context.getIgnoreAnnotations()) { applicationAnnotationsConfig(); } if (ok) { validateSecurityRoles(); } // Configure an authenticator if we need one if (ok) { authenticatorConfig(); } // Dump the contents of this pipeline if requested if (log.isDebugEnabled()) { log.debug("Pipeline Configuration:"); Pipeline pipeline = context.getPipeline(); Valve valves[] = null; if (pipeline != null) { valves = pipeline.getValves(); } if (valves != null) { for (int i = 0; i < valves.length; i++) { log.debug(" " + valves[i].getClass().getName()); } } log.debug("======================"); } // Make our application available if no problems were encountered if (ok) { context.setConfigured(true); } else { log.error(sm.getString("contextConfig.unavailable")); context.setConfigured(false); } } /** * Process a "stop" event for this Context. */ protected synchronized void configureStop() { if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.stop")); } int i; // Removing children Container[] children = context.findChildren(); for (i = 0; i < children.length; i++) { context.removeChild(children[i]); } // Removing application parameters /* ApplicationParameter[] applicationParameters = context.findApplicationParameters(); for (i = 0; i < applicationParameters.length; i++) { context.removeApplicationParameter (applicationParameters[i].getName()); } */ // Removing security constraints SecurityConstraint[] securityConstraints = context.findConstraints(); for (i = 0; i < securityConstraints.length; i++) { context.removeConstraint(securityConstraints[i]); } // Removing Ejbs /* ContextEjb[] contextEjbs = context.findEjbs(); for (i = 0; i < contextEjbs.length; i++) { context.removeEjb(contextEjbs[i].getName()); } */ // Removing environments /* ContextEnvironment[] contextEnvironments = context.findEnvironments(); for (i = 0; i < contextEnvironments.length; i++) { context.removeEnvironment(contextEnvironments[i].getName()); } */ // Removing errors pages ErrorPage[] errorPages = context.findErrorPages(); for (i = 0; i < errorPages.length; i++) { context.removeErrorPage(errorPages[i]); } // Removing filter defs FilterDef[] filterDefs = context.findFilterDefs(); for (i = 0; i < filterDefs.length; i++) { context.removeFilterDef(filterDefs[i]); } // Removing filter maps FilterMap[] filterMaps = context.findFilterMaps(); for (i = 0; i < filterMaps.length; i++) { context.removeFilterMap(filterMaps[i]); } // Removing local ejbs /* ContextLocalEjb[] contextLocalEjbs = context.findLocalEjbs(); for (i = 0; i < contextLocalEjbs.length; i++) { context.removeLocalEjb(contextLocalEjbs[i].getName()); } */ // Removing Mime mappings String[] mimeMappings = context.findMimeMappings(); for (i = 0; i < mimeMappings.length; i++) { context.removeMimeMapping(mimeMappings[i]); } // Removing parameters String[] parameters = context.findParameters(); for (i = 0; i < parameters.length; i++) { context.removeParameter(parameters[i]); } // Removing resource env refs /* String[] resourceEnvRefs = context.findResourceEnvRefs(); for (i = 0; i < resourceEnvRefs.length; i++) { context.removeResourceEnvRef(resourceEnvRefs[i]); } */ // Removing resource links /* ContextResourceLink[] contextResourceLinks = context.findResourceLinks(); for (i = 0; i < contextResourceLinks.length; i++) { context.removeResourceLink(contextResourceLinks[i].getName()); } */ // Removing resources /* ContextResource[] contextResources = context.findResources(); for (i = 0; i < contextResources.length; i++) { context.removeResource(contextResources[i].getName()); } */ // Removing security role String[] securityRoles = context.findSecurityRoles(); for (i = 0; i < securityRoles.length; i++) { context.removeSecurityRole(securityRoles[i]); } // Removing servlet mappings String[] servletMappings = context.findServletMappings(); for (i = 0; i < servletMappings.length; i++) { context.removeServletMapping(servletMappings[i]); } // FIXME : Removing status pages // Removing welcome files String[] welcomeFiles = context.findWelcomeFiles(); for (i = 0; i < welcomeFiles.length; i++) { context.removeWelcomeFile(welcomeFiles[i]); } // Removing wrapper lifecycles String[] wrapperLifecycles = context.findWrapperLifecycles(); for (i = 0; i < wrapperLifecycles.length; i++) { context.removeWrapperLifecycle(wrapperLifecycles[i]); } // Removing wrapper listeners String[] wrapperListeners = context.findWrapperListeners(); for (i = 0; i < wrapperListeners.length; i++) { context.removeWrapperListener(wrapperListeners[i]); } // Remove (partially) folders and files created by antiLocking if (antiLockingDocBase != null) { // No need to log failure - it is expected in this case ExpandWar.delete(antiLockingDocBase, false); } // Reset ServletContextInitializer scanning initializerClassMap.clear(); typeInitializerMap.clear(); ok = true; } /** * Process a "destroy" event for this Context. */ protected synchronized void destroy() { // Called from StandardContext.destroy() if (log.isDebugEnabled()) { log.debug(sm.getString("contextConfig.destroy")); } // Skip clearing the work directory if Tomcat is being shutdown Server s = getServer(); if (s != null && !s.getState().isAvailable()) { return; } // Changed to getWorkPath per Bugzilla 35819. if (context instanceof StandardContext) { String workDir = ((StandardContext) context).getWorkPath(); if (workDir != null) { ExpandWar.delete(new File(workDir)); } } } private Server getServer() { Container c = context; while (c != null && !(c instanceof Engine)) { c = c.getParent(); } if (c == null) { return null; } Service s = ((Engine)c).getService(); if (s == null) { return null; } return s.getServer(); } /** * Validate the usage of security role names in the web application * deployment descriptor. If any problems are found, issue warning * messages (for backwards compatibility) and add the missing roles. * (To make these problems fatal instead, simply set the <code>ok</code> * instance variable to <code>false</code> as well). */ protected void validateSecurityRoles() { // Check role names used in <security-constraint> elements SecurityConstraint constraints[] = context.findConstraints(); for (int i = 0; i < constraints.length; i++) { String roles[] = constraints[i].findAuthRoles(); for (int j = 0; j < roles.length; j++) { if (!"*".equals(roles[j]) && !context.findSecurityRole(roles[j])) { log.warn(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.warn(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.warn(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(); if (!webXmlParser.parseWebXml(contextWebXml, webXml, false)) { ok = false; } ServletContext sContext = context.getServletContext(); // Ordering is important here // Step 1. Identify all the JARs packaged with the application and those // provided by the container. If any of the application JARs have a // web-fragment.xml it will be parsed at this point. web-fragment.xml // files are ignored for container provided JARs. Map<String,WebXml> fragments = processJarsForWebFragments(); // Step 2. Order the fragments. Set<WebXml> orderedFragments = null; orderedFragments = WebXml.orderWebFragments(webXml, fragments, sContext); // Step 3. Look for ServletContainerInitializer implementations if (ok) { processServletContainerInitializers(sContext); } if (!webXml.isMetadataComplete() || typeInitializerMap.size() > 0) { // Step 4. Process /WEB-INF/classes for annotations and // @HandlesTypes matches 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 for annotations and // @HandlesTypes matches - only need to process those fragments we // are going to use (remember orderedFragments includes any // container fragments) if (ok) { processAnnotations( orderedFragments, webXml.isMetadataComplete()); } // Cache, if used, is no longer required so clear it javaClassCache.clear(); } if (!webXml.isMetadataComplete()) { // Step 6. Merge web-fragment.xml files into the main web.xml // file. if (ok) { ok = webXml.merge(orderedFragments); } // Step 7. Apply global defaults // Have to merge defaults before JSP conversion since defaults // provide JSP servlet definition. webXml.merge(defaults); // Step 8. Convert explicitly mentioned jsps to servlets if (ok) { convertJsps(webXml); } // Step 9. Apply merged web.xml to Context if (ok) { configureContext(webXml); } } else { webXml.merge(defaults); convertJsps(webXml); configureContext(webXml); } // Step 9a. Make the merged web.xml available to other // components, specifically Jasper, to save those components // from having to re-generate it. // TODO Use a ServletContainerInitializer for Jasper String mergedWebXml = webXml.toXml(); sContext.setAttribute( org.apache.tomcat.util.scan.Constants.MERGED_WEB_XML, mergedWebXml); if (context.getLogEffectiveWebXml()) { log.info("web.xml:\n" + mergedWebXml); } // Always need to look for static resources // Step 10. Look for static resources packaged in JARs if (ok) { // Spec does not define an order. // Use ordered JARs followed by remaining JARs Set<WebXml> resourceJars = new LinkedHashSet<>(); if (orderedFragments != null) { for (WebXml fragment : orderedFragments) { resourceJars.add(fragment); } } for (WebXml fragment : fragments.values()) { if (!resourceJars.contains(fragment)) { resourceJars.add(fragment); } } processResourceJARs(resourceJars); // See also StandardContext.resourcesStart() for // WEB-INF/classes/META-INF/resources configuration } // Step 11. Apply the ServletContainerInitializer config to the // context if (ok) { for (Map.Entry<ServletContainerInitializer, Set<Class<?>>> entry : initializerClassMap.entrySet()) { if (entry.getValue().isEmpty()) { context.addServletContainerInitializer( entry.getKey(), null); } else { context.addServletContainerInitializer( entry.getKey(), entry.getValue()); } } } } private void configureContext(WebXml webxml) { // As far as possible, process in alphabetical order so it is easy to // check everything is present // Some validation depends on correct public ID context.setPublicId(webxml.getPublicId()); // Everything else in order context.setEffectiveMajorVersion(webxml.getMajorVersion()); context.setEffectiveMinorVersion(webxml.getMinorVersion()); for (Entry<String, String> entry : webxml.getContextParams().entrySet()) { context.addParameter(entry.getKey(), entry.getValue()); } context.setDenyUncoveredHttpMethods( webxml.getDenyUncoveredHttpMethods()); context.setDisplayName(webxml.getDisplayName()); context.setDistributable(webxml.isDistributable()); for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) { context.getNamingResources().addLocalEjb(ejbLocalRef); } for (ContextEjb ejbRef : webxml.getEjbRefs().values()) { context.getNamingResources().addEjb(ejbRef); } for (ContextEnvironment environment : webxml.getEnvEntries().values()) { context.getNamingResources().addEnvironment(environment); } for (ErrorPage errorPage : webxml.getErrorPages().values()) { context.addErrorPage(errorPage); } for (FilterDef filter : webxml.getFilters().values()) { if (filter.getAsyncSupported() == null) { filter.setAsyncSupported("false"); } context.addFilterDef(filter); } for (FilterMap filterMap : webxml.getFilterMappings()) { context.addFilterMap(filterMap); } context.setJspConfigDescriptor(webxml.getJspConfigDescriptor()); for (String listener : webxml.getListeners()) { context.addApplicationListener( new ApplicationListener(listener, false)); } for (Entry<String, String> entry : webxml.getLocaleEncodingMappings().entrySet()) { context.addLocaleEncodingMappingParameter(entry.getKey(), entry.getValue()); } // Prevents IAE if (webxml.getLoginConfig() != null) { context.setLoginConfig(webxml.getLoginConfig()); } for (MessageDestinationRef mdr : webxml.getMessageDestinationRefs().values()) { context.getNamingResources().addMessageDestinationRef(mdr); } // messageDestinations were ignored in Tomcat 6, so ignore here context.setIgnoreAnnotations(webxml.isMetadataComplete()); for (Entry<String, String> entry : webxml.getMimeMappings().entrySet()) { context.addMimeMapping(entry.getKey(), entry.getValue()); } // Name is just used for ordering for (ContextResourceEnvRef resource : webxml.getResourceEnvRefs().values()) { context.getNamingResources().addResourceEnvRef(resource); } for (ContextResource resource : webxml.getResourceRefs().values()) { context.getNamingResources().addResource(resource); } boolean allAuthenticatedUsersIsAppRole = webxml.getSecurityRoles().contains( SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS); for (SecurityConstraint constraint : webxml.getSecurityConstraints()) { if (allAuthenticatedUsersIsAppRole) { constraint.treatAllAuthenticatedUsersAsApplicationRole(); } context.addConstraint(constraint); } for (String role : webxml.getSecurityRoles()) { context.addSecurityRole(role); } for (ContextService service : webxml.getServiceRefs().values()) { context.getNamingResources().addService(service); } for (ServletDef servlet : webxml.getServlets().values()) { Wrapper wrapper = context.createWrapper(); // Description is ignored // Display name is ignored // Icons are ignored // jsp-file gets passed to the JSP Servlet as an init-param if (servlet.getLoadOnStartup() != null) { wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue()); } if (servlet.getEnabled() != null) { wrapper.setEnabled(servlet.getEnabled().booleanValue()); } wrapper.setName(servlet.getServletName()); Map<String,String> params = servlet.getParameterMap(); for (Entry<String, String> entry : params.entrySet()) { wrapper.addInitParameter(entry.getKey(), entry.getValue()); } wrapper.setRunAs(servlet.getRunAs()); Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs(); for (SecurityRoleRef roleRef : roleRefs) { wrapper.addSecurityReference( roleRef.getName(), roleRef.getLink()); } wrapper.setServletClass(servlet.getServletClass()); MultipartDef multipartdef = servlet.getMultipartDef(); if (multipartdef != null) { if (multipartdef.getMaxFileSize() != null && multipartdef.getMaxRequestSize()!= null && multipartdef.getFileSizeThreshold() != null) { wrapper.setMultipartConfigElement(new MultipartConfigElement( multipartdef.getLocation(), Long.parseLong(multipartdef.getMaxFileSize()), Long.parseLong(multipartdef.getMaxRequestSize()), Integer.parseInt( multipartdef.getFileSizeThreshold()))); } else { wrapper.setMultipartConfigElement(new MultipartConfigElement( multipartdef.getLocation())); } } if (servlet.getAsyncSupported() != null) { wrapper.setAsyncSupported( servlet.getAsyncSupported().booleanValue()); } wrapper.setOverridable(servlet.isOverridable()); context.addChild(wrapper); } for (Entry<String, String> entry : webxml.getServletMappings().entrySet()) { context.addServletMapping(entry.getKey(), entry.getValue()); } SessionConfig sessionConfig = webxml.getSessionConfig(); if (sessionConfig != null) { if (sessionConfig.getSessionTimeout() != null) { context.setSessionTimeout( sessionConfig.getSessionTimeout().intValue()); } SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig(); scc.setName(sessionConfig.getCookieName()); scc.setDomain(sessionConfig.getCookieDomain()); scc.setPath(sessionConfig.getCookiePath()); scc.setComment(sessionConfig.getCookieComment()); if (sessionConfig.getCookieHttpOnly() != null) { scc.setHttpOnly(sessionConfig.getCookieHttpOnly().booleanValue()); } if (sessionConfig.getCookieSecure() != null) { scc.setSecure(sessionConfig.getCookieSecure().booleanValue()); } if (sessionConfig.getCookieMaxAge() != null) { scc.setMaxAge(sessionConfig.getCookieMaxAge().intValue()); } if (sessionConfig.getSessionTrackingModes().size() > 0) { context.getServletContext().setSessionTrackingModes( sessionConfig.getSessionTrackingModes()); } } // Context doesn't use version directly for (String welcomeFile : webxml.getWelcomeFiles()) { /* * The following will result in a welcome file of "" so don't add * that to the context * <welcome-file-list> * <welcome-file/> * </welcome-file-list> */ if (welcomeFile != null && welcomeFile.length() > 0) { context.addWelcomeFile(welcomeFile); } } // Do this last as it depends on servlets for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) { String jspServletName = context.findServletMapping("*.jsp"); if (jspServletName == null) { jspServletName = "jsp"; } if (context.findChild(jspServletName) != null) { for (String urlPattern : jspPropertyGroup.getUrlPatterns()) { context.addServletMapping(urlPattern, jspServletName, true); } } else { if(log.isDebugEnabled()) { for (String urlPattern : jspPropertyGroup.getUrlPatterns()) { log.debug("Skiping " + urlPattern + " , no servlet " + jspServletName); } } } } for (Entry<String, String> entry : webxml.getPostConstructMethods().entrySet()) { context.addPostConstructMethod(entry.getKey(), entry.getValue()); } for (Entry<String, String> entry : webxml.getPreDestroyMethods().entrySet()) { context.addPreDestroyMethod(entry.getKey(), entry.getValue()); } } private WebXml getDefaultWebXmlFragment() { // Host should never be null Host host = (Host) context.getParent(); DefaultWebXmlCacheEntry entry = hostWebXmlCache.get(host); InputSource globalWebXml = getGlobalWebXmlSource(); InputSource hostWebXml = getHostWebXmlSource(); long globalTimeStamp = 0; long hostTimeStamp = 0; if (globalWebXml != null) { try { URL url = new URL(globalWebXml.getSystemId()); globalTimeStamp = url.openConnection().getLastModified(); } catch (MalformedURLException e) { globalTimeStamp = -1; } catch (IOException e) { globalTimeStamp = -1; } } if (hostWebXml != null) { try { URL url = new URL(hostWebXml.getSystemId()); hostTimeStamp = url.openConnection().getLastModified(); } catch (MalformedURLException e) { hostTimeStamp = -1; } catch (IOException e) { hostTimeStamp = -1; } } if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp && entry.getHostTimeStamp() == hostTimeStamp) { return entry.getWebXml(); } // Parsing global web.xml is relatively expensive. Use a sync block to // make sure it only happens once. Use the pipeline since a lock will // already be held on the host by another thread synchronized (host.getPipeline()) { entry = hostWebXmlCache.get(host); if (entry != null && entry.getGlobalTimeStamp() == globalTimeStamp && entry.getHostTimeStamp() == hostTimeStamp) { return entry.getWebXml(); } WebXml webXmlDefaultFragment = createWebXml(); webXmlDefaultFragment.setOverridable(true); // Set to distributable else every app will be prevented from being // distributable when the default fragment is merged with the main // web.xml webXmlDefaultFragment.setDistributable(true); // When merging, the default welcome files are only used if the app has // not defined any welcomes files. webXmlDefaultFragment.setAlwaysAddWelcomeFiles(false); // Parse global web.xml if present if (globalWebXml == null) { // This is unusual enough to log log.info(sm.getString("contextConfig.defaultMissing")); } else { if (!webXmlParser.parseWebXml( globalWebXml, webXmlDefaultFragment, false)) { ok = false; } } // Parse host level web.xml if present // Additive apart from welcome pages webXmlDefaultFragment.setReplaceWelcomeFiles(true); if (!webXmlParser.parseWebXml( hostWebXml, webXmlDefaultFragment, false)) { ok = 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. */ protected void processServletContainerInitializers(ServletContext servletContext) { List<ServletContainerInitializer> detectedScis; try { WebappServiceLoader<ServletContainerInitializer> loader = new WebappServiceLoader<>(servletContext); detectedScis = loader.load(ServletContainerInitializer.class); } catch (IOException e) { log.error(sm.getString( "contextConfig.servletContainerInitializerFail", context.getName()), e); ok = false; return; } for (ServletContainerInitializer sci : detectedScis) { initializerClassMap.put(sci, new HashSet<Class<?>>()); HandlesTypes ht; try { ht = sci.getClass().getAnnotation(HandlesTypes.class); } catch (Exception e) { if (log.isDebugEnabled()) { log.info(sm.getString("contextConfig.sci.debug", sci.getClass().getName()), e); } else { log.info(sm.getString("contextConfig.sci.info", sci.getClass().getName())); } continue; } if (ht == null) { continue; } Class<?>[] types = ht.value(); if (types == null) { continue; } 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); } } } /** * 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 { 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(), null, "/"); } } } 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; } /** * 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(); boolean delegate = false; if (context instanceof StandardContext) { delegate = ((StandardContext) context).getDelegate(); } FragmentJarScannerCallback callback = new FragmentJarScannerCallback(webXmlParser, delegate); jarScanner.scan(JarScanType.PLUGGABILITY, context.getServletContext(), callback); if (!callback.isOk()) { ok = false; } return callback.getFragments(); } protected void processAnnotations(Set<WebXml> fragments, boolean handlesTypesOnly) { for(WebXml fragment : fragments) { // Only need to scan for @HandlesTypes matches if any of the // following are true: // - it has already been determined only @HandlesTypes is required // (e.g. main web.xml has metadata-complete="true" // - this fragment is for a container JAR (Servlet 3.1 section 8.1) // - this fragment has metadata-complete="true" boolean htOnly = handlesTypesOnly || !fragment.getWebappJar() || fragment.isMetadataComplete(); WebXml annotations = new WebXml(); // no impact on distributable annotations.setDistributable(true); URL url = fragment.getURL(); processAnnotationsUrl(url, annotations, htOnly); 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); } finally { try { is.close(); } catch (IOException e) { // ignore } } } } 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 static class DefaultWebXmlCacheEntry { private final WebXml webXml; private final long globalTimeStamp; private final long hostTimeStamp; public DefaultWebXmlCacheEntry(WebXml webXml, long globalTimeStamp, long hostTimeStamp) { this.webXml = webXml; this.globalTimeStamp = globalTimeStamp; this.hostTimeStamp = hostTimeStamp; } public WebXml getWebXml() { return webXml; } public long getGlobalTimeStamp() { return globalTimeStamp; } public long getHostTimeStamp() { return hostTimeStamp; } } private static class JavaClassCacheEntry { public final String superclassName; public final String[] interfaceNames; private Set<ServletContainerInitializer> sciSet = null; public JavaClassCacheEntry(JavaClass javaClass) { superclassName = javaClass.getSuperclassName(); interfaceNames = javaClass.getInterfaceNames(); } public String getSuperclassName() { return superclassName; } public String[] getInterfaceNames() { return interfaceNames; } public Set<ServletContainerInitializer> getSciSet() { return sciSet; } public void setSciSet(Set<ServletContainerInitializer> sciSet) { this.sciSet = sciSet; } } }
55,811
Bug 55811 Do not parse web-fragment.xml files when empty absolute-ordering
null
resolved fixed
f4da7dc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-07T20:43:46Z
2013-11-22T19:53:20Z
java/org/apache/jasper/servlet/JspCServletContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.servlet; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; 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.Map; import java.util.Set; import java.util.Vector; import javax.servlet.Filter; import javax.servlet.FilterRegistration; import javax.servlet.FilterRegistration.Dynamic; import javax.servlet.RequestDispatcher; import javax.servlet.Servlet; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRegistration; import javax.servlet.SessionCookieConfig; import javax.servlet.SessionTrackingMode; import javax.servlet.descriptor.JspConfigDescriptor; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.util.ExceptionUtils; import org.apache.tomcat.JarScanType; import org.apache.tomcat.util.descriptor.web.Constants; import org.apache.tomcat.util.descriptor.web.FragmentJarScannerCallback; import org.apache.tomcat.util.descriptor.web.WebXml; import org.apache.tomcat.util.descriptor.web.WebXmlParser; import org.apache.tomcat.util.scan.StandardJarScanFilter; import org.apache.tomcat.util.scan.StandardJarScanner; /** * Simple <code>ServletContext</code> implementation without * HTTP-specific methods. * * @author Peter Rossbach (pr@webapp.de) */ public class JspCServletContext implements ServletContext { // ----------------------------------------------------- Instance Variables /** * Servlet context attributes. */ private final Map<String,Object> myAttributes; /** * The log writer we will write log messages to. */ private final PrintWriter myLogWriter; /** * The base URL (document root) for this context. */ private final URL myResourceBaseURL; /** * Merged web.xml for the application. */ private final WebXml webXml; private final JspConfigDescriptor jspConfigDescriptor; /** * Web application class loader. */ private final ClassLoader loader; // ----------------------------------------------------------- Constructors /** * Create a new instance of this ServletContext implementation. * * @param aLogWriter PrintWriter which is used for <code>log()</code> calls * @param aResourceBaseURL Resource base URL * @throws JasperException */ public JspCServletContext(PrintWriter aLogWriter, URL aResourceBaseURL, ClassLoader classLoader) throws JasperException { myAttributes = new HashMap<>(); myLogWriter = aLogWriter; myResourceBaseURL = aResourceBaseURL; this.loader = classLoader; this.webXml = buildMergedWebXml(); jspConfigDescriptor = webXml.getJspConfigDescriptor(); } private WebXml buildMergedWebXml() throws JasperException { WebXml webXml = new WebXml(); WebXmlParser webXmlParser = new WebXmlParser(false, false); // Use this class's classloader as Ant will have set the TCCL to its own webXmlParser.setClassLoader(getClass().getClassLoader()); try { URL url = getResource(Constants.WEB_XML_LOCATION); if (!webXmlParser.parseWebXml(url, webXml, false)) { throw new JasperException(Localizer.getMessage("jspc.error.invalidWebXml")); } } catch (IOException e) { throw new JasperException(e); } // if the application is metadata-complete then we can skip fragment processing if (webXml.isMetadataComplete()) { return webXml; } Map<String, WebXml> fragments = scanForFragments(webXmlParser); Set<WebXml> orderedFragments = WebXml.orderWebFragments(webXml, fragments, this); // JspC is not affected by annotations so skip that processing, proceed to merge webXml.merge(orderedFragments); return webXml; } private Map<String, WebXml> scanForFragments(WebXmlParser webXmlParser) throws JasperException { StandardJarScanner scanner = new StandardJarScanner(); // TODO - enabling this means initializing the classloader first in JspC scanner.setScanClassPath(false); // TODO - configure filter rules from Ant rather then system properties scanner.setJarScanFilter(new StandardJarScanFilter()); FragmentJarScannerCallback callback = new FragmentJarScannerCallback(webXmlParser, false); scanner.scan(JarScanType.PLUGGABILITY, this, callback); if (!callback.isOk()) { throw new JasperException(Localizer.getMessage("jspc.error.invalidFragment")); } return callback.getFragments(); } // --------------------------------------------------------- Public Methods /** * Return the specified context attribute, if any. * * @param name Name of the requested attribute */ @Override public Object getAttribute(String name) { return myAttributes.get(name); } /** * Return an enumeration of context attribute names. */ @Override public Enumeration<String> getAttributeNames() { return Collections.enumeration(myAttributes.keySet()); } /** * Return the servlet context for the specified path. * * @param uripath Server-relative path starting with '/' */ @Override public ServletContext getContext(String uripath) { return null; } /** * Return the context path. */ @Override public String getContextPath() { return null; } /** * Return the specified context initialization parameter. * * @param name Name of the requested parameter */ @Override public String getInitParameter(String name) { return null; } /** * Return an enumeration of the names of context initialization * parameters. */ @Override public Enumeration<String> getInitParameterNames() { return new Vector<String>().elements(); } /** * Return the Servlet API major version number. */ @Override public int getMajorVersion() { return 3; } /** * Return the MIME type for the specified filename. * * @param file Filename whose MIME type is requested */ @Override public String getMimeType(String file) { return null; } /** * Return the Servlet API minor version number. */ @Override public int getMinorVersion() { return 1; } /** * Return a request dispatcher for the specified servlet name. * * @param name Name of the requested servlet */ @Override public RequestDispatcher getNamedDispatcher(String name) { return null; } /** * Return the real path for the specified context-relative * virtual path. * * @param path The context-relative virtual path to resolve */ @Override public String getRealPath(String path) { if (!myResourceBaseURL.getProtocol().equals("file")) return (null); if (!path.startsWith("/")) return (null); try { return (getResource(path).getFile().replace('/', File.separatorChar)); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); } } /** * Return a request dispatcher for the specified context-relative path. * * @param path Context-relative path for which to acquire a dispatcher */ @Override public RequestDispatcher getRequestDispatcher(String path) { return null; } /** * Return a URL object of a resource that is mapped to the * specified context-relative path. * * @param path Context-relative path of the desired resource * * @exception MalformedURLException if the resource path is * not properly formed */ @Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); URL url = new URL(myResourceBaseURL, path.substring(1)); InputStream is = null; try { is = url.openStream(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); url = null; } finally { if (is != null) { try { is.close(); } catch (Throwable t2) { ExceptionUtils.handleThrowable(t2); } } } return url; } /** * Return an InputStream allowing access to the resource at the * specified context-relative path. * * @param path Context-relative path of the desired resource */ @Override public InputStream getResourceAsStream(String path) { try { return (getResource(path).openStream()); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); return (null); } } /** * Return the set of resource paths for the "directory" at the * specified context path. * * @param path Context-relative base path */ @Override public Set<String> getResourcePaths(String path) { Set<String> thePaths = new HashSet<>(); if (!path.endsWith("/")) path += "/"; String basePath = getRealPath(path); if (basePath == null) return (thePaths); File theBaseDir = new File(basePath); if (!theBaseDir.exists() || !theBaseDir.isDirectory()) return (thePaths); String theFiles[] = theBaseDir.list(); for (int i = 0; i < theFiles.length; i++) { File testFile = new File(basePath + File.separator + theFiles[i]); if (testFile.isFile()) thePaths.add(path + theFiles[i]); else if (testFile.isDirectory()) thePaths.add(path + theFiles[i] + "/"); } return (thePaths); } /** * Return descriptive information about this server. */ @Override public String getServerInfo() { return ("JspC/ApacheTomcat8"); } /** * Return a null reference for the specified servlet name. * * @param name Name of the requested servlet * * @deprecated This method has been deprecated with no replacement */ @Override @Deprecated public Servlet getServlet(String name) throws ServletException { return null; } /** * Return the name of this servlet context. */ @Override public String getServletContextName() { return (getServerInfo()); } /** * Return an empty enumeration of servlet names. * * @deprecated This method has been deprecated with no replacement */ @Override @Deprecated public Enumeration<String> getServletNames() { return (new Vector<String>().elements()); } /** * Return an empty enumeration of servlets. * * @deprecated This method has been deprecated with no replacement */ @Override @Deprecated public Enumeration<Servlet> getServlets() { return (new Vector<Servlet>().elements()); } /** * Log the specified message. * * @param message The message to be logged */ @Override public void log(String message) { myLogWriter.println(message); } /** * Log the specified message and exception. * * @param exception The exception to be logged * @param message The message to be logged * * @deprecated Use log(String,Throwable) instead */ @Override @Deprecated public void log(Exception exception, String message) { log(message, exception); } /** * Log the specified message and exception. * * @param message The message to be logged * @param exception The exception to be logged */ @Override public void log(String message, Throwable exception) { myLogWriter.println(message); exception.printStackTrace(myLogWriter); } /** * Remove the specified context attribute. * * @param name Name of the attribute to remove */ @Override public void removeAttribute(String name) { myAttributes.remove(name); } /** * Set or replace the specified context attribute. * * @param name Name of the context attribute to set * @param value Corresponding attribute value */ @Override public void setAttribute(String name, Object value) { myAttributes.put(name, value); } @Override public FilterRegistration.Dynamic addFilter(String filterName, String className) { return null; } @Override public ServletRegistration.Dynamic addServlet(String servletName, String className) { return null; } @Override public Set<SessionTrackingMode> getDefaultSessionTrackingModes() { return EnumSet.noneOf(SessionTrackingMode.class); } @Override public Set<SessionTrackingMode> getEffectiveSessionTrackingModes() { return EnumSet.noneOf(SessionTrackingMode.class); } @Override public SessionCookieConfig getSessionCookieConfig() { return null; } @Override public void setSessionTrackingModes( Set<SessionTrackingMode> sessionTrackingModes) { // Do nothing } @Override public Dynamic addFilter(String filterName, Filter filter) { return null; } @Override public Dynamic addFilter(String filterName, Class<? extends Filter> filterClass) { return null; } @Override public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) { return null; } @Override public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass) { return null; } @Override public <T extends Filter> T createFilter(Class<T> c) throws ServletException { return null; } @Override public <T extends Servlet> T createServlet(Class<T> c) throws ServletException { return null; } @Override public FilterRegistration getFilterRegistration(String filterName) { return null; } @Override public ServletRegistration getServletRegistration(String servletName) { return null; } @Override public boolean setInitParameter(String name, String value) { return false; } @Override public void addListener(Class<? extends EventListener> listenerClass) { // NOOP } @Override public void addListener(String className) { // NOOP } @Override public <T extends EventListener> void addListener(T t) { // NOOP } @Override public <T extends EventListener> T createListener(Class<T> c) throws ServletException { return null; } @Override public void declareRoles(String... roleNames) { // NOOP } @Override public ClassLoader getClassLoader() { return loader; } @Override public int getEffectiveMajorVersion() { return webXml.getMajorVersion(); } @Override public int getEffectiveMinorVersion() { return webXml.getMinorVersion(); } @Override public Map<String, ? extends FilterRegistration> getFilterRegistrations() { return null; } @Override public JspConfigDescriptor getJspConfigDescriptor() { return jspConfigDescriptor; } @Override public Map<String, ? extends ServletRegistration> getServletRegistrations() { return null; } @Override public String getVirtualServerName() { return null; } }
55,811
Bug 55811 Do not parse web-fragment.xml files when empty absolute-ordering
null
resolved fixed
f4da7dc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-07T20:43:46Z
2013-11-22T19:53:20Z
java/org/apache/tomcat/util/descriptor/web/FragmentJarScannerCallback.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.descriptor.web; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.JarURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; import org.apache.tomcat.JarScannerCallback; import org.apache.tomcat.util.scan.Jar; import org.apache.tomcat.util.scan.JarFactory; import org.xml.sax.InputSource; /** * Callback handling a web-fragment.xml descriptor. */ public class FragmentJarScannerCallback implements JarScannerCallback { private static final String FRAGMENT_LOCATION = "META-INF/web-fragment.xml"; private final WebXmlParser webXmlParser; private final boolean delegate; private final Map<String,WebXml> fragments = new HashMap<>(); private boolean ok = true; public FragmentJarScannerCallback(WebXmlParser webXmlParser, boolean delegate) { this.webXmlParser = webXmlParser; this.delegate = delegate; } @Override public void scan(JarURLConnection jarConn, String webappPath, boolean isWebapp) throws IOException { URL url = jarConn.getURL(); URL resourceURL = jarConn.getJarFileURL(); Jar jar = null; InputStream is = null; WebXml fragment = new WebXml(); fragment.setWebappJar(isWebapp); fragment.setDelegate(delegate); try { // Only web application JARs are checked for web-fragment.xml // files if (isWebapp) { jar = JarFactory.newInstance(url); is = jar.getInputStream(FRAGMENT_LOCATION); } if (is == null) { // If there is no web.xml, normal JAR no impact on // distributable fragment.setDistributable(true); } else { InputSource source = new InputSource( "jar:" + resourceURL.toString() + "!/" + FRAGMENT_LOCATION); source.setByteStream(is); if (!webXmlParser.parseWebXml(source, fragment, true)) { ok = false; } } } 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, String webappPath, boolean isWebapp) throws IOException { InputStream stream = null; WebXml fragment = new WebXml(); fragment.setWebappJar(isWebapp); fragment.setDelegate(delegate); 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); if (!webXmlParser.parseWebXml(source, fragment, true)) { ok = false; } } else { // If there is no web.xml, normal folder no impact on // distributable fragment.setDistributable(true); } } finally { fragment.setURL(file.toURI().toURL()); if (fragment.getName() == null) { fragment.setName(fragment.getURL().toString()); } fragment.setJarName(file.getName()); fragments.put(fragment.getName(), fragment); } } @Override public void scanWebInfClasses() { // NO-OP. Fragments unpacked in WEB-INF classes are not handled, // mainly because if there are multiple fragments there is no way to // handle multiple web-fragment.xml files. } public boolean isOk() { return ok; } public Map<String,WebXml> getFragments() { return fragments; } }
55,820
Bug 55820 Add 172.16/12 range to default internal proxies
null
resolved fixed
c1be72f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-09T09:48:42Z
2013-11-27T22:06:40Z
java/org/apache/catalina/filters/RemoteIpFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.filters; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Pattern; 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.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import org.apache.catalina.AccessLog; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * <p> * Servlet filter to integrate "X-Forwarded-For" and "X-Forwarded-Proto" HTTP headers. * </p> * <p> * Most of the design of this Servlet Filter is a port of <a * href="http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this servlet filter replaces the apparent client remote * IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request headers (e.g. * "X-Forwarded-For"). * </p> * <p> * Another feature of this servlet filter is to replace the apparent scheme (http/https) and server port with the scheme presented by a * proxy or a load balancer via a request header (e.g. "X-Forwarded-Proto"). * </p> * <p> * This servlet filter proceeds as follows: * </p> * <p> * If the incoming <code>request.getRemoteAddr()</code> matches the servlet filter's list of internal proxies : * <ul> * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http * header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li> * <li>For each ip/host of the list: * <ul> * <li>if it matches the internal proxies list, the ip/host is swallowed</li> * <li>if it matches the trusted proxies list, the ip/host is added to the created proxies header</li> * <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li> * </ul> * </li> * <li>If the request http header named <code>$protocolHeader</code> (e.g. <code>x-forwarded-for</code>) equals to the value of * <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>, * <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the * <code>$httpsServerPort</code> configuration parameter.</li> * </ul> * </p> * <p> * <strong>Configuration parameters:</strong> * <table border="1"> * <tr> * <th>XForwardedFilter property</th> * <th>Description</th> * <th>Equivalent mod_remoteip directive</th> * <th>Format</th> * <th>Default Value</th> * </tr> * <tr> * <td>remoteIpHeader</td> * <td>Name of the Http Header read by this servlet filter that holds the list of traversed IP addresses starting from the requesting client * </td> * <td>RemoteIPHeader</td> * <td>Compliant http header name</td> * <td>x-forwarded-for</td> * </tr> * <tr> * <td>internalProxies</td> * <td>Regular expression that matches the IP addresses of internal proxies. * If they appear in the <code>remoteIpHeader</code> value, they will be * trusted and will not appear * in the <code>proxiesHeader</code> value</td> * <td>RemoteIPInternalProxy</td> * <td>Regular expression (in the syntax supported by * {@link java.util.regex.Pattern java.util.regex})</td> * <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3} <br/> * By default, 10/8, 192.168/16, 169.254/16 and 127/8 are allowed ; 172.16/12 has not been enabled by default because it is complex to * describe with regular expressions</td> * </tr> * </tr> * <tr> * <td>proxiesHeader</td> * <td>Name of the http header created by this servlet filter to hold the list of proxies that have been processed in the incoming * <code>remoteIpHeader</code></td> * <td>RemoteIPProxiesHeader</td> * <td>Compliant http header name</td> * <td>x-forwarded-by</td> * </tr> * <tr> * <td>trustedProxies</td> * <td>Regular expression that matches the IP addresses of trusted proxies. * If they appear in the <code>remoteIpHeader</code> value, they will be * trusted and will appear in the <code>proxiesHeader</code> value</td> * <td>RemoteIPTrustedProxy</td> * <td>Regular expression (in the syntax supported by * {@link java.util.regex.Pattern java.util.regex})</td> * <td>&nbsp;</td> * </tr> * <tr> * <td>protocolHeader</td> * <td>Name of the http header read by this servlet filter that holds the flag that this request</td> * <td>N/A</td> * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td> * <td><code>null</code></td> * </tr> * <tr> * <td>protocolHeaderHttpsValue</td> * <td>Value of the <code>protocolHeader</code> to indicate that it is an Https request</td> * <td>N/A</td> * <td>String like <code>https</code> or <code>ON</code></td> * <td><code>https</code></td> * </tr> * <tr> * <td>httpServerPort</td> * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td> * <td>N/A</td> * <td>integer</td> * <td>80</td> * </tr> * <tr> * <td>httpsServerPort</td> * <td>Value returned by {@link ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td> * <td>N/A</td> * <td>integer</td> * <td>443</td> * </tr> * </table> * </p> * <p> * <p> * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g. * <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as the JVM doesn't have a * library similar to <a * href="http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>, we rely on * regular expressions. * </p> * <hr/> * <p> * <strong>Sample with internal proxies</strong> * </p> * <p> * XForwardedFilter configuration: * </p> * <code><pre> * &lt;filter&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;filter-class&gt;org.apache.catalina.filters.RemoteIpFilter&lt;/filter-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;internalProxies&lt;/param-name&gt; * &lt;param-value&gt;192\.168\.0\.10|192\.168\.0\.11&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-for&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpProxiesHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-by&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;protocolHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-proto&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/filter&gt; * * &lt;filter-mapping&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; * &lt;/filter-mapping&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpFilter</th> * <th>Value After RemoteIpFilter</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, 192.168.0.10</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-proto']</td> * <td>https</td> * <td>https</td> * </tr> * <tr> * <td>request.scheme</td> * <td>http</td> * <td>https</td> * </tr> * <tr> * <td>request.secure</td> * <td>false</td> * <td>true</td> * </tr> * <tr> * <td>request.serverPort</td> * <td>80</td> * <td>443</td> * </tr> * </table> * Note : <code>x-forwarded-by</code> header is null because only internal proxies as been traversed by the request. * <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with trusted proxies</strong> * </p> * <p> * RemoteIpFilter configuration: * </p> * <code><pre> * &lt;filter&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;filter-class&gt;org.apache.catalina.filters.RemoteIpFilter&lt;/filter-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;internalProxies&lt;/param-name&gt; * &lt;param-value&gt;192\.168\.0\.10|192\.168\.0\.11&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-for&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpProxiesHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-by&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;trustedProxies&lt;/param-name&gt; * &lt;param-value&gt;proxy1|proxy2&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/filter&gt; * * &lt;filter-mapping&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; * &lt;/filter-mapping&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpFilter</th> * <th>Value After RemoteIpFilter</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, proxy1, proxy2</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1, proxy2</td> * </tr> * </table> * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both * are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with internal and trusted proxies</strong> * </p> * <p> * RemoteIpFilter configuration: * </p> * <code><pre> * &lt;filter&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;filter-class&gt;org.apache.catalina.filters.RemoteIpFilter&lt;/filter-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;internalProxies&lt;/param-name&gt; * &lt;param-value&gt;192\.168\.0\.10|192\.168\.0\.11&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-for&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpProxiesHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-by&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;trustedProxies&lt;/param-name&gt; * &lt;param-value&gt;proxy1|proxy2&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/filter&gt; * * &lt;filter-mapping&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; * &lt;/filter-mapping&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpFilter</th> * <th>Value After RemoteIpFilter</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, proxy1, proxy2, 192.168.0.10</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1, proxy2</td> * </tr> * </table> * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both * are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in * <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with an untrusted proxy</strong> * </p> * <p> * RemoteIpFilter configuration: * </p> * <code><pre> * &lt;filter&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;filter-class&gt;org.apache.catalina.filters.RemoteIpFilter&lt;/filter-class&gt; * &lt;init-param&gt; * &lt;param-name&gt;internalProxies&lt;/param-name&gt; * &lt;param-value&gt;192\.168\.0\.10|192\.168\.0\.11&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-for&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;remoteIpProxiesHeader&lt;/param-name&gt; * &lt;param-value&gt;x-forwarded-by&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;init-param&gt; * &lt;param-name&gt;trustedProxies&lt;/param-name&gt; * &lt;param-value&gt;proxy1|proxy2&lt;/param-value&gt; * &lt;/init-param&gt; * &lt;/filter&gt; * * &lt;filter-mapping&gt; * &lt;filter-name&gt;RemoteIpFilter&lt;/filter-name&gt; * &lt;url-pattern&gt;/*&lt;/url-pattern&gt; * &lt;dispatcher&gt;REQUEST&lt;/dispatcher&gt; * &lt;/filter-mapping&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpFilter</th> * <th>Value After RemoteIpFilter</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>untrusted-proxy</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, untrusted-proxy, proxy1</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1</td> * </tr> * </table> * Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds * <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we can not trust that * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP * verified by <code>proxy1</code>. * </p> * <hr/> */ public class RemoteIpFilter implements Filter { public static class XForwardedRequest extends HttpServletRequestWrapper { static final ThreadLocal<SimpleDateFormat[]> threadLocalDateFormats = new ThreadLocal<SimpleDateFormat[]>() { @Override protected SimpleDateFormat[] initialValue() { return new SimpleDateFormat[] { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", 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) }; } }; protected final Map<String, List<String>> headers; protected int localPort; protected String remoteAddr; protected String remoteHost; protected String scheme; protected boolean secure; protected int serverPort; public XForwardedRequest(HttpServletRequest request) { super(request); this.localPort = request.getLocalPort(); this.remoteAddr = request.getRemoteAddr(); this.remoteHost = request.getRemoteHost(); this.scheme = request.getScheme(); this.secure = request.isSecure(); this.serverPort = request.getServerPort(); headers = new HashMap<>(); for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements();) { String header = headerNames.nextElement(); headers.put(header, Collections.list(request.getHeaders(header))); } } @Override public long getDateHeader(String name) { String value = getHeader(name); if (value == null) { return -1; } DateFormat[] dateFormats = threadLocalDateFormats.get(); Date date = null; for (int i = 0; ((i < dateFormats.length) && (date == null)); i++) { DateFormat dateFormat = dateFormats[i]; try { date = dateFormat.parse(value); } catch (Exception ParseException) { // Ignore } } if (date == null) { throw new IllegalArgumentException(value); } return date.getTime(); } @Override public String getHeader(String name) { Map.Entry<String, List<String>> header = getHeaderEntry(name); if (header == null || header.getValue() == null || header.getValue().isEmpty()) { return null; } return header.getValue().get(0); } protected Map.Entry<String, List<String>> getHeaderEntry(String name) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) { if (entry.getKey().equalsIgnoreCase(name)) { return entry; } } return null; } @Override public Enumeration<String> getHeaderNames() { return Collections.enumeration(headers.keySet()); } @Override public Enumeration<String> getHeaders(String name) { Map.Entry<String, List<String>> header = getHeaderEntry(name); if (header == null || header.getValue() == null) { return Collections.enumeration(Collections.<String>emptyList()); } return Collections.enumeration(header.getValue()); } @Override public int getIntHeader(String name) { String value = getHeader(name); if (value == null) { return -1; } return Integer.parseInt(value); } @Override public int getLocalPort() { return localPort; } @Override public String getRemoteAddr() { return this.remoteAddr; } @Override public String getRemoteHost() { return this.remoteHost; } @Override public String getScheme() { return scheme; } @Override public int getServerPort() { return serverPort; } @Override public boolean isSecure() { return secure; } public void removeHeader(String name) { Map.Entry<String, List<String>> header = getHeaderEntry(name); if (header != null) { headers.remove(header.getKey()); } } public void setHeader(String name, String value) { List<String> values = Arrays.asList(value); Map.Entry<String, List<String>> header = getHeaderEntry(name); if (header == null) { headers.put(name, values); } else { header.setValue(values); } } public void setLocalPort(int localPort) { this.localPort = localPort; } public void setRemoteAddr(String remoteAddr) { this.remoteAddr = remoteAddr; } public void setRemoteHost(String remoteHost) { this.remoteHost = remoteHost; } public void setScheme(String scheme) { this.scheme = scheme; } public void setSecure(boolean secure) { this.secure = secure; } public void setServerPort(int serverPort) { this.serverPort = serverPort; } } /** * {@link Pattern} for a comma delimited string that support whitespace characters */ private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*"); protected static final String HTTP_SERVER_PORT_PARAMETER = "httpServerPort"; protected static final String HTTPS_SERVER_PORT_PARAMETER = "httpsServerPort"; protected static final String INTERNAL_PROXIES_PARAMETER = "internalProxies"; /** * Logger */ private static final Log log = LogFactory.getLog(RemoteIpFilter.class); protected static final String PROTOCOL_HEADER_PARAMETER = "protocolHeader"; protected static final String PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER = "protocolHeaderHttpsValue"; protected static final String PORT_HEADER_PARAMETER = "portHeader"; protected static final String CHANGE_LOCAL_PORT_PARAMETER = "changeLocalPort"; protected static final String PROXIES_HEADER_PARAMETER = "proxiesHeader"; protected static final String REMOTE_IP_HEADER_PARAMETER = "remoteIpHeader"; protected static final String TRUSTED_PROXIES_PARAMETER = "trustedProxies"; /** * Convert a given comma delimited list of regular expressions into an array of String * * @return array of patterns (non <code>null</code>) */ protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) { return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern .split(commaDelimitedStrings); } /** * Convert an array of strings in a comma delimited string */ protected static String listToCommaDelimitedString(List<String> stringList) { if (stringList == null) { return ""; } StringBuilder result = new StringBuilder(); for (Iterator<String> it = stringList.iterator(); it.hasNext();) { Object element = it.next(); if (element != null) { result.append(element); if (it.hasNext()) { result.append(", "); } } } return result.toString(); } /** * @see #setHttpServerPort(int) */ private int httpServerPort = 80; /** * @see #setHttpsServerPort(int) */ private int httpsServerPort = 443; /** * @see #setInternalProxies(String) */ private Pattern internalProxies = Pattern.compile( "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" + "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); /** * @see #setProtocolHeader(String) */ private String protocolHeader = null; private String protocolHeaderHttpsValue = "https"; private String portHeader = null; private boolean changeLocalPort = false; /** * @see #setProxiesHeader(String) */ private String proxiesHeader = "X-Forwarded-By"; /** * @see #setRemoteIpHeader(String) */ private String remoteIpHeader = "X-Forwarded-For"; /** * @see #setRequestAttributesEnabled(boolean) */ private boolean requestAttributesEnabled = true; /** * @see #setTrustedProxies(String) */ private Pattern trustedProxies = null; @Override public void destroy() { // NOOP } public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { if (internalProxies != null && internalProxies.matcher(request.getRemoteAddr()).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } XForwardedRequest xRequest = new XForwardedRequest(request); if (remoteIp != null) { xRequest.setRemoteAddr(remoteIp); xRequest.setRemoteHost(remoteIp); if (proxiesHeaderValue.size() == 0) { xRequest.removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); xRequest.setHeader(proxiesHeader, commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { xRequest.removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); xRequest.setHeader(remoteIpHeader, commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { xRequest.setSecure(true); xRequest.setScheme("https"); setPorts(xRequest, httpsServerPort); } else { xRequest.setSecure(false); xRequest.setScheme("http"); setPorts(xRequest, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "', originalRemoteHost='" + request.getRemoteHost() + "', originalSecure='" + request.isSecure() + "', originalScheme='" + request.getScheme() + "', original[" + remoteIpHeader + "]='" + concatRemoteIpHeaderValue + "', original[" + protocolHeader + "]='" + (protocolHeader == null ? null : request.getHeader(protocolHeader)) + "' will be seen as newRemoteAddr='" + xRequest.getRemoteAddr() + "', newRemoteHost='" + xRequest.getRemoteHost() + "', newScheme='" + xRequest.getScheme() + "', newSecure='" + xRequest.isSecure() + "', new[" + remoteIpHeader + "]='" + xRequest.getHeader(remoteIpHeader) + "', new[" + proxiesHeader + "]='" + xRequest.getHeader(proxiesHeader) + "'"); } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, xRequest.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, xRequest.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, xRequest.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(xRequest.getServerPort())); } chain.doFilter(xRequest, response); } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpFilter for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } chain.doFilter(request, response); } } private void setPorts(XForwardedRequest xrequest, int defaultPort) { int port = defaultPort; if (getPortHeader() != null) { String portHeaderValue = xrequest.getHeader(getPortHeader()); if (portHeaderValue != null) { try { port = Integer.parseInt(portHeaderValue); } catch (NumberFormatException nfe) { log.debug("Invalid port value [" + portHeaderValue + "] provided in header [" + getPortHeader() + "]"); } } } xrequest.setServerPort(port); if (isChangeLocalPort()) { xrequest.setLocalPort(port); } } /** * Wrap the incoming <code>request</code> in a {@link XForwardedRequest} if the http header <code>x-forwareded-for</code> is not empty. */ @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) { doFilter((HttpServletRequest)request, (HttpServletResponse)response, chain); } else { chain.doFilter(request, response); } } public boolean isChangeLocalPort() { return changeLocalPort; } public int getHttpsServerPort() { return httpsServerPort; } public Pattern getInternalProxies() { return internalProxies; } public String getProtocolHeader() { return protocolHeader; } public String getPortHeader() { return portHeader; } public String getProtocolHeaderHttpsValue() { return protocolHeaderHttpsValue; } public String getProxiesHeader() { return proxiesHeader; } public String getRemoteIpHeader() { return remoteIpHeader; } /** * @see #setRequestAttributesEnabled(boolean) * @return <code>true</code> if the attributes will be logged, otherwise * <code>false</code> */ public boolean getRequestAttributesEnabled() { return requestAttributesEnabled; } public Pattern getTrustedProxies() { return trustedProxies; } @Override public void init(FilterConfig filterConfig) throws ServletException { if (filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER) != null) { setInternalProxies(filterConfig.getInitParameter(INTERNAL_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER) != null) { setProtocolHeader(filterConfig.getInitParameter(PROTOCOL_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER) != null) { setProtocolHeaderHttpsValue(filterConfig.getInitParameter(PROTOCOL_HEADER_HTTPS_VALUE_PARAMETER)); } if (filterConfig.getInitParameter(PORT_HEADER_PARAMETER) != null) { setPortHeader(filterConfig.getInitParameter(PORT_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER) != null) { setChangeLocalPort(Boolean.parseBoolean(filterConfig.getInitParameter(CHANGE_LOCAL_PORT_PARAMETER))); } if (filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER) != null) { setProxiesHeader(filterConfig.getInitParameter(PROXIES_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER) != null) { setRemoteIpHeader(filterConfig.getInitParameter(REMOTE_IP_HEADER_PARAMETER)); } if (filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER) != null) { setTrustedProxies(filterConfig.getInitParameter(TRUSTED_PROXIES_PARAMETER)); } if (filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER) != null) { try { setHttpServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTP_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTP_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } if (filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER) != null) { try { setHttpsServerPort(Integer.parseInt(filterConfig.getInitParameter(HTTPS_SERVER_PORT_PARAMETER))); } catch (NumberFormatException e) { throw new NumberFormatException("Illegal " + HTTPS_SERVER_PORT_PARAMETER + " : " + e.getMessage()); } } } /** * <p> * If <code>true</code>, the return values for both {@link * ServletRequest#getLocalPort()} and {@link ServletRequest#getServerPort()} * wil be modified by this Filter rather than just * {@link ServletRequest#getServerPort()}. * </p> * <p> * Default value : <code>false</code> * </p> */ public void setChangeLocalPort(boolean changeLocalPort) { this.changeLocalPort = changeLocalPort; } /** * <p> * Server Port value if the {@link #protocolHeader} indicates HTTP (i.e. {@link #protocolHeader} is not null and * has a value different of {@link #protocolHeaderHttpsValue}). * </p> * <p> * Default value : 80 * </p> */ public void setHttpServerPort(int httpServerPort) { this.httpServerPort = httpServerPort; } /** * <p> * Server Port value if the {@link #protocolHeader} indicates HTTPS * </p> * <p> * Default value : 443 * </p> */ public void setHttpsServerPort(int httpsServerPort) { this.httpsServerPort = httpsServerPort; } /** * <p> * Regular expression that defines the internal proxies. * </p> * <p> * Default value : 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254.\d{1,3}.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3} * </p> */ public void setInternalProxies(String internalProxies) { if (internalProxies == null || internalProxies.length() == 0) { this.internalProxies = null; } else { this.internalProxies = Pattern.compile(internalProxies); } } /** * <p> * Header that holds the incoming port, usally named * <code>X-Forwarded-Port</code>. If <code>null</code>, * {@link #httpServerPort} or {@link #httpsServerPort} will be used. * </p> * <p> * Default value : <code>null</code> * </p> */ public void setPortHeader(String portHeader) { this.portHeader = portHeader; } /** * <p> * Header that holds the incoming protocol, usally named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and * request.secure will not be modified. * </p> * <p> * Default value : <code>null</code> * </p> */ public void setProtocolHeader(String protocolHeader) { this.protocolHeader = protocolHeader; } /** * <p> * Case insensitive value of the protocol header to indicate that the incoming http request uses HTTPS. * </p> * <p> * Default value : <code>https</code> * </p> */ public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) { this.protocolHeaderHttpsValue = protocolHeaderHttpsValue; } /** * <p> * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP * addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header, * while any intermediate RemoteIPInternalProxy addresses are discarded. * </p> * <p> * Name of the http header that holds the list of trusted proxies that has been traversed by the http request. * </p> * <p> * The value of this header can be comma delimited. * </p> * <p> * Default value : <code>X-Forwarded-By</code> * </p> */ public void setProxiesHeader(String proxiesHeader) { this.proxiesHeader = proxiesHeader; } /** * <p> * Name of the http header from which the remote ip is extracted. * </p> * <p> * The value of this header can be comma delimited. * </p> * <p> * Default value : <code>X-Forwarded-For</code> * </p> */ public void setRemoteIpHeader(String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } /** * Should this filter set request attributes for IP address, Hostname, * protocol and port used for the request? This are typically used in * conjunction with an {@link AccessLog} which will otherwise log the * original values. Default is <code>true</code>. * * The attributes set are: * <ul> * <li>org.apache.catalina.AccessLog.RemoteAddr</li> * <li>org.apache.catalina.AccessLog.RemoteHost</li> * <li>org.apache.catalina.AccessLog.Protocol</li> * <li>org.apache.catalina.AccessLog.ServerPort</li> * </ul> * * @param requestAttributesEnabled <code>true</code> causes the attributes * to be set, <code>false</code> disables * the setting of the attributes. */ public void setRequestAttributesEnabled(boolean requestAttributesEnabled) { this.requestAttributesEnabled = requestAttributesEnabled; } /** * <p> * Regular expression defining proxies that are trusted when they appear in * the {@link #remoteIpHeader} header. * </p> * <p> * Default value : empty list, no external proxy is trusted. * </p> */ public void setTrustedProxies(String trustedProxies) { if (trustedProxies == null || trustedProxies.length() == 0) { this.trustedProxies = null; } else { this.trustedProxies = Pattern.compile(trustedProxies); } } }
55,820
Bug 55820 Add 172.16/12 range to default internal proxies
null
resolved fixed
c1be72f
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-09T09:48:42Z
2013-11-27T22:06:40Z
java/org/apache/catalina/valves/RemoteIpValve.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.valves; import java.io.IOException; import java.util.Enumeration; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.regex.Pattern; import javax.servlet.ServletException; import org.apache.catalina.AccessLog; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * <p> * Tomcat port of <a href="http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html">mod_remoteip</a>, this valve replaces the apparent * client remote IP address and hostname for the request with the IP address list presented by a proxy or a load balancer via a request * headers (e.g. "X-Forwarded-For"). * </p> * <p> * Another feature of this valve is to replace the apparent scheme (http/https) and server port with the scheme presented by a proxy or a * load balancer via a request header (e.g. "X-Forwarded-Proto"). * </p> * <p> * This valve proceeds as follows: * </p> * <p> * If the incoming <code>request.getRemoteAddr()</code> matches the valve's list of internal proxies : * <ul> * <li>Loop on the comma delimited list of IPs and hostnames passed by the preceding load balancer or proxy in the given request's Http * header named <code>$remoteIpHeader</code> (default value <code>x-forwarded-for</code>). Values are processed in right-to-left order.</li> * <li>For each ip/host of the list: * <ul> * <li>if it matches the internal proxies list, the ip/host is swallowed</li> * <li>if it matches the trusted proxies list, the ip/host is added to the created proxies header</li> * <li>otherwise, the ip/host is declared to be the remote ip and looping is stopped.</li> * </ul> * </li> * <li>If the request http header named <code>$protocolHeader</code> (e.g. <code>x-forwarded-for</code>) equals to the value of * <code>protocolHeaderHttpsValue</code> configuration parameter (default <code>https</code>) then <code>request.isSecure = true</code>, * <code>request.scheme = https</code> and <code>request.serverPort = 443</code>. Note that 443 can be overwritten with the * <code>$httpsServerPort</code> configuration parameter.</li> * </ul> * </p> * <p> * <strong>Configuration parameters:</strong> * <table border="1"> * <tr> * <th>RemoteIpValve property</th> * <th>Description</th> * <th>Equivalent mod_remoteip directive</th> * <th>Format</th> * <th>Default Value</th> * </tr> * <tr> * <td>remoteIpHeader</td> * <td>Name of the Http Header read by this valve that holds the list of traversed IP addresses starting from the requesting client</td> * <td>RemoteIPHeader</td> * <td>Compliant http header name</td> * <td>x-forwarded-for</td> * </tr> * <tr> * <td>internalProxies</td> * <td>Regular expression that matches the IP addresses of internal proxies. * If they appear in the <code>remoteIpHeader</code> value, they will be * trusted and will not appear * in the <code>proxiesHeader</code> value</td> * <td>RemoteIPInternalProxy</td> * <td>Regular expression (in the syntax supported by * {@link java.util.regex.Pattern java.util.regex})</td> * <td>10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254\.\d{1,3}\.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3}<br/> * By default, 10/8, 192.168/16, 169.254/16 and 127/8 are allowed ; 172.16/12 has not been enabled by default because it is complex to * describe with regular expressions</td> * </tr> * </tr> * <tr> * <td>proxiesHeader</td> * <td>Name of the http header created by this valve to hold the list of proxies that have been processed in the incoming * <code>remoteIpHeader</code></td> * <td>proxiesHeader</td> * <td>Compliant http header name</td> * <td>x-forwarded-by</td> * </tr> * <tr> * <td>trustedProxies</td> * <td>Regular expression that matches the IP addresses of trusted proxies. * If they appear in the <code>remoteIpHeader</code> value, they will be * trusted and will appear in the <code>proxiesHeader</code> value</td> * <td>RemoteIPTrustedProxy</td> * <td>Regular expression (in the syntax supported by * {@link java.util.regex.Pattern java.util.regex})</td> * <td>&nbsp;</td> * </tr> * <tr> * <td>protocolHeader</td> * <td>Name of the http header read by this valve that holds the flag that this request </td> * <td>N/A</td> * <td>Compliant http header name like <code>X-Forwarded-Proto</code>, <code>X-Forwarded-Ssl</code> or <code>Front-End-Https</code></td> * <td><code>null</code></td> * </tr> * <tr> * <td>protocolHeaderHttpsValue</td> * <td>Value of the <code>protocolHeader</code> to indicate that it is an Https request</td> * <td>N/A</td> * <td>String like <code>https</code> or <code>ON</code></td> * <td><code>https</code></td> * </tr> * <tr> * <td>httpServerPort</td> * <td>Value returned by {@link javax.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>http</code> protocol</td> * <td>N/A</td> * <td>integer</td> * <td>80</td> * </tr> * <tr> * <td>httpsServerPort</td> * <td>Value returned by {@link javax.servlet.ServletRequest#getServerPort()} when the <code>protocolHeader</code> indicates <code>https</code> protocol</td> * <td>N/A</td> * <td>integer</td> * <td>443</td> * </tr> * </table> * </p> * <p> * <p> * This Valve may be attached to any Container, depending on the granularity of the filtering you wish to perform. * </p> * <p> * <strong>Regular expression vs. IP address blocks:</strong> <code>mod_remoteip</code> allows to use address blocks (e.g. * <code>192.168/16</code>) to configure <code>RemoteIPInternalProxy</code> and <code>RemoteIPTrustedProxy</code> ; as Tomcat doesn't have a * library similar to <a * href="http://apr.apache.org/docs/apr/1.3/group__apr__network__io.html#gb74d21b8898b7c40bf7fd07ad3eb993d">apr_ipsubnet_test</a>, * <code>RemoteIpValve</code> uses regular expression to configure <code>internalProxies</code> and <code>trustedProxies</code> in the same * fashion as {@link RequestFilterValve} does. * </p> * <hr/> * <p> * <strong>Sample with internal proxies</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * proxiesHeader="x-forwarded-by" * protocolHeader="x-forwarded-proto" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, 192.168.0.10</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-proto']</td> * <td>https</td> * <td>https</td> * </tr> * <tr> * <td>request.scheme</td> * <td>http</td> * <td>https</td> * </tr> * <tr> * <td>request.secure</td> * <td>false</td> * <td>true</td> * </tr> * <tr> * <td>request.serverPort</td> * <td>80</td> * <td>443</td> * </tr> * </table> * Note : <code>x-forwarded-by</code> header is null because only internal proxies as been traversed by the request. * <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with trusted proxies</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * proxiesHeader="x-forwarded-by" * trustedProxies="proxy1|proxy2" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, proxy1, proxy2</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1, proxy2</td> * </tr> * </table> * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both * are migrated in <code>x-forwarded-by</code> header. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with internal and trusted proxies</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * proxiesHeader="x-forwarded-by" * trustedProxies="proxy1|proxy2" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, proxy1, proxy2, 192.168.0.10</td> * <td>null</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1, proxy2</td> * </tr> * </table> * Note : <code>proxy1</code> and <code>proxy2</code> are both trusted proxies that come in <code>x-forwarded-for</code> header, they both * are migrated in <code>x-forwarded-by</code> header. As <code>192.168.0.10</code> is an internal proxy, it does not appear in * <code>x-forwarded-by</code>. <code>x-forwarded-by</code> is null because all the proxies are trusted or internal. * </p> * <hr/> * <p> * <strong>Sample with an untrusted proxy</strong> * </p> * <p> * RemoteIpValve configuration: * </p> * <code><pre> * &lt;Valve * className="org.apache.catalina.valves.RemoteIpValve" * internalProxies="192\.168\.0\.10|192\.168\.0\.11" * remoteIpHeader="x-forwarded-for" * proxiesHeader="x-forwarded-by" * trustedProxies="proxy1|proxy2" * /&gt;</pre></code> * <p> * Request values: * <table border="1"> * <tr> * <th>property</th> * <th>Value Before RemoteIpValve</th> * <th>Value After RemoteIpValve</th> * </tr> * <tr> * <td>request.remoteAddr</td> * <td>192.168.0.10</td> * <td>untrusted-proxy</td> * </tr> * <tr> * <td>request.header['x-forwarded-for']</td> * <td>140.211.11.130, untrusted-proxy, proxy1</td> * <td>140.211.11.130</td> * </tr> * <tr> * <td>request.header['x-forwarded-by']</td> * <td>null</td> * <td>proxy1</td> * </tr> * </table> * Note : <code>x-forwarded-by</code> holds the trusted proxy <code>proxy1</code>. <code>x-forwarded-by</code> holds * <code>140.211.11.130</code> because <code>untrusted-proxy</code> is not trusted and thus, we can not trust that * <code>untrusted-proxy</code> is the actual remote ip. <code>request.remoteAddr</code> is <code>untrusted-proxy</code> that is an IP * verified by <code>proxy1</code>. * </p> */ public class RemoteIpValve extends ValveBase { /** * {@link Pattern} for a comma delimited string that support whitespace characters */ private static final Pattern commaSeparatedValuesPattern = Pattern.compile("\\s*,\\s*"); /** * Logger */ private static final Log log = LogFactory.getLog(RemoteIpValve.class); /** * Convert a given comma delimited String into an array of String * * @return array of String (non <code>null</code>) */ protected static String[] commaDelimitedListToStringArray(String commaDelimitedStrings) { return (commaDelimitedStrings == null || commaDelimitedStrings.length() == 0) ? new String[0] : commaSeparatedValuesPattern .split(commaDelimitedStrings); } /** * Convert an array of strings in a comma delimited string */ protected static String listToCommaDelimitedString(List<String> stringList) { if (stringList == null) { return ""; } StringBuilder result = new StringBuilder(); for (Iterator<String> it = stringList.iterator(); it.hasNext();) { Object element = it.next(); if (element != null) { result.append(element); if (it.hasNext()) { result.append(", "); } } } return result.toString(); } /** * @see #setHttpServerPort(int) */ private int httpServerPort = 80; /** * @see #setHttpsServerPort(int) */ private int httpsServerPort = 443; private boolean changeLocalPort = false; /** * @see #setInternalProxies(String) */ private Pattern internalProxies = Pattern.compile( "10\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}|" + "192\\.168\\.\\d{1,3}\\.\\d{1,3}|" + "169\\.254\\.\\d{1,3}\\.\\d{1,3}|" + "127\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}"); /** * @see #setProtocolHeader(String) */ private String protocolHeader = null; /** * @see #setProtocolHeaderHttpsValue(String) */ private String protocolHeaderHttpsValue = "https"; private String portHeader = null; /** * @see #setProxiesHeader(String) */ private String proxiesHeader = "X-Forwarded-By"; /** * @see #setRemoteIpHeader(String) */ private String remoteIpHeader = "X-Forwarded-For"; /** * @see #setRequestAttributesEnabled(boolean) */ private boolean requestAttributesEnabled = true; /** * @see RemoteIpValve#setTrustedProxies(String) */ private Pattern trustedProxies = null; /** * Default constructor that ensures {@link ValveBase#ValveBase(boolean)} is * called with <code>true</code>. */ public RemoteIpValve() { // Async requests are supported with this valve super(true); } public int getHttpsServerPort() { return httpsServerPort; } public int getHttpServerPort() { return httpServerPort; } public boolean isChangeLocalPort() { return changeLocalPort; } public void setChangeLocalPort(boolean changeLocalPort) { this.changeLocalPort = changeLocalPort; } /** * Obtain the name of the HTTP header used to override the value returned * by {@link Request#getServerPort()} and (optionally depending on {link * {@link #isChangeLocalPort()} {@link Request#getLocalPort()}. * * @return The HTTP header name */ public String getPortHeader() { return portHeader; } /** * Set the name of the HTTP header used to override the value returned * by {@link Request#getServerPort()} and (optionally depending on {link * {@link #isChangeLocalPort()} {@link Request#getLocalPort()}. * * @param portHeader The HTTP header name */ public void setPortHeader(String portHeader) { this.portHeader = portHeader; } /** * @see #setInternalProxies(String) * @return Regular expression that defines the internal proxies */ public String getInternalProxies() { if (internalProxies == null) { return null; } return internalProxies.toString(); } /** * @see #setProtocolHeader(String) * @return the protocol header (e.g. "X-Forwarded-Proto") */ public String getProtocolHeader() { return protocolHeader; } /** * @see RemoteIpValve#setProtocolHeaderHttpsValue(String) * @return the value of the protocol header for incoming https request (e.g. "https") */ public String getProtocolHeaderHttpsValue() { return protocolHeaderHttpsValue; } /** * @see #setProxiesHeader(String) * @return the proxies header name (e.g. "X-Forwarded-By") */ public String getProxiesHeader() { return proxiesHeader; } /** * @see #setRemoteIpHeader(String) * @return the remote IP header name (e.g. "X-Forwarded-For") */ public String getRemoteIpHeader() { return remoteIpHeader; } /** * @see #setRequestAttributesEnabled(boolean) * @return <code>true</code> if the attributes will be logged, otherwise * <code>false</code> */ public boolean getRequestAttributesEnabled() { return requestAttributesEnabled; } /** * @see #setTrustedProxies(String) * @return Regular expression that defines the trusted proxies */ public String getTrustedProxies() { if (trustedProxies == null) { return null; } return trustedProxies.toString(); } /** * {@inheritDoc} */ @Override public void invoke(Request request, Response response) throws IOException, ServletException { final String originalRemoteAddr = request.getRemoteAddr(); final String originalRemoteHost = request.getRemoteHost(); final String originalScheme = request.getScheme(); final boolean originalSecure = request.isSecure(); final int originalServerPort = request.getServerPort(); if (internalProxies !=null && internalProxies.matcher(originalRemoteAddr).matches()) { String remoteIp = null; // In java 6, proxiesHeaderValue should be declared as a java.util.Deque LinkedList<String> proxiesHeaderValue = new LinkedList<>(); StringBuilder concatRemoteIpHeaderValue = new StringBuilder(); for (Enumeration<String> e = request.getHeaders(remoteIpHeader); e.hasMoreElements();) { if (concatRemoteIpHeaderValue.length() > 0) { concatRemoteIpHeaderValue.append(", "); } concatRemoteIpHeaderValue.append(e.nextElement()); } String[] remoteIpHeaderValue = commaDelimitedListToStringArray(concatRemoteIpHeaderValue.toString()); int idx; // loop on remoteIpHeaderValue to find the first trusted remote ip and to build the proxies chain for (idx = remoteIpHeaderValue.length - 1; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; remoteIp = currentRemoteIp; if (internalProxies.matcher(currentRemoteIp).matches()) { // do nothing, internalProxies IPs are not appended to the } else if (trustedProxies != null && trustedProxies.matcher(currentRemoteIp).matches()) { proxiesHeaderValue.addFirst(currentRemoteIp); } else { idx--; // decrement idx because break statement doesn't do it break; } } // continue to loop on remoteIpHeaderValue to build the new value of the remoteIpHeader LinkedList<String> newRemoteIpHeaderValue = new LinkedList<>(); for (; idx >= 0; idx--) { String currentRemoteIp = remoteIpHeaderValue[idx]; newRemoteIpHeaderValue.addFirst(currentRemoteIp); } if (remoteIp != null) { request.setRemoteAddr(remoteIp); request.setRemoteHost(remoteIp); // use request.coyoteRequest.mimeHeaders.setValue(str).setString(str) because request.addHeader(str, str) is no-op in Tomcat // 6.0 if (proxiesHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(proxiesHeader); } else { String commaDelimitedListOfProxies = listToCommaDelimitedString(proxiesHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(proxiesHeader).setString(commaDelimitedListOfProxies); } if (newRemoteIpHeaderValue.size() == 0) { request.getCoyoteRequest().getMimeHeaders().removeHeader(remoteIpHeader); } else { String commaDelimitedRemoteIpHeaderValue = listToCommaDelimitedString(newRemoteIpHeaderValue); request.getCoyoteRequest().getMimeHeaders().setValue(remoteIpHeader).setString(commaDelimitedRemoteIpHeaderValue); } } if (protocolHeader != null) { String protocolHeaderValue = request.getHeader(protocolHeader); if (protocolHeaderValue == null) { // don't modify the secure,scheme and serverPort attributes // of the request } else if (protocolHeaderHttpsValue.equalsIgnoreCase(protocolHeaderValue)) { request.setSecure(true); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("https"); setPorts(request, httpsServerPort); } else { request.setSecure(false); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString("http"); setPorts(request, httpServerPort); } } if (log.isDebugEnabled()) { log.debug("Incoming request " + request.getRequestURI() + " with originalRemoteAddr '" + originalRemoteAddr + "', originalRemoteHost='" + originalRemoteHost + "', originalSecure='" + originalSecure + "', originalScheme='" + originalScheme + "' will be seen as newRemoteAddr='" + request.getRemoteAddr() + "', newRemoteHost='" + request.getRemoteHost() + "', newScheme='" + request.getScheme() + "', newSecure='" + request.isSecure() + "'"); } } else { if (log.isDebugEnabled()) { log.debug("Skip RemoteIpValve for request " + request.getRequestURI() + " with originalRemoteAddr '" + request.getRemoteAddr() + "'"); } } if (requestAttributesEnabled) { request.setAttribute(AccessLog.REMOTE_ADDR_ATTRIBUTE, request.getRemoteAddr()); request.setAttribute(AccessLog.REMOTE_HOST_ATTRIBUTE, request.getRemoteHost()); request.setAttribute(AccessLog.PROTOCOL_ATTRIBUTE, request.getProtocol()); request.setAttribute(AccessLog.SERVER_PORT_ATTRIBUTE, Integer.valueOf(request.getServerPort())); } try { getNext().invoke(request, response); } finally { request.setRemoteAddr(originalRemoteAddr); request.setRemoteHost(originalRemoteHost); request.setSecure(originalSecure); // use request.coyoteRequest.scheme instead of request.setScheme() because request.setScheme() is no-op in Tomcat 6.0 request.getCoyoteRequest().scheme().setString(originalScheme); request.setServerPort(originalServerPort); } } private void setPorts(Request request, int defaultPort) { int port = defaultPort; if (portHeader != null) { String portHeaderValue = request.getHeader(portHeader); if (portHeaderValue != null) { try { port = Integer.parseInt(portHeaderValue); } catch (NumberFormatException nfe) { if (log.isDebugEnabled()) { log.debug(sm.getString( "remoteIpValve.invalidPortHeader", portHeaderValue, portHeader), nfe); } } } } request.setServerPort(port); if (changeLocalPort) { request.setLocalPort(port); } } /** * <p> * Server Port value if the {@link #protocolHeader} is not <code>null</code> and does not indicate HTTP * </p> * <p> * Default value : 80 * </p> */ public void setHttpServerPort(int httpServerPort) { this.httpServerPort = httpServerPort; } /** * <p> * Server Port value if the {@link #protocolHeader} indicates HTTPS * </p> * <p> * Default value : 443 * </p> */ public void setHttpsServerPort(int httpsServerPort) { this.httpsServerPort = httpsServerPort; } /** * <p> * Regular expression that defines the internal proxies. * </p> * <p> * Default value : 10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|169\.254.\d{1,3}.\d{1,3}|127\.\d{1,3}\.\d{1,3}\.\d{1,3} * </p> */ public void setInternalProxies(String internalProxies) { if (internalProxies == null || internalProxies.length() == 0) { this.internalProxies = null; } else { this.internalProxies = Pattern.compile(internalProxies); } } /** * <p> * Header that holds the incoming protocol, usally named <code>X-Forwarded-Proto</code>. If <code>null</code>, request.scheme and * request.secure will not be modified. * </p> * <p> * Default value : <code>null</code> * </p> */ public void setProtocolHeader(String protocolHeader) { this.protocolHeader = protocolHeader; } /** * <p> * Case insensitive value of the protocol header to indicate that the incoming http request uses SSL. * </p> * <p> * Default value : <code>https</code> * </p> */ public void setProtocolHeaderHttpsValue(String protocolHeaderHttpsValue) { this.protocolHeaderHttpsValue = protocolHeaderHttpsValue; } /** * <p> * The proxiesHeader directive specifies a header into which mod_remoteip will collect a list of all of the intermediate client IP * addresses trusted to resolve the actual remote IP. Note that intermediate RemoteIPTrustedProxy addresses are recorded in this header, * while any intermediate RemoteIPInternalProxy addresses are discarded. * </p> * <p> * Name of the http header that holds the list of trusted proxies that has been traversed by the http request. * </p> * <p> * The value of this header can be comma delimited. * </p> * <p> * Default value : <code>X-Forwarded-By</code> * </p> */ public void setProxiesHeader(String proxiesHeader) { this.proxiesHeader = proxiesHeader; } /** * <p> * Name of the http header from which the remote ip is extracted. * </p> * <p> * The value of this header can be comma delimited. * </p> * <p> * Default value : <code>X-Forwarded-For</code> * </p> * * @param remoteIpHeader */ public void setRemoteIpHeader(String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } /** * Should this valve set request attributes for IP address, Hostname, * protocol and port used for the request? This are typically used in * conjunction with the {@link AccessLog} which will otherwise log the * original values. Default is <code>true</code>. * * The attributes set are: * <ul> * <li>org.apache.catalina.AccessLog.RemoteAddr</li> * <li>org.apache.catalina.AccessLog.RemoteHost</li> * <li>org.apache.catalina.AccessLog.Protocol</li> * <li>org.apache.catalina.AccessLog.ServerPort</li> * </ul> * * @param requestAttributesEnabled <code>true</code> causes the attributes * to be set, <code>false</code> disables * the setting of the attributes. */ public void setRequestAttributesEnabled(boolean requestAttributesEnabled) { this.requestAttributesEnabled = requestAttributesEnabled; } /** * <p> * Regular expression defining proxies that are trusted when they appear in * the {@link #remoteIpHeader} header. * </p> * <p> * Default value : empty list, no external proxy is trusted. * </p> */ public void setTrustedProxies(String trustedProxies) { if (trustedProxies == null || trustedProxies.length() == 0) { this.trustedProxies = null; } else { this.trustedProxies = Pattern.compile(trustedProxies); } } }
55,884
Bug 55884 JSPs no longer compile in Java 8
null
verified fixed
8a5179c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-16T15:48:04Z
2013-12-14T22:26:40Z
java/org/apache/jasper/compiler/JspRuntimeContext.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.FileNotFoundException; import java.io.FilePermission; import java.net.URL; import java.net.URLClassLoader; import java.security.CodeSource; import java.security.PermissionCollection; import java.security.Policy; import java.security.cert.Certificate; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.ServletContext; import org.apache.jasper.Constants; import org.apache.jasper.JspCompilationContext; import org.apache.jasper.Options; import org.apache.jasper.servlet.JspServletWrapper; import org.apache.jasper.util.ExceptionUtils; import org.apache.jasper.util.FastRemovalDequeue; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; /** * Class for tracking JSP compile time file dependencies when the * &060;%@include file="..."%&062; directive is used. * * A background thread periodically checks the files a JSP page * is dependent upon. If a dependent file changes the JSP page * which included it is recompiled. * * Only used if a web application context is a directory. * * @author Glenn L. Nielsen * @version $Revision$ */ public final class JspRuntimeContext { // Logger private final Log log = LogFactory.getLog(JspRuntimeContext.class); /* * Counts how many times the webapp's JSPs have been reloaded. */ private final AtomicInteger jspReloadCount = new AtomicInteger(0); /* * Counts how many times JSPs have been unloaded in this webapp. */ private final AtomicInteger jspUnloadCount = new AtomicInteger(0); // ----------------------------------------------------------- Constructors /** * Create a JspRuntimeContext for a web application context. * * Loads in any previously generated dependencies from file. * * @param context ServletContext for web application */ public JspRuntimeContext(ServletContext context, Options options) { this.context = context; this.options = options; // Get the parent class loader ClassLoader loader = Thread.currentThread().getContextClassLoader(); if (loader == null) { loader = this.getClass().getClassLoader(); } if (log.isDebugEnabled()) { if (loader != null) { log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", loader.toString())); } else { log.debug(Localizer.getMessage("jsp.message.parent_class_loader_is", "<none>")); } } parentClassLoader = loader; classpath = initClassPath(); if (context instanceof org.apache.jasper.servlet.JspCServletContext) { codeSource = null; permissionCollection = null; return; } if (Constants.IS_SECURITY_ENABLED) { SecurityHolder holder = initSecurity(); codeSource = holder.cs; permissionCollection = holder.pc; } else { codeSource = null; permissionCollection = null; } // If this web application context is running from a // directory, start the background compilation thread String appBase = context.getRealPath("/"); if (!options.getDevelopment() && appBase != null && options.getCheckInterval() > 0) { lastCompileCheck = System.currentTimeMillis(); } if (options.getMaxLoadedJsps() > 0) { jspQueue = new FastRemovalDequeue<>(options.getMaxLoadedJsps()); if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.message.jsp_queue_created", "" + options.getMaxLoadedJsps(), context.getContextPath())); } } /* Init parameter is in seconds, locally we use milliseconds */ jspIdleTimeout = options.getJspIdleTimeout() * 1000; } // ----------------------------------------------------- Instance Variables /** * This web applications ServletContext */ private final ServletContext context; private final Options options; private final ClassLoader parentClassLoader; private final PermissionCollection permissionCollection; private final CodeSource codeSource; private final String classpath; private volatile long lastCompileCheck = -1L; private volatile long lastJspQueueUpdate = System.currentTimeMillis(); /* JSP idle timeout in milliseconds */ private long jspIdleTimeout; /** * Maps JSP pages to their JspServletWrapper's */ private final Map<String, JspServletWrapper> jsps = new ConcurrentHashMap<>(); /** * Keeps JSP pages ordered by last access. */ private FastRemovalDequeue<JspServletWrapper> jspQueue = null; // ------------------------------------------------------ Public Methods /** * Add a new JspServletWrapper. * * @param jspUri JSP URI * @param jsw Servlet wrapper for JSP */ public void addWrapper(String jspUri, JspServletWrapper jsw) { jsps.put(jspUri, jsw); } /** * Get an already existing JspServletWrapper. * * @param jspUri JSP URI * @return JspServletWrapper for JSP */ public JspServletWrapper getWrapper(String jspUri) { return jsps.get(jspUri); } /** * Remove a JspServletWrapper. * * @param jspUri JSP URI of JspServletWrapper to remove */ public void removeWrapper(String jspUri) { jsps.remove(jspUri); } /** * Push a newly compiled JspServletWrapper into the queue at first * execution of jsp. Destroy any JSP that has been replaced in the queue. * * @param jsw Servlet wrapper for jsp. * @return an unloadHandle that can be pushed to front of queue at later execution times. * */ public FastRemovalDequeue<JspServletWrapper>.Entry push(JspServletWrapper jsw) { if (log.isTraceEnabled()) { log.trace(Localizer.getMessage("jsp.message.jsp_added", jsw.getJspUri(), context.getContextPath())); } FastRemovalDequeue<JspServletWrapper>.Entry entry = jspQueue.push(jsw); JspServletWrapper replaced = entry.getReplaced(); if (replaced != null) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.message.jsp_removed_excess", replaced.getJspUri(), context.getContextPath())); } unloadJspServletWrapper(replaced); entry.clearReplaced(); } return entry; } /** * Push unloadHandle for JspServletWrapper to front of the queue. * * @param unloadHandle the unloadHandle for the jsp. * */ public void makeYoungest(FastRemovalDequeue<JspServletWrapper>.Entry unloadHandle) { if (log.isTraceEnabled()) { JspServletWrapper jsw = unloadHandle.getContent(); log.trace(Localizer.getMessage("jsp.message.jsp_queue_update", jsw.getJspUri(), context.getContextPath())); } jspQueue.moveFirst(unloadHandle); } /** * Returns the number of JSPs for which JspServletWrappers exist, i.e., * the number of JSPs that have been loaded into the webapp. * * @return The number of JSPs that have been loaded into the webapp */ public int getJspCount() { return jsps.size(); } /** * Get the SecurityManager Policy CodeSource for this web * application context. * * @return CodeSource for JSP */ public CodeSource getCodeSource() { return codeSource; } /** * Get the parent ClassLoader. * * @return ClassLoader parent */ public ClassLoader getParentClassLoader() { return parentClassLoader; } /** * Get the SecurityManager PermissionCollection for this * web application context. * * @return PermissionCollection permissions */ public PermissionCollection getPermissionCollection() { return permissionCollection; } /** * Process a "destroy" event for this web application context. */ public void destroy() { Iterator<JspServletWrapper> servlets = jsps.values().iterator(); while (servlets.hasNext()) { servlets.next().destroy(); } } /** * Increments the JSP reload counter. */ public void incrementJspReloadCount() { jspReloadCount.incrementAndGet(); } /** * Resets the JSP reload counter. * * @param count Value to which to reset the JSP reload counter */ public void setJspReloadCount(int count) { jspReloadCount.set(count); } /** * Gets the current value of the JSP reload counter. * * @return The current value of the JSP reload counter */ public int getJspReloadCount() { return jspReloadCount.intValue(); } /** * Gets the number of JSPs that are in the JSP limiter queue * * @return The number of JSPs (in the webapp with which this JspServlet is * associated) that are in the JSP limiter queue */ public int getJspQueueLength() { if (jspQueue != null) { return jspQueue.getSize(); } return -1; } /** * Gets the number of JSPs that have been unloaded. * * @return The number of JSPs (in the webapp with which this JspServlet is * associated) that have been unloaded */ public int getJspUnloadCount() { return jspUnloadCount.intValue(); } /** * Method used by background thread to check the JSP dependencies * registered with this class for JSP's. */ public void checkCompile() { if (lastCompileCheck < 0) { // Checking was disabled return; } long now = System.currentTimeMillis(); if (now > (lastCompileCheck + (options.getCheckInterval() * 1000L))) { lastCompileCheck = now; } else { return; } Object [] wrappers = jsps.values().toArray(); for (int i = 0; i < wrappers.length; i++ ) { JspServletWrapper jsw = (JspServletWrapper)wrappers[i]; JspCompilationContext ctxt = jsw.getJspEngineContext(); // JspServletWrapper also synchronizes on this when // it detects it has to do a reload synchronized(jsw) { try { ctxt.compile(); } catch (FileNotFoundException ex) { ctxt.incrementRemoved(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); jsw.getServletContext().log("Background compile failed", t); } } } } /** * The classpath that is passed off to the Java compiler. */ public String getClassPath() { return classpath; } /** * Last time the update background task has run */ public long getLastJspQueueUpdate() { return lastJspQueueUpdate; } // -------------------------------------------------------- Private Methods /** * Method used to initialize classpath for compiles. */ private String initClassPath() { StringBuilder cpath = new StringBuilder(); String sep = System.getProperty("path.separator"); if (parentClassLoader instanceof URLClassLoader) { URL [] urls = ((URLClassLoader)parentClassLoader).getURLs(); for(int i = 0; i < urls.length; i++) { // Tomcat 4 can use URL's other than file URL's, // a protocol other than file: will generate a // bad file system path, so only add file: // protocol URL's to the classpath. if( urls[i].getProtocol().equals("file") ) { cpath.append(urls[i].getFile()+sep); } } } cpath.append(options.getScratchDir() + sep); String cp = (String) context.getAttribute(Constants.SERVLET_CLASSPATH); if (cp == null || cp.equals("")) { cp = options.getClassPath(); } String path = cpath.toString() + cp; if(log.isDebugEnabled()) { log.debug("Compilation classpath initialized: " + path); } return path; } // Helper class to allow initSecurity() to return two items private static class SecurityHolder{ private final CodeSource cs; private final PermissionCollection pc; private SecurityHolder(CodeSource cs, PermissionCollection pc){ this.cs = cs; this.pc = pc; } } /** * Method used to initialize SecurityManager data. */ private SecurityHolder initSecurity() { // Setup the PermissionCollection for this web app context // based on the permissions configured for the root of the // web app context directory, then add a file read permission // for that directory. Policy policy = Policy.getPolicy(); CodeSource source = null; PermissionCollection permissions = null; if( policy != null ) { try { // Get the permissions for the web app context String docBase = context.getRealPath("/"); if( docBase == null ) { docBase = options.getScratchDir().toString(); } String codeBase = docBase; if (!codeBase.endsWith(File.separator)){ codeBase = codeBase + File.separator; } File contextDir = new File(codeBase); URL url = contextDir.getCanonicalFile().toURI().toURL(); source = new CodeSource(url,(Certificate[])null); permissions = policy.getPermissions(source); // Create a file read permission for web app context directory if (!docBase.endsWith(File.separator)){ permissions.add (new FilePermission(docBase,"read")); docBase = docBase + File.separator; } else { permissions.add (new FilePermission (docBase.substring(0,docBase.length() - 1),"read")); } docBase = docBase + "-"; permissions.add(new FilePermission(docBase,"read")); // Spec says apps should have read/write for their temp // directory. This is fine, as no security sensitive files, at // least any that the app doesn't have full control of anyway, // will be written here. String workDir = options.getScratchDir().toString(); if (!workDir.endsWith(File.separator)){ permissions.add (new FilePermission(workDir,"read,write")); workDir = workDir + File.separator; } workDir = workDir + "-"; permissions.add(new FilePermission( workDir,"read,write,delete")); // Allow the JSP to access org.apache.jasper.runtime.HttpJspBase permissions.add( new RuntimePermission( "accessClassInPackage.org.apache.jasper.runtime") ); if (parentClassLoader instanceof URLClassLoader) { URL [] urls = ((URLClassLoader)parentClassLoader).getURLs(); String jarUrl = null; String jndiUrl = null; for (int i=0; i<urls.length; i++) { if (jndiUrl == null && urls[i].toString().startsWith("jndi:") ) { jndiUrl = urls[i].toString() + "-"; } if (jarUrl == null && urls[i].toString().startsWith("jar:jndi:") ) { jarUrl = urls[i].toString(); jarUrl = jarUrl.substring(0,jarUrl.length() - 2); jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('/')) + "/-"; } } if (jarUrl != null) { permissions.add( new FilePermission(jarUrl,"read")); permissions.add( new FilePermission(jarUrl.substring(4),"read")); } if (jndiUrl != null) permissions.add( new FilePermission(jndiUrl,"read") ); } } catch(Exception e) { context.log("Security Init for context failed",e); } } return new SecurityHolder(source, permissions); } private void unloadJspServletWrapper(JspServletWrapper jsw) { removeWrapper(jsw.getJspUri()); synchronized(jsw) { jsw.destroy(); } jspUnloadCount.incrementAndGet(); } /** * Method used by background thread to check if any JSP's should be unloaded. */ public void checkUnload() { if (log.isTraceEnabled()) { int queueLength = -1; if (jspQueue != null) { queueLength = jspQueue.getSize(); } log.trace(Localizer.getMessage("jsp.message.jsp_unload_check", context.getContextPath(), "" + jsps.size(), "" + queueLength)); } long now = System.currentTimeMillis(); if (jspIdleTimeout > 0) { long unloadBefore = now - jspIdleTimeout; Object [] wrappers = jsps.values().toArray(); for (int i = 0; i < wrappers.length; i++ ) { JspServletWrapper jsw = (JspServletWrapper)wrappers[i]; synchronized(jsw) { if (jsw.getLastUsageTime() < unloadBefore) { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.message.jsp_removed_idle", jsw.getJspUri(), context.getContextPath(), "" + (now-jsw.getLastUsageTime()))); } if (jspQueue != null) { jspQueue.remove(jsw.getUnloadHandle()); } unloadJspServletWrapper(jsw); } } } } lastJspQueueUpdate = now; } }
55,905
Bug 55905 Error message unhelpful when web.xml references a tld file that doesn't exist
null
resolved fixed
bcb9c58
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-18T19:28:21Z
2013-12-18T20:53:20Z
java/org/apache/jasper/servlet/TldScanner.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.servlet; import java.io.File; import java.io.IOException; import java.net.JarURLConnection; import java.net.URL; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.ServletContext; import javax.servlet.descriptor.JspConfigDescriptor; import javax.servlet.descriptor.TaglibDescriptor; import org.apache.jasper.compiler.JarScannerFactory; import org.apache.jasper.compiler.Localizer; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.JarScanType; import org.apache.tomcat.JarScanner; import org.apache.tomcat.JarScannerCallback; import org.apache.tomcat.util.descriptor.tld.TaglibXml; import org.apache.tomcat.util.descriptor.tld.TldParser; import org.apache.tomcat.util.descriptor.tld.TldResourcePath; import org.apache.tomcat.util.scan.Jar; import org.apache.tomcat.util.scan.JarFactory; import org.xml.sax.SAXException; /** * Scans for and loads Tag Library Descriptors contained in a web application. */ public class TldScanner { private static final Log log = LogFactory.getLog(TldScanner.class); private static final String MSG = "org.apache.jasper.servlet.TldScanner"; private static final String TLD_EXT = ".tld"; private static final String WEB_INF = "/WEB-INF/"; private final ServletContext context; private final TldParser tldParser; private final Map<String, TldResourcePath> uriTldResourcePathMap = new HashMap<>(); private final Map<TldResourcePath, TaglibXml> tldResourcePathTaglibXmlMap = new HashMap<>(); private final List<String> listeners = new ArrayList<>(); /** * Initialize with the application's ServletContext. * * @param context the application's servletContext */ public TldScanner(ServletContext context, boolean namespaceAware, boolean validation, boolean blockExternal) { this.context = context; this.tldParser = new TldParser(namespaceAware, validation, blockExternal); } /** * Scan for TLDs in all places defined by the specification: * <ol> * <li>Tag libraries defined by the platform</li> * <li>Entries from &lt;jsp-config&gt; in web.xml</li> * <li>A resources under /WEB-INF</li> * <li>In jar files from /WEB-INF/lib</li> * <li>Additional entries from the container</li> * </ol> * * @throws IOException if there was a problem scanning for or loading a TLD * @throws SAXException if there was a problem parsing a TLD */ public void scan() throws IOException, SAXException { scanPlatform(); scanJspConfig(); scanResourcePaths(WEB_INF); scanJars(); } /** * Returns the map of URI to TldResourcePath built by this scanner. * * @return the map of URI to TldResourcePath */ public Map<String, TldResourcePath> getUriTldResourcePathMap() { return uriTldResourcePathMap; } /** * Returns the map of TldResourcePath to parsed XML files built by this * scanner. * * @return the map of TldResourcePath to parsed XML files */ public Map<TldResourcePath,TaglibXml> getTldResourcePathTaglibXmlMap() { return tldResourcePathTaglibXmlMap; } /** * Returns a list of all listeners declared by scanned TLDs. * * @return a list of listener class names */ public List<String> getListeners() { return listeners; } /** * Set the class loader used by the digester to create objects as a result * of this scan. Normally this only needs tobe set when using JspC. */ public void setClassLoader(ClassLoader classLoader) { tldParser.setClassLoader(classLoader); } /** * Scan for TLDs required by the platform specification. */ protected void scanPlatform() { } /** * Scan for TLDs defined in &lt;jsp-config&gt;. */ protected void scanJspConfig() throws IOException, SAXException { JspConfigDescriptor jspConfigDescriptor = context.getJspConfigDescriptor(); if (jspConfigDescriptor == null) { return; } Collection<TaglibDescriptor> descriptors = jspConfigDescriptor.getTaglibs(); for (TaglibDescriptor descriptor : descriptors) { String taglibURI = descriptor.getTaglibURI(); String resourcePath = descriptor.getTaglibLocation(); // Note: Whilst the Servlet 2.4 DTD implies that the location must // be a context-relative path starting with '/', JSP.7.3.6.1 states // explicitly how paths that do not start with '/' should be // handled. if (!resourcePath.startsWith("/")) { resourcePath = WEB_INF + resourcePath; } if (uriTldResourcePathMap.containsKey(taglibURI)) { log.warn(Localizer.getMessage(MSG + ".webxmlSkip", resourcePath, taglibURI)); continue; } if (log.isTraceEnabled()) { log.trace(Localizer.getMessage(MSG + ".webxmlAdd", resourcePath, taglibURI)); } URL url = context.getResource(resourcePath); TldResourcePath tldResourcePath; if (resourcePath.endsWith(".jar")) { // if the path points to a jar file, the TLD is presumed to be // inside at META-INF/taglib.tld tldResourcePath = new TldResourcePath( url, resourcePath, "META-INF/taglib.tld"); } else { tldResourcePath = new TldResourcePath(url, resourcePath); } // parse TLD but store using the URI supplied in the descriptor TaglibXml tld = tldParser.parse(tldResourcePath); uriTldResourcePathMap.put(taglibURI, tldResourcePath); tldResourcePathTaglibXmlMap.put(tldResourcePath, tld); if (tld.getListeners() != null) { listeners.addAll(tld.getListeners()); } } } /** * Scan web application resources for TLDs, recursively. * * @param startPath the directory resource to scan * @throws IOException if there was a problem scanning for or loading a TLD * @throws SAXException if there was a problem parsing a TLD */ protected void scanResourcePaths(String startPath) throws IOException, SAXException { Set<String> dirList = context.getResourcePaths(startPath); if (dirList != null) { for (String path : dirList) { if (path.startsWith("/WEB-INF/classes/")) { // Skip: JSP.7.3.1 } else if (path.startsWith("/WEB-INF/lib/")) { // Skip: JSP.7.3.1 } else if (path.endsWith("/")) { scanResourcePaths(path); } else if (path.startsWith("/WEB-INF/tags/")) { // JSP 7.3.1: in /WEB-INF/tags only consider implicit.tld if (path.endsWith("/implicit.tld")) { parseTld(path); } } else if (path.endsWith(TLD_EXT)) { parseTld(path); } } } } /** * Scan for TLDs in JARs in /WEB-INF/lib. */ public void scanJars() { JarScanner scanner = JarScannerFactory.getJarScanner(context); TldScannerCallback callback = new TldScannerCallback(); scanner.scan(JarScanType.TLD, context, callback); if (callback.scanFoundNoTLDs()) { log.info(Localizer.getMessage("jsp.tldCache.noTldSummary")); } } private void parseTld(String resourcePath) throws IOException, SAXException { TldResourcePath tldResourcePath = new TldResourcePath(context.getResource(resourcePath), resourcePath); parseTld(tldResourcePath); } private void parseTld(TldResourcePath path) throws IOException, SAXException { if (tldResourcePathTaglibXmlMap.containsKey(path)) { // TLD has already been parsed as a result of processing web.xml return; } TaglibXml tld = tldParser.parse(path); String uri = tld.getUri(); if (uri != null) { if (!uriTldResourcePathMap.containsKey(uri)) { uriTldResourcePathMap.put(uri, path); } } tldResourcePathTaglibXmlMap.put(path, tld); if (tld.getListeners() != null) { listeners.addAll(tld.getListeners()); } } private class TldScannerCallback implements JarScannerCallback { private boolean tldFound = false; private boolean jarFound = false; @Override public void scan(JarURLConnection urlConn, String webappPath, boolean isWebapp) throws IOException { if (!jarFound) { jarFound = true; } boolean found = false; Jar jar = JarFactory.newInstance(urlConn.getURL()); URL jarURL = jar.getJarFileURL(); try { jar.nextEntry(); for (String entryName = jar.getEntryName(); entryName != null; jar.nextEntry(), entryName = jar.getEntryName()) { if (!(entryName.startsWith("META-INF/") && entryName.endsWith(TLD_EXT))) { continue; } found = true; TldResourcePath tldResourcePath = new TldResourcePath(jarURL, webappPath, entryName); try { parseTld(tldResourcePath); } catch (SAXException e) { throw new IOException(e); } } } finally { jar.close(); } if (found) { tldFound = true; } else { if (log.isDebugEnabled()) { log.debug(Localizer.getMessage("jsp.tldCache.noTldInJar", jarURL.toString())); } } } @Override public void scan(File file, final String webappPath, boolean isWebapp) throws IOException { if (!jarFound) { jarFound = true; } File metaInf = new File(file, "META-INF"); if (!metaInf.isDirectory()) { return; } final Path filePath = file.toPath(); Files.walkFileTree(metaInf.toPath(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (!file.getFileName().toString() .toLowerCase(Locale.ENGLISH).endsWith(TLD_EXT)) { return FileVisitResult.CONTINUE; } String subPath = file.subpath( filePath.getNameCount(), file.getNameCount()).toString(); if ('/' != File.separatorChar) { subPath = subPath.replace(File.separatorChar, '/'); } String resourcePath = webappPath + "/" + subPath; try { URL url = file.toUri().toURL(); TldResourcePath path = new TldResourcePath(url, resourcePath); parseTld(path); tldFound = true; } catch (SAXException e) { throw new IOException(e); } return FileVisitResult.CONTINUE; } }); } @Override public void scanWebInfClasses() throws IOException { // This is used when scanAllDirectories is enabled and one or more // JARs have been unpacked into WEB-INF/classes as happens with some // IDEs. // We know that WEB-INF/classes/META-INF must be a directory on disk String webappPath = WEB_INF + "classes"; String realPath = context.getRealPath(webappPath); File webInfClasses = new File(realPath); scan(webInfClasses, webappPath, true); } private boolean scanFoundNoTLDs() { return jarFound && !tldFound; } } }
55,939
Bug 55939 Seeing issues with non-blocking io when writing lots of data
null
resolved fixed
411e4cc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2013-12-30T19:39:23Z
2013-12-29T23:33:20Z
java/org/apache/coyote/Response.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.io.StringReader; import java.util.Locale; import java.util.concurrent.atomic.AtomicBoolean; import javax.servlet.WriteListener; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.http.MimeHeaders; import org.apache.tomcat.util.http.parser.HttpParser; import org.apache.tomcat.util.http.parser.MediaType; import org.apache.tomcat.util.res.StringManager; /** * Response object. * * @author James Duncan Davidson [duncan@eng.sun.com] * @author Jason Hunter [jch@eng.sun.com] * @author James Todd [gonzo@eng.sun.com] * @author Harish Prabandham * @author Hans Bergsten <hans@gefionsoftware.com> * @author Remy Maucherat */ public final class Response { private static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------- Class Variables /** * Default locale as mandated by the spec. */ private static final Locale DEFAULT_LOCALE = Locale.getDefault(); // ----------------------------------------------------- Instance Variables /** * Status code. */ protected int status = 200; /** * Status message. */ protected String message = null; /** * Response headers. */ protected final MimeHeaders headers = new MimeHeaders(); /** * Associated output buffer. */ protected OutputBuffer outputBuffer; /** * Notes. */ protected final Object notes[] = new Object[Constants.MAX_NOTES]; /** * Committed flag. */ protected boolean commited = false; /** * Action hook. */ public ActionHook hook; /** * HTTP specific fields. */ protected String contentType = null; protected String contentLanguage = null; protected String characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; protected long contentLength = -1; private Locale locale = DEFAULT_LOCALE; // General informations private long contentWritten = 0; private long commitTime = -1; /** * Holds request error exception. */ protected Exception errorException = null; /** * Has the charset been explicitly set. */ protected boolean charsetSet = false; protected Request req; // ------------------------------------------------------------- Properties public Request getRequest() { return req; } public void setRequest( Request req ) { this.req=req; } public OutputBuffer getOutputBuffer() { return outputBuffer; } public void setOutputBuffer(OutputBuffer outputBuffer) { this.outputBuffer = outputBuffer; } public MimeHeaders getMimeHeaders() { return headers; } public ActionHook getHook() { return hook; } public void setHook(ActionHook hook) { this.hook = hook; } // -------------------- Per-Response "notes" -------------------- public final void setNote(int pos, Object value) { notes[pos] = value; } public final Object getNote(int pos) { return notes[pos]; } // -------------------- Actions -------------------- public void action(ActionCode actionCode, Object param) { if (hook != null) { if( param==null ) hook.action(actionCode, this); else hook.action(actionCode, param); } } // -------------------- State -------------------- public int getStatus() { return status; } /** * Set the response status */ public void setStatus( int status ) { this.status = status; } /** * Get the status message. */ public String getMessage() { return message; } /** * Set the status message. */ public void setMessage(String message) { this.message = message; } public boolean isCommitted() { return commited; } public void setCommitted(boolean v) { if (v && !this.commited) { this.commitTime = System.currentTimeMillis(); } this.commited = v; } /** * Return the time the response was committed (based on System.currentTimeMillis). * * @return the time the response was committed */ public long getCommitTime() { return commitTime; } // -----------------Error State -------------------- /** * Set the error Exception that occurred during * request processing. */ public void setErrorException(Exception ex) { errorException = ex; } /** * Get the Exception that occurred during request * processing. */ public Exception getErrorException() { return errorException; } public boolean isExceptionPresent() { return ( errorException != null ); } // -------------------- Methods -------------------- public void reset() throws IllegalStateException { // Reset the headers only if this is the main request, // not for included contentType = null; locale = DEFAULT_LOCALE; contentLanguage = null; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; contentLength = -1; charsetSet = false; status = 200; message = null; headers.clear(); // Force the PrintWriter to flush its data to the output // stream before resetting the output stream // // Reset the stream if (commited) { //String msg = sm.getString("servletOutputStreamImpl.reset.ise"); throw new IllegalStateException(); } action(ActionCode.RESET, this); } public void finish() { action(ActionCode.CLOSE, this); } public void acknowledge() { action(ActionCode.ACK, this); } // -------------------- Headers -------------------- /** * Warning: This method always returns <code>false<code> for Content-Type * and Content-Length. */ public boolean containsHeader(String name) { return headers.getHeader(name) != null; } public void setHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.setValue(name).setString( value); } public void addHeader(String name, String value) { char cc=name.charAt(0); if( cc=='C' || cc=='c' ) { if( checkSpecialHeader(name, value) ) return; } headers.addValue(name).setString( value ); } /** * Set internal fields for special header names. * Called from set/addHeader. * Return true if the header is special, no need to set the header. */ private boolean checkSpecialHeader( String name, String value) { // XXX Eliminate redundant fields !!! // ( both header and in special fields ) if( name.equalsIgnoreCase( "Content-Type" ) ) { setContentType( value ); return true; } if( name.equalsIgnoreCase( "Content-Length" ) ) { try { long cL=Long.parseLong( value ); setContentLength( cL ); return true; } catch( NumberFormatException ex ) { // Do nothing - the spec doesn't have any "throws" // and the user might know what he's doing return false; } } return false; } /** Signal that we're done with the headers, and body will follow. * Any implementation needs to notify ContextManager, to allow * interceptors to fix headers. */ public void sendHeaders() { action(ActionCode.COMMIT, this); setCommitted(true); } // -------------------- I18N -------------------- public Locale getLocale() { return locale; } /** * Called explicitly by user to set the Content-Language and * the default encoding */ public void setLocale(Locale locale) { if (locale == null) { return; // throw an exception? } // Save the locale for use by getLocale() this.locale = locale; // Set the contentLanguage for header output contentLanguage = locale.getLanguage(); if ((contentLanguage != null) && (contentLanguage.length() > 0)) { String country = locale.getCountry(); StringBuilder value = new StringBuilder(contentLanguage); if ((country != null) && (country.length() > 0)) { value.append('-'); value.append(country); } contentLanguage = value.toString(); } } /** * Return the content language. */ public String getContentLanguage() { return contentLanguage; } /* * Overrides the name of the character encoding used in the body * of the response. This method must be called prior to writing output * using getWriter(). * * @param charset String containing the name of the character encoding. */ public void setCharacterEncoding(String charset) { if (isCommitted()) return; if (charset == null) return; characterEncoding = charset; charsetSet=true; } public String getCharacterEncoding() { return characterEncoding; } /** * Sets the content type. * * This method must preserve any response charset that may already have * been set via a call to response.setContentType(), response.setLocale(), * or response.setCharacterEncoding(). * * @param type the content type */ public void setContentType(String type) { if (type == null) { this.contentType = null; return; } MediaType m = null; try { m = HttpParser.parseMediaType(new StringReader(type)); } catch (IOException e) { // Ignore - null test below handles this } if (m == null) { // Invalid - Assume no charset and just pass through whatever // the user provided. this.contentType = type; return; } this.contentType = m.toStringNoCharset(); String charsetValue = m.getCharset(); if (charsetValue != null) { charsetValue = charsetValue.trim(); if (charsetValue.length() > 0) { charsetSet = true; this.characterEncoding = charsetValue; } } } public void setContentTypeNoCharset(String type) { this.contentType = type; } public String getContentType() { String ret = contentType; if (ret != null && characterEncoding != null && charsetSet) { ret = ret + ";charset=" + characterEncoding; } return ret; } public void setContentLength(int contentLength) { this.contentLength = contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public int getContentLength() { long length = getContentLengthLong(); if (length < Integer.MAX_VALUE) { return (int) length; } return -1; } public long getContentLengthLong() { return contentLength; } /** * Write a chunk of bytes. */ public void doWrite(ByteChunk chunk/*byte buffer[], int pos, int count*/) throws IOException { outputBuffer.doWrite(chunk, this); contentWritten+=chunk.getLength(); } // -------------------- public void recycle() { contentType = null; contentLanguage = null; locale = DEFAULT_LOCALE; characterEncoding = Constants.DEFAULT_CHARACTER_ENCODING; charsetSet = false; contentLength = -1; status = 200; message = null; commited = false; commitTime = -1; errorException = null; headers.clear(); listener = null; // update counters contentWritten=0; } /** * Bytes written by application - i.e. before compression, chunking, etc. */ public long getContentWritten() { return contentWritten; } /** * Bytes written to socket - i.e. after compression, chunking, etc. */ public long getBytesWritten(boolean flush) { if (flush) { action(ActionCode.CLIENT_FLUSH, this); } return outputBuffer.getBytesWritten(); } /* * State for non-blocking output is maintained here as it is the one point * easily reachable from the CoyoteOutputStream and the Processor which both * need access to state. */ protected volatile WriteListener listener; private boolean fireListener = false; private boolean registeredForWrite = false; private final Object nonBlockingStateLock = new Object(); public WriteListener getWriteListener() { return listener; } public void setWriteListener(WriteListener listener) { if (listener == null) { throw new NullPointerException( sm.getString("response.nullWriteListener")); } if (getWriteListener() != null) { throw new IllegalStateException( sm.getString("response.writeListenerSet")); } // Note: This class is not used for HTTP upgrade so only need to test // for async AtomicBoolean result = new AtomicBoolean(false); action(ActionCode.ASYNC_IS_ASYNC, result); if (!result.get()) { throw new IllegalStateException( sm.getString("response.notAsync")); } this.listener = listener; // The container is responsible for the first call to // listener.onWritePossible(). If isReady() returns true, the container // needs to call listener.onWritePossible() from a new thread. If // isReady() returns false, the socket will be registered for write and // the container will call listener.onWritePossible() once data can be // written. if (isReady()) { action(ActionCode.DISPATCH_WRITE, null); // Need to set the fireListener flag otherwise when the container // tries to trigger onWritePossible, nothing will happen synchronized (nonBlockingStateLock) { fireListener = true; } } } public boolean isReady() { if (listener == null) { // TODO i18n throw new IllegalStateException("not in non blocking mode."); } // Assume write is not possible boolean ready = false; synchronized (nonBlockingStateLock) { if (registeredForWrite) { fireListener = true; return false; } ready = checkRegisterForWrite(false); fireListener = !ready; } return ready; } public boolean checkRegisterForWrite(boolean internal) { AtomicBoolean ready = new AtomicBoolean(false); synchronized (nonBlockingStateLock) { if (!registeredForWrite || internal) { action(ActionCode.NB_WRITE_INTEREST, ready); registeredForWrite = !ready.get(); } } return ready.get(); } public void onWritePossible() throws IOException { // Any buffered data left over from a previous non-blocking write is // written in the Processor so if this point is reached the app is able // to write data. boolean fire = false; synchronized (nonBlockingStateLock) { registeredForWrite = false; if (fireListener) { fireListener = false; fire = true; } } if (fire) { listener.onWritePossible(); } } }
55,937
Bug 55937 Tomcat auto deployer not working for ROOT applications
null
resolved fixed
346e264
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T11:38:52Z
2013-12-27T21:33:20Z
java/org/apache/catalina/util/ContextName.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.util.Locale; /** * Utility class to manage context names so there is one place where the * conversions between baseName, path and version take place. */ public final class ContextName { public static final String ROOT_NAME = "ROOT"; private static final String VERSION_MARKER = "##"; private static final String FWD_SLASH_REPLACEMENT = "#"; private final String baseName; private final String path; private final String version; private final String name; /** * Creates an instance from a context name, display name, base name, * directory name, WAR name or context.xml name. * * @param name The name to use as the basis for this object */ public ContextName(String name) { String tmp1 = name; // Convert Context names and display names to base names // Strip off any leading "/" if (tmp1.startsWith("/")) { tmp1 = tmp1.substring(1); } // Replace any remaining / tmp1 = tmp1.replaceAll("/", FWD_SLASH_REPLACEMENT); // Insert the ROOT name if required if (tmp1.startsWith(VERSION_MARKER) || "".equals(tmp1)) { tmp1 = ROOT_NAME + tmp1; } // Remove any file extensions if (tmp1.toLowerCase(Locale.ENGLISH).endsWith(".war") || tmp1.toLowerCase(Locale.ENGLISH).endsWith(".xml")) { tmp1 = tmp1.substring(0, tmp1.length() -4); } baseName = tmp1; String tmp2; // Extract version number int versionIndex = baseName.indexOf(VERSION_MARKER); if (versionIndex > -1) { version = baseName.substring(versionIndex + 2); tmp2 = baseName.substring(0, versionIndex); } else { version = ""; tmp2 = baseName; } if (ROOT_NAME.equals(tmp2)) { path = ""; } else { path = "/" + tmp2.replaceAll(FWD_SLASH_REPLACEMENT, "/"); } if (versionIndex > -1) { this.name = path + VERSION_MARKER + version; } else { this.name = path; } } /** * Construct an instance from a path and version. * * @param path Context path to use * @param version Context version to use */ public ContextName(String path, String version) { // Path should never be null or '/' if (path == null || "/".equals(path)) { this.path = ""; } else { this.path = path; } // Version should never be null if (version == null) { this.version = ""; } else { this.version = version; } // Name is path + version if ("".equals(this.version)) { name = this.path; } else { name = this.path + VERSION_MARKER + this.version; } // Base name is converted path + version StringBuilder tmp = new StringBuilder(); if ("".equals(this.path)) { tmp.append(ROOT_NAME); } else { tmp.append(this.path.substring(1).replaceAll("/", FWD_SLASH_REPLACEMENT)); } if (this.version.length() > 0) { tmp.append(VERSION_MARKER); tmp.append(this.version); } this.baseName = tmp.toString(); } public String getBaseName() { return baseName; } public String getPath() { return path; } public String getVersion() { return version; } public String getName() { return name; } public String getDisplayName() { StringBuilder tmp = new StringBuilder(); if ("".equals(path)) { tmp.append('/'); } else { tmp.append(path); } if (!"".equals(version)) { tmp.append(VERSION_MARKER); tmp.append(version); } return tmp.toString(); } @Override public String toString() { return getDisplayName(); } }
55,937
Bug 55937 Tomcat auto deployer not working for ROOT applications
null
resolved fixed
346e264
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T11:38:52Z
2013-12-27T21:33:20Z
test/org/apache/catalina/util/TestContextName.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 static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class TestContextName { private ContextName cn1; private ContextName cn2; private ContextName cn3; private ContextName cn4; private ContextName cn5; private ContextName cn6; private ContextName cn7; private ContextName cn8; private ContextName cn9; private ContextName cn10; private ContextName cn11; private ContextName cn12; private ContextName cn13; private ContextName cn14; private ContextName cn15; private ContextName cn16; @Before public void setUp() throws Exception { cn1 = new ContextName(null, null); cn2 = new ContextName("", null); cn3 = new ContextName("/", null); cn4 = new ContextName("/foo", null); cn5 = new ContextName("/foo/bar", null); cn6 = new ContextName(null, "A"); cn7 = new ContextName("", "B"); cn8 = new ContextName("/", "C"); cn9 = new ContextName("/foo", "D"); cn10 = new ContextName("/foo/bar", "E"); cn11 = new ContextName("ROOT"); cn12 = new ContextName("foo"); cn13 = new ContextName("foo#bar"); cn14 = new ContextName("ROOT##A"); cn15 = new ContextName("foo##D"); cn16 = new ContextName("foo#bar##E"); } @Test public void testGetBaseName() { assertEquals("ROOT", cn1.getBaseName()); assertEquals("ROOT", cn2.getBaseName()); assertEquals("ROOT", cn3.getBaseName()); assertEquals("foo", cn4.getBaseName()); assertEquals("foo#bar", cn5.getBaseName()); assertEquals("ROOT##A", cn6.getBaseName()); assertEquals("ROOT##B", cn7.getBaseName()); assertEquals("ROOT##C", cn8.getBaseName()); assertEquals("foo##D", cn9.getBaseName()); assertEquals("foo#bar##E", cn10.getBaseName()); assertEquals("ROOT", cn11.getBaseName()); assertEquals("foo", cn12.getBaseName()); assertEquals("foo#bar", cn13.getBaseName()); assertEquals("ROOT##A", cn14.getBaseName()); assertEquals("foo##D", cn15.getBaseName()); assertEquals("foo#bar##E", cn16.getBaseName()); } @Test public void testGetPath() { assertEquals("", cn1.getPath()); assertEquals("", cn2.getPath()); assertEquals("", cn3.getPath()); assertEquals("/foo", cn4.getPath()); assertEquals("/foo/bar", cn5.getPath()); assertEquals("", cn6.getPath()); assertEquals("", cn7.getPath()); assertEquals("", cn8.getPath()); assertEquals("/foo", cn9.getPath()); assertEquals("/foo/bar", cn10.getPath()); assertEquals("", cn11.getPath()); assertEquals("/foo", cn12.getPath()); assertEquals("/foo/bar", cn13.getPath()); assertEquals("", cn14.getPath()); assertEquals("/foo", cn15.getPath()); assertEquals("/foo/bar", cn16.getPath()); } @Test public void testGetVersion() { assertEquals("", cn1.getVersion()); assertEquals("", cn2.getVersion()); assertEquals("", cn3.getVersion()); assertEquals("", cn4.getVersion()); assertEquals("", cn5.getVersion()); assertEquals("A", cn6.getVersion()); assertEquals("B", cn7.getVersion()); assertEquals("C", cn8.getVersion()); assertEquals("D", cn9.getVersion()); assertEquals("E", cn10.getVersion()); assertEquals("", cn11.getVersion()); assertEquals("", cn12.getVersion()); assertEquals("", cn13.getVersion()); assertEquals("A", cn14.getVersion()); assertEquals("D", cn15.getVersion()); assertEquals("E", cn16.getVersion()); } @Test public void testGetName() { assertEquals("", cn1.getName()); assertEquals("", cn2.getName()); assertEquals("", cn3.getName()); assertEquals("/foo", cn4.getName()); assertEquals("/foo/bar", cn5.getName()); assertEquals("##A", cn6.getName()); assertEquals("##B", cn7.getName()); assertEquals("##C", cn8.getName()); assertEquals("/foo##D", cn9.getName()); assertEquals("/foo/bar##E", cn10.getName()); assertEquals("", cn11.getName()); assertEquals("/foo", cn12.getName()); assertEquals("/foo/bar", cn13.getName()); assertEquals("##A", cn14.getName()); assertEquals("/foo##D", cn15.getName()); assertEquals("/foo/bar##E", cn16.getName()); } @Test public void testGetDisplayName() { assertEquals("/", cn1.getDisplayName()); assertEquals("/", cn2.getDisplayName()); assertEquals("/", cn3.getDisplayName()); assertEquals("/foo", cn4.getDisplayName()); assertEquals("/foo/bar", cn5.getDisplayName()); assertEquals("/##A", cn6.getDisplayName()); assertEquals("/##B", cn7.getDisplayName()); assertEquals("/##C", cn8.getDisplayName()); assertEquals("/foo##D", cn9.getDisplayName()); assertEquals("/foo/bar##E", cn10.getDisplayName()); assertEquals("/", cn11.getDisplayName()); assertEquals("/foo", cn12.getDisplayName()); assertEquals("/foo/bar", cn13.getDisplayName()); assertEquals("/##A", cn14.getDisplayName()); assertEquals("/foo##D", cn15.getDisplayName()); assertEquals("/foo/bar##E", cn16.getDisplayName()); } @Test public void testConstructorString() { doTestConstructorString(cn1); doTestConstructorString(cn2); doTestConstructorString(cn3); doTestConstructorString(cn4); doTestConstructorString(cn5); doTestConstructorString(cn6); doTestConstructorString(cn7); doTestConstructorString(cn8); doTestConstructorString(cn9); doTestConstructorString(cn10); doTestConstructorString(cn11); doTestConstructorString(cn12); doTestConstructorString(cn13); doTestConstructorString(cn14); doTestConstructorString(cn15); doTestConstructorString(cn16); } private void doTestConstructorString(ContextName src) { doCompare(src, new ContextName(src.getBaseName())); doCompare(src, new ContextName(src.getDisplayName())); doCompare(src, new ContextName(src.getName())); } private void doCompare(ContextName cn1, ContextName cn2) { assertEquals(cn1.getBaseName(), cn2.getBaseName()); assertEquals(cn1.getDisplayName(), cn2.getDisplayName()); assertEquals(cn1.getName(), cn2.getName()); assertEquals(cn1.getPath(), cn2.getPath()); assertEquals(cn1.getVersion(), cn2.getVersion()); } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/core/ContainerBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.core; import java.beans.PropertyChangeListener; import java.beans.PropertyChangeSupport; import java.io.File; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.management.ObjectName; import org.apache.catalina.AccessLog; import org.apache.catalina.Cluster; import org.apache.catalina.Container; import org.apache.catalina.ContainerEvent; import org.apache.catalina.ContainerListener; 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.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Loader; import org.apache.catalina.Pipeline; import org.apache.catalina.Realm; import org.apache.catalina.Valve; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * Abstract implementation of the <b>Container</b> interface, providing common * functionality required by nearly every implementation. Classes extending * this base class must may implement a replacement for <code>invoke()</code>. * <p> * All subclasses of this abstract base class will include support for a * Pipeline object that defines the processing to be performed for each request * received by the <code>invoke()</code> method of this class, utilizing the * "Chain of Responsibility" design pattern. A subclass should encapsulate its * own processing functionality as a <code>Valve</code>, and configure this * Valve into the pipeline by calling <code>setBasic()</code>. * <p> * This implementation fires property change events, per the JavaBeans design * pattern, for changes in singleton properties. In addition, it fires the * following <code>ContainerEvent</code> events to listeners who register * themselves with <code>addContainerListener()</code>: * <table border=1> * <tr> * <th>Type</th> * <th>Data</th> * <th>Description</th> * </tr> * <tr> * <td align=center><code>addChild</code></td> * <td align=center><code>Container</code></td> * <td>Child container added to this Container.</td> * </tr> * <tr> * <td align=center><code>addValve</code></td> * <td align=center><code>Valve</code></td> * <td>Valve added to this Container.</td> * </tr> * <tr> * <td align=center><code>removeChild</code></td> * <td align=center><code>Container</code></td> * <td>Child container removed from this Container.</td> * </tr> * <tr> * <td align=center><code>removeValve</code></td> * <td align=center><code>Valve</code></td> * <td>Valve removed from this Container.</td> * </tr> * <tr> * <td align=center><code>start</code></td> * <td align=center><code>null</code></td> * <td>Container was started.</td> * </tr> * <tr> * <td align=center><code>stop</code></td> * <td align=center><code>null</code></td> * <td>Container was stopped.</td> * </tr> * </table> * Subclasses that fire additional events should document them in the * class comments of the implementation class. * * TODO: Review synchronisation around background processing. See bug 47024. * * @author Craig R. McClanahan */ public abstract class ContainerBase extends LifecycleMBeanBase implements Container { private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog( ContainerBase.class ); /** * Perform addChild with the permissions of this class. * addChild can be called with the XML parser on the stack, * this allows the XML parser to have fewer privileges than * Tomcat. */ protected class PrivilegedAddChild implements PrivilegedAction<Void> { private final Container child; PrivilegedAddChild(Container child) { this.child = child; } @Override public Void run() { addChildInternal(child); return null; } } // ----------------------------------------------------- Instance Variables /** * The child Containers belonging to this Container, keyed by name. */ protected final HashMap<String, Container> children = new HashMap<>(); /** * The processor delay for this component. */ protected int backgroundProcessorDelay = -1; /** * The container event listeners for this Container. Implemented as a * CopyOnWriteArrayList since listeners may invoke methods to add/remove * themselves or other listeners and with a ReadWriteLock that would trigger * a deadlock. */ protected final List<ContainerListener> listeners = new CopyOnWriteArrayList<>(); /** * The Logger implementation with which this Container is associated. */ protected Log logger = null; /** * Associated logger name. */ protected String logName = null; /** * The cluster with which this Container is associated. */ protected Cluster cluster = null; private final ReadWriteLock clusterLock = new ReentrantReadWriteLock(); /** * The human-readable name of this Container. */ protected String name = null; /** * The parent Container to which this Container is a child. */ protected Container parent = null; /** * The parent class loader to be configured when we install a Loader. */ protected ClassLoader parentClassLoader = null; /** * The Pipeline object with which this Container is associated. */ protected final Pipeline pipeline = new StandardPipeline(this); /** * The Realm with which this Container is associated. */ private volatile Realm realm = null; /** * Lock used to control access to the Realm. */ private final ReadWriteLock realmLock = new ReentrantReadWriteLock(); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Will children be started automatically when they are added. */ protected boolean startChildren = true; /** * The property change support for this component. */ protected final PropertyChangeSupport support = new PropertyChangeSupport(this); /** * The background thread. */ private Thread thread = null; /** * The background thread completion semaphore. */ private volatile boolean threadDone = false; /** * The access log to use for requests normally handled by this container * that have been handled earlier in the processing chain. */ protected volatile AccessLog accessLog = null; private volatile boolean accessLogScanComplete = false; /** * The number of threads available to process start and stop events for any * children associated with this container. */ private int startStopThreads = 1; protected ThreadPoolExecutor startStopExecutor; // ------------------------------------------------------------- Properties @Override public int getStartStopThreads() { return startStopThreads; } /** * Handles the special values. */ private int getStartStopThreadsInternal() { int result = getStartStopThreads(); // Positive values are unchanged if (result > 0) { return result; } // Zero == Runtime.getRuntime().availableProcessors() // -ve == Runtime.getRuntime().availableProcessors() + value // These two are the same result = Runtime.getRuntime().availableProcessors() + result; if (result < 1) { result = 1; } return result; } @Override public void setStartStopThreads(int startStopThreads) { this.startStopThreads = startStopThreads; // Use local copies to ensure thread safety ThreadPoolExecutor executor = startStopExecutor; if (executor != null) { int newThreads = getStartStopThreadsInternal(); executor.setMaximumPoolSize(newThreads); executor.setCorePoolSize(newThreads); } } /** * Get the delay between the invocation of the backgroundProcess method on * this container and its children. Child containers will not be invoked * if their delay value is not negative (which would mean they are using * their own thread). Setting this to a positive value will cause * a thread to be spawn. After waiting the specified amount of time, * the thread will invoke the executePeriodic method on this container * and all its children. */ @Override public int getBackgroundProcessorDelay() { return backgroundProcessorDelay; } /** * Set the delay between the invocation of the execute method on this * container and its children. * * @param delay The delay in seconds between the invocation of * backgroundProcess methods */ @Override public void setBackgroundProcessorDelay(int delay) { backgroundProcessorDelay = delay; } /** * Return the Logger for this Container. */ @Override public Log getLogger() { if (logger != null) return (logger); logger = LogFactory.getLog(logName()); return (logger); } /** * Return the Cluster with which this Container is associated. If there is * no associated Cluster, return the Cluster associated with our parent * Container (if any); otherwise return <code>null</code>. */ @Override public Cluster getCluster() { Lock readLock = clusterLock.readLock(); readLock.lock(); try { if (cluster != null) return cluster; if (parent != null) return parent.getCluster(); return null; } finally { readLock.unlock(); } } /* * Provide access to just the cluster component attached to this container. */ protected Cluster getClusterInternal() { Lock readLock = clusterLock.readLock(); readLock.lock(); try { return cluster; } finally { readLock.unlock(); } } /** * Set the Cluster with which this Container is associated. * * @param cluster The newly associated Cluster */ @Override public void setCluster(Cluster cluster) { Cluster oldCluster = null; Lock writeLock = clusterLock.writeLock(); writeLock.lock(); try { // Change components if necessary oldCluster = this.cluster; if (oldCluster == cluster) return; this.cluster = cluster; // Stop the old component if necessary if (getState().isAvailable() && (oldCluster != null) && (oldCluster instanceof Lifecycle)) { try { ((Lifecycle) oldCluster).stop(); } catch (LifecycleException e) { log.error("ContainerBase.setCluster: stop: ", e); } } // Start the new component if necessary if (cluster != null) cluster.setContainer(this); if (getState().isAvailable() && (cluster != null) && (cluster instanceof Lifecycle)) { try { ((Lifecycle) cluster).start(); } catch (LifecycleException e) { log.error("ContainerBase.setCluster: start: ", e); } } } finally { writeLock.unlock(); } // Report this property change to interested listeners support.firePropertyChange("cluster", oldCluster, cluster); } /** * Return a name string (suitable for use by humans) that describes this * Container. Within the set of child containers belonging to a particular * parent, Container names must be unique. */ @Override public String getName() { return (name); } /** * Set a name string (suitable for use by humans) that describes this * Container. Within the set of child containers belonging to a particular * parent, Container names must be unique. * * @param name New name of this container * * @exception IllegalStateException if this Container has already been * added to the children of a parent Container (after which the name * may not be changed) */ @Override public void setName(String name) { String oldName = this.name; this.name = name; support.firePropertyChange("name", oldName, this.name); } /** * Return if children of this container will be started automatically when * they are added to this container. */ public boolean getStartChildren() { return (startChildren); } /** * Set if children of this container will be started automatically when * they are added to this container. * * @param startChildren New value of the startChildren flag */ public void setStartChildren(boolean startChildren) { boolean oldStartChildren = this.startChildren; this.startChildren = startChildren; support.firePropertyChange("startChildren", oldStartChildren, this.startChildren); } /** * Return the Container for which this Container is a child, if there is * one. If there is no defined parent, return <code>null</code>. */ @Override public Container getParent() { return (parent); } /** * Set the parent Container to which this Container is being added as a * child. This Container may refuse to become attached to the specified * Container by throwing an exception. * * @param container Container to which this Container is being added * as a child * * @exception IllegalArgumentException if this Container refuses to become * attached to the specified Container */ @Override public void setParent(Container container) { Container oldParent = this.parent; this.parent = container; support.firePropertyChange("parent", oldParent, this.parent); } /** * 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 (parent != null) { return (parent.getParentClassLoader()); } return (ClassLoader.getSystemClassLoader()); } /** * Set the parent class loader (if any) for this web application. * This call is meaningful only <strong>before</strong> a Loader has * been configured, and the specified value (if non-null) should be * passed as an argument to the class loader constructor. * * * @param parent The new parent class loader */ @Override public void setParentClassLoader(ClassLoader parent) { ClassLoader oldParentClassLoader = this.parentClassLoader; this.parentClassLoader = parent; support.firePropertyChange("parentClassLoader", oldParentClassLoader, this.parentClassLoader); } /** * Return the Pipeline object that manages the Valves associated with * this Container. */ @Override public Pipeline getPipeline() { return (this.pipeline); } /** * Return the Realm with which this Container is associated. If there is * no associated Realm, return the Realm associated with our parent * Container (if any); otherwise return <code>null</code>. */ @Override public Realm getRealm() { Lock l = realmLock.readLock(); try { l.lock(); if (realm != null) return (realm); if (parent != null) return (parent.getRealm()); return null; } finally { l.unlock(); } } protected Realm getRealmInternal() { Lock l = realmLock.readLock(); try { l.lock(); return realm; } finally { l.unlock(); } } /** * Set the Realm with which this Container is associated. * * @param realm The newly associated Realm */ @Override public void setRealm(Realm realm) { Lock l = realmLock.writeLock(); try { l.lock(); // Change components if necessary Realm oldRealm = this.realm; if (oldRealm == realm) return; this.realm = realm; // Stop the old component if necessary if (getState().isAvailable() && (oldRealm != null) && (oldRealm instanceof Lifecycle)) { try { ((Lifecycle) oldRealm).stop(); } catch (LifecycleException e) { log.error("ContainerBase.setRealm: stop: ", e); } } // Start the new component if necessary if (realm != null) realm.setContainer(this); if (getState().isAvailable() && (realm != null) && (realm instanceof Lifecycle)) { try { ((Lifecycle) realm).start(); } catch (LifecycleException e) { log.error("ContainerBase.setRealm: start: ", e); } } // Report this property change to interested listeners support.firePropertyChange("realm", oldRealm, this.realm); } finally { l.unlock(); } } // ------------------------------------------------------ Container Methods /** * Add a new child Container to those associated with this Container, * if supported. Prior to adding this Container to the set of children, * the child's <code>setParent()</code> method must be called, with this * Container as an argument. This method may thrown an * <code>IllegalArgumentException</code> if this Container chooses not * to be attached to the specified Container, in which case it is not added * * @param child New child Container to be added * * @exception IllegalArgumentException if this exception is thrown by * the <code>setParent()</code> method of the child Container * @exception IllegalArgumentException if the new child does not have * a name unique from that of existing children of this Container * @exception IllegalStateException if this Container does not support * child Containers */ @Override public void addChild(Container child) { if (Globals.IS_SECURITY_ENABLED) { PrivilegedAction<Void> dp = new PrivilegedAddChild(child); AccessController.doPrivileged(dp); } else { addChildInternal(child); } } private void addChildInternal(Container child) { if( log.isDebugEnabled() ) log.debug("Add child " + child + " " + this); synchronized(children) { if (children.get(child.getName()) != null) throw new IllegalArgumentException("addChild: Child name '" + child.getName() + "' is not unique"); child.setParent(this); // May throw IAE children.put(child.getName(), child); } // Start child // Don't do this inside sync block - start can be a slow process and // locking the children object can cause problems elsewhere if ((getState().isAvailable() || LifecycleState.STARTING_PREP.equals(getState())) && startChildren) { try { child.start(); } catch (LifecycleException e) { log.error("ContainerBase.addChild: start: ", e); throw new IllegalStateException ("ContainerBase.addChild: start: " + e); } } fireContainerEvent(ADD_CHILD_EVENT, child); } /** * Add a container event listener to this component. * * @param listener The listener to add */ @Override public void addContainerListener(ContainerListener listener) { listeners.add(listener); } /** * 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 child Container, associated with this Container, with * the specified name (if any); otherwise, return <code>null</code> * * @param name Name of the child Container to be retrieved */ @Override public Container findChild(String name) { if (name == null) return (null); synchronized (children) { return children.get(name); } } /** * Return the set of children Containers associated with this Container. * If this Container has no children, a zero-length array is returned. */ @Override public Container[] findChildren() { synchronized (children) { Container results[] = new Container[children.size()]; return children.values().toArray(results); } } /** * Return the set of container listeners associated with this Container. * If this Container has no registered container listeners, a zero-length * array is returned. */ @Override public ContainerListener[] findContainerListeners() { ContainerListener[] results = new ContainerListener[0]; return listeners.toArray(results); } /** * Remove an existing child Container from association with this parent * Container. * * @param child Existing child Container to be removed */ @Override public void removeChild(Container child) { if (child == null) { return; } synchronized(children) { if (children.get(child.getName()) == null) return; children.remove(child.getName()); } try { if (child.getState().isAvailable()) { child.stop(); } } catch (LifecycleException e) { log.error("ContainerBase.removeChild: stop: ", e); } fireContainerEvent(REMOVE_CHILD_EVENT, child); try { // child.destroy() may have already been called which would have // triggered this call. If that is the case, no need to destroy the // child again. if (!LifecycleState.DESTROYING.equals(child.getState())) { child.destroy(); } } catch (LifecycleException e) { log.error("ContainerBase.removeChild: destroy: ", e); } } /** * Remove a container event listener from this component. * * @param listener The listener to remove */ @Override public void removeContainerListener(ContainerListener listener) { listeners.remove(listener); } /** * 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 { BlockingQueue<Runnable> startStopQueue = new LinkedBlockingQueue<>(); startStopExecutor = new ThreadPoolExecutor( getStartStopThreadsInternal(), getStartStopThreadsInternal(), 10, TimeUnit.SECONDS, startStopQueue, new StartStopThreadFactory(getName() + "-startStop-")); startStopExecutor.allowCoreThreadTimeOut(true); super.initInternal(); } /** * 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 { // Start our subordinate components, if any 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(); // Start our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StartChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStartFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStartFailed")); } // Start the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) ((Lifecycle) pipeline).start(); setState(LifecycleState.STARTING); // Start our thread threadStart(); } /** * 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 { // Stop our thread threadStop(); setState(LifecycleState.STOPPING); // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle && ((Lifecycle) pipeline).getState().isAvailable()) { ((Lifecycle) pipeline).stop(); } // Stop our child containers, if any Container children[] = findChildren(); List<Future<Void>> results = new ArrayList<>(); for (int i = 0; i < children.length; i++) { results.add(startStopExecutor.submit(new StopChild(children[i]))); } boolean fail = false; for (Future<Void> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString("containerBase.threadedStopFailed"), e); fail = true; } } if (fail) { throw new LifecycleException( sm.getString("containerBase.threadedStopFailed")); } // Stop our subordinate components, if any Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).stop(); } Cluster cluster = getClusterInternal(); if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).stop(); } } @Override protected void destroyInternal() throws LifecycleException { Realm realm = getRealmInternal(); if ((realm != null) && (realm instanceof Lifecycle)) { ((Lifecycle) realm).destroy(); } Cluster cluster = getClusterInternal(); if ((cluster != null) && (cluster instanceof Lifecycle)) { ((Lifecycle) cluster).destroy(); } // Stop the Valves in our pipeline (including the basic), if any if (pipeline instanceof Lifecycle) { ((Lifecycle) pipeline).destroy(); } // Remove children now this container is being destroyed for (Container child : findChildren()) { removeChild(child); } // Required if the child is destroyed directly. if (parent != null) { parent.removeChild(this); } // If init fails, this may be null if (startStopExecutor != null) { startStopExecutor.shutdownNow(); } super.destroyInternal(); } /** * Check this container for an access log and if none is found, look to the * parent. If there is no parent and still none is found, use the NoOp * access log. */ @Override public void logAccess(Request request, Response response, long time, boolean useDefault) { boolean logged = false; if (getAccessLog() != null) { getAccessLog().log(request, response, time); logged = true; } if (getParent() != null) { // No need to use default logger once request/response has been logged // once getParent().logAccess(request, response, time, (useDefault && !logged)); } } @Override public AccessLog getAccessLog() { if (accessLogScanComplete) { return accessLog; } AccessLogAdapter adapter = null; Valve valves[] = getPipeline().getValves(); for (Valve valve : valves) { if (valve instanceof AccessLog) { if (adapter == null) { adapter = new AccessLogAdapter((AccessLog) valve); } else { adapter.add((AccessLog) valve); } } } if (adapter != null) { accessLog = adapter; } accessLogScanComplete = true; return accessLog; } // ------------------------------------------------------- Pipeline Methods /** * Convenience method, intended for use by the digester to simplify the * process of adding Valves to containers. See * {@link Pipeline#addValve(Valve)} for full details. Components other than * the digester should use {@link #getPipeline()}.{@link #addValve(Valve)} in case a * future implementation provides an alternative method for the digester to * use. * * @param valve Valve to be added * * @exception IllegalArgumentException if this Container refused to * accept the specified Valve * @exception IllegalArgumentException if the specified Valve refuses to be * associated with this Container * @exception IllegalStateException if the specified Valve is already * associated with a different Container */ public synchronized void addValve(Valve valve) { pipeline.addValve(valve); } /** * 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 (!getState().isAvailable()) return; Cluster cluster = getClusterInternal(); if (cluster != null) { try { cluster.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.cluster", cluster), e); } } Realm realm = getRealmInternal(); if (realm != null) { try { realm.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.realm", realm), e); } } Valve current = pipeline.getFirst(); while (current != null) { try { current.backgroundProcess(); } catch (Exception e) { log.warn(sm.getString("containerBase.backgroundProcess.valve", current), e); } current = current.getNext(); } fireLifecycleEvent(Lifecycle.PERIODIC_EVENT, null); } @Override public File getCatalinaBase() { if (parent == null) { return null; } return parent.getCatalinaBase(); } // ------------------------------------------------------ Protected Methods /** * Notify all container event listeners that a particular event has * occurred for this Container. The default implementation performs * this notification synchronously using the calling thread. * * @param type Event type * @param data Event data */ @Override public void fireContainerEvent(String type, Object data) { if (listeners.size() < 1) return; ContainerEvent event = new ContainerEvent(this, type, data); // Note for each uses an iterator internally so this is safe for (ContainerListener listener : listeners) { listener.containerEvent(event); } } /** * Return the abbreviated name of this container for logging messages */ protected String logName() { if (logName != null) { return logName; } String loggerName = null; Container current = this; while (current != null) { String name = current.getName(); if ((name == null) || (name.equals(""))) { name = "/"; } else if (name.startsWith("##")) { name = "/" + name; } loggerName = "[" + name + "]" + ((loggerName != null) ? ("." + loggerName) : ""); current = current.getParent(); } logName = ContainerBase.class.getName() + "." + loggerName; return logName; } // -------------------- JMX and Registration -------------------- @Override protected String getDomainInternal() { Container p = this.getParent(); if (p == null) { return null; } else { return p.getDomain(); } } @Override public String getMBeanKeyProperties() { Container c = this; StringBuilder keyProperties = new StringBuilder(); int containerCount = 0; // Work up container hierarchy, add a component to the name for // each container while (!(c instanceof Engine)) { if (c instanceof Wrapper) { keyProperties.insert(0, ",servlet="); keyProperties.insert(9, c.getName()); } else if (c instanceof Context) { keyProperties.insert(0, ",context="); ContextName cn = new ContextName(c.getName()); keyProperties.insert(9,cn.getDisplayName()); } else if (c instanceof Host) { keyProperties.insert(0, ",host="); keyProperties.insert(6, c.getName()); } else if (c == null) { // May happen in unit testing and/or some embedding scenarios keyProperties.append(",container"); keyProperties.append(containerCount++); keyProperties.append("=null"); break; } else { // Should never happen... keyProperties.append(",container"); keyProperties.append(containerCount++); keyProperties.append('='); keyProperties.append(c.getName()); } c = c.getParent(); } return keyProperties.toString(); } public ObjectName[] getChildren() { ObjectName result[]=new ObjectName[children.size()]; Iterator<Container> it=children.values().iterator(); int i=0; while( it.hasNext() ) { Object next=it.next(); if( next instanceof ContainerBase ) { result[i++]=((ContainerBase)next).getObjectName(); } } return result; } // -------------------- Background Thread -------------------- /** * Start the background thread that will periodically check for * session timeouts. */ protected void threadStart() { if (thread != null) return; if (backgroundProcessorDelay <= 0) return; threadDone = false; String threadName = "ContainerBackgroundProcessor[" + toString() + "]"; thread = new Thread(new ContainerBackgroundProcessor(), threadName); thread.setDaemon(true); thread.start(); } /** * Stop the background thread that is periodically checking for * session timeouts. */ protected void threadStop() { if (thread == null) return; threadDone = true; thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { // Ignore } thread = null; } // -------------------------------------- ContainerExecuteDelay Inner Class /** * Private thread class to invoke the backgroundProcess method * of this container and its children after a fixed delay. */ protected class ContainerBackgroundProcessor implements Runnable { @Override public void run() { while (!threadDone) { try { Thread.sleep(backgroundProcessorDelay * 1000L); } catch (InterruptedException e) { // Ignore } if (!threadDone) { processChildren(ContainerBase.this); } } } protected void processChildren(Container container) { ClassLoader originalClassLoader = null; try { if (container instanceof Context) { Loader loader = ((Context) container).getLoader(); // Loader will be null for FailedContext instances if (loader == null) { return; } // Ensure background processing for Contexts and Wrappers // is performed under the web app's class loader originalClassLoader = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader( loader.getClassLoader()); } container.backgroundProcess(); Container[] children = container.findChildren(); for (int i = 0; i < children.length; i++) { if (children[i].getBackgroundProcessorDelay() <= 0) { processChildren(children[i]); } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error("Exception invoking periodic operation: ", t); } finally { if (originalClassLoader != null) { Thread.currentThread().setContextClassLoader( originalClassLoader); } } } } // ----------------------------- Inner classes used with start/stop Executor private static class StartChild implements Callable<Void> { private Container child; public StartChild(Container child) { this.child = child; } @Override public Void call() throws LifecycleException { child.start(); return null; } } private static class StopChild implements Callable<Void> { private Container child; public StopChild(Container child) { this.child = child; } @Override public Void call() throws LifecycleException { if (child.getState().isAvailable()) { child.stop(); } return null; } } private static class StartStopThreadFactory implements ThreadFactory { private final ThreadGroup group; private final AtomicInteger threadNumber = new AtomicInteger(1); private final String namePrefix; public StartStopThreadFactory(String namePrefix) { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); this.namePrefix = namePrefix; } @Override public Thread newThread(Runnable r) { Thread thread = new Thread(group, r, namePrefix + threadNumber.getAndIncrement()); thread.setDaemon(true); return thread; } } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/ha/deploy/FarmWarDeployer.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.deploy; import java.io.File; import java.io.IOException; import java.util.HashMap; import javax.management.MBeanServer; import javax.management.ObjectName; 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.ha.ClusterDeployer; import org.apache.catalina.ha.ClusterListener; import org.apache.catalina.ha.ClusterMessage; import org.apache.catalina.tribes.Member; import org.apache.catalina.util.ContextName; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.modeler.Registry; import org.apache.tomcat.util.res.StringManager; /** * <p> * A farm war deployer is a class that is able to deploy/undeploy web * applications in WAR from within the cluster. * </p> * Any host can act as the admin, and will have three directories * <ul> * <li>deployDir - the directory where we watch for changes</li> * <li>applicationDir - the directory where we install applications</li> * <li>tempDir - a temporaryDirectory to store binary data when downloading a * war from the cluster</li> * </ul> * Currently we only support deployment of WAR files since they are easier to * send across the wire. * * @author Filip Hanik * @author Peter Rossbach * @version $Revision$ */ public class FarmWarDeployer extends ClusterListener implements ClusterDeployer, FileChangeListener { /*--Static Variables----------------------------------------*/ private static final Log log = LogFactory.getLog(FarmWarDeployer.class); private static final StringManager sm = StringManager.getManager(Constants.Package); /*--Instance Variables--------------------------------------*/ protected boolean started = false; protected final HashMap<String, FileMessageFactory> fileFactories = new HashMap<>(); /** * Deployment directory. */ protected String deployDir; private File deployDirFile = null; /** * Temporary directory. */ protected String tempDir; private File tempDirFile = null; /** * Watch directory. */ protected String watchDir; private File watchDirFile = null; protected boolean watchEnabled = false; protected WarWatcher watcher = null; /** * Iteration count for background processing. */ private int count = 0; /** * Frequency of the Farm watchDir check. Cluster wide deployment 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 processDeployFrequency = 2; /** * Path where context descriptors should be deployed. */ protected File configBase = null; /** * The associated host. */ protected Host host = null; /** * MBean server. */ protected MBeanServer mBeanServer = null; /** * The associated deployer ObjectName. */ protected ObjectName oname = null; /** * The maximum valid time(in seconds) for FileMessageFactory. */ protected int maxValidTime = 5 * 60; /*--Constructor---------------------------------------------*/ public FarmWarDeployer() { } /*--Logic---------------------------------------------------*/ @Override public void start() throws Exception { if (started) return; Container hcontainer = getCluster().getContainer(); if(!(hcontainer instanceof Host)) { log.error(sm.getString("farmWarDeployer.hostOnly")); return ; } host = (Host) hcontainer; // Check to correct engine and host setup Container econtainer = host.getParent(); if(!(econtainer instanceof Engine)) { log.error(sm.getString("farmWarDeployer.hostParentEngine", host.getName())); return ; } Engine engine = (Engine) econtainer; String hostname = null; hostname = host.getName(); try { oname = new ObjectName(engine.getName() + ":type=Deployer,host=" + hostname); } catch (Exception e) { log.error(sm.getString("farmWarDeployer.mbeanNameFail", engine.getName(), hostname),e); return; } if (watchEnabled) { watcher = new WarWatcher(this, getWatchDirFile()); if (log.isInfoEnabled()) { log.info(sm.getString( "farmWarDeployer.watchDir", getWatchDir())); } } configBase = host.getConfigBaseFile(); // Retrieve the MBean server mBeanServer = Registry.getRegistry(null, null).getMBeanServer(); started = true; count = 0; getCluster().addClusterListener(this); if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.started")); } /* * stop cluster wide deployments * * @see org.apache.catalina.ha.ClusterDeployer#stop() */ @Override public void stop() throws LifecycleException { started = false; getCluster().removeClusterListener(this); count = 0; if (watcher != null) { watcher.clear(); watcher = null; } if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.stopped")); } /** * Callback from the cluster, when a message is received, The cluster will * broadcast it invoking the messageReceived on the receiver. * * @param msg * ClusterMessage - the message received from the cluster */ @Override public void messageReceived(ClusterMessage msg) { try { if (msg instanceof FileMessage) { FileMessage fmsg = (FileMessage) msg; if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.msgRxDeploy", fmsg.getContextName(), fmsg.getFileName())); FileMessageFactory factory = getFactory(fmsg); // TODO correct second try after app is in service! if (factory.writeMessage(fmsg)) { //last message received war file is completed String name = factory.getFile().getName(); if (!name.endsWith(".war")) name = name + ".war"; File deployable = new File(getDeployDirFile(), name); try { String contextName = fmsg.getContextName(); if (!isServiced(contextName)) { addServiced(contextName); try { remove(contextName); if (!factory.getFile().renameTo(deployable)) { log.error(sm.getString( "farmWarDeployer.renameFail", factory.getFile(), deployable)); } check(contextName); } finally { removeServiced(contextName); } if (log.isDebugEnabled()) log.debug(sm.getString( "farmWarDeployer.deployEnd", contextName)); } else log.error(sm.getString( "farmWarDeployer.servicingDeploy", contextName, name)); } catch (Exception ex) { log.error(ex); } finally { removeFactory(fmsg); } } } else if (msg instanceof UndeployMessage) { try { UndeployMessage umsg = (UndeployMessage) msg; String contextName = umsg.getContextName(); if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.msgRxUndeploy", contextName)); if (!isServiced(contextName)) { addServiced(contextName); try { remove(contextName); } finally { removeServiced(contextName); } if (log.isDebugEnabled()) log.debug(sm.getString( "farmWarDeployer.undeployEnd", contextName)); } else log.error(sm.getString( "farmWarDeployer.servicingUneploy", contextName)); } catch (Exception ex) { log.error(ex); } } } catch (java.io.IOException x) { log.error(sm.getString("farmWarDeployer.msgIoe"), x); } } /** * create factory for all transported war files * * @param msg * @return Factory for all app message (war files) * @throws java.io.FileNotFoundException * @throws java.io.IOException */ public synchronized FileMessageFactory getFactory(FileMessage msg) throws java.io.FileNotFoundException, java.io.IOException { File writeToFile = new File(getTempDirFile(), msg.getFileName()); FileMessageFactory factory = fileFactories.get(msg.getFileName()); if (factory == null) { factory = FileMessageFactory.getInstance(writeToFile, true); factory.setMaxValidTime(maxValidTime); fileFactories.put(msg.getFileName(), factory); } return factory; } /** * Remove file (war) from messages) * * @param msg */ public void removeFactory(FileMessage msg) { fileFactories.remove(msg.getFileName()); } /** * Before the cluster invokes messageReceived the cluster will ask the * receiver to accept or decline the message, In the future, when messages * get big, the accept method will only take a message header * * @param msg * ClusterMessage * @return boolean - returns true to indicate that messageReceived should be * invoked. If false is returned, the messageReceived method will * not be invoked. */ @Override public boolean accept(ClusterMessage msg) { return (msg instanceof FileMessage) || (msg instanceof UndeployMessage); } /** * Install a new web application, whose web application archive is at the * specified URL, into this container and all the other members of the * cluster with the specified context name. * <p> * If this application is successfully installed locally, a ContainerEvent * of type <code>INSTALL_EVENT</code> will be sent to all registered * listeners, with the newly created <code>Context</code> as an argument. * * @param contextName * The context name to which this application should be installed * (must be unique) * @param webapp * A WAR file or unpacked directory structure containing the web * application to be installed * * @exception IllegalArgumentException * if the specified context name is malformed * @exception IllegalStateException * if the specified context name is already deployed * @exception IOException * if an input/output error was encountered during * installation */ @Override public void install(String contextName, File webapp) throws IOException { Member[] members = getCluster().getMembers(); if (members.length == 0) return; Member localMember = getCluster().getLocalMember(); FileMessageFactory factory = FileMessageFactory.getInstance(webapp, false); FileMessage msg = new FileMessage(localMember, webapp.getName(), contextName); if(log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.sendStart", contextName, webapp)); msg = factory.readMessage(msg); while (msg != null) { for (int i = 0; i < members.length; i++) { if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.sendFragment", contextName, webapp, members[i])); getCluster().send(msg, members[i]); } msg = factory.readMessage(msg); } if(log.isDebugEnabled()) log.debug(sm.getString( "farmWarDeployer.sendEnd", contextName, webapp)); } /** * Remove an existing web application, attached to the specified context * name. If this application is successfully removed, a ContainerEvent of * type <code>REMOVE_EVENT</code> will be sent to all registered * listeners, with the removed <code>Context</code> as an argument. * Deletes the web application war file and/or directory if they exist in * the Host's appBase. * * @param contextName * The context name of the application to be removed * @param undeploy * boolean flag to remove web application from server * * @exception IllegalArgumentException * if the specified context name is malformed * @exception IllegalArgumentException * if the specified context name does not identify a * currently installed web application * @exception IOException * if an input/output error occurs during removal */ @Override public void remove(String contextName, boolean undeploy) throws IOException { if (getCluster().getMembers().length > 0) { if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.removeStart", contextName)); Member localMember = getCluster().getLocalMember(); UndeployMessage msg = new UndeployMessage(localMember, System .currentTimeMillis(), "Undeploy:" + contextName + ":" + System.currentTimeMillis(), contextName); if (log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.removeTxMsg", contextName)); cluster.send(msg); } // remove locally if (undeploy) { try { if (!isServiced(contextName)) { addServiced(contextName); try { remove(contextName); } finally { removeServiced(contextName); } } else log.error(sm.getString("farmWarDeployer.removeFailRemote", contextName)); } catch (Exception ex) { log.error(sm.getString("farmWarDeployer.removeFailLocal", contextName), ex); } } } /* * Modification from watchDir war detected! * * @see org.apache.catalina.ha.deploy.FileChangeListener#fileModified(File) */ @Override public void fileModified(File newWar) { try { File deployWar = new File(getDeployDirFile(), newWar.getName()); ContextName cn = new ContextName(deployWar.getName()); if (deployWar.exists() && deployWar.lastModified() > newWar.lastModified()) { if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.alreadyDeployed", cn.getName())); return; } if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.modInstall", cn.getName(), deployWar.getAbsolutePath())); // install local if (!isServiced(cn.getName())) { addServiced(cn.getName()); try { copy(newWar, deployWar); check(cn.getName()); } finally { removeServiced(cn.getName()); } } else { log.error(sm.getString("farmWarDeployer.servicingDeploy", cn.getName(), deployWar.getName())); } install(cn.getName(), deployWar); } catch (Exception x) { log.error(sm.getString("farmWarDeployer.modInstallFail"), x); } } /* * War remove from watchDir * * @see org.apache.catalina.ha.deploy.FileChangeListener#fileRemoved(File) */ @Override public void fileRemoved(File removeWar) { try { ContextName cn = new ContextName(removeWar.getName()); if (log.isInfoEnabled()) log.info(sm.getString("farmWarDeployer.removeLocal", cn.getName())); remove(cn.getName(), true); } catch (Exception x) { log.error(sm.getString("farmWarDeployer.removeLocalFail"), x); } } /** * Invoke the remove method on the deployer. */ protected void remove(String contextName) throws Exception { // TODO Handle remove also work dir content ! // Stop the context first to be nicer Context context = (Context) host.findChild(contextName); if (context != null) { if(log.isDebugEnabled()) log.debug(sm.getString("farmWarDeployer.undeployLocal", contextName)); context.stop(); String baseName = context.getBaseName(); File war = new File(host.getAppBaseFile(), baseName + ".war"); File dir = new File(host.getAppBaseFile(), baseName); File xml = new File(configBase, baseName + ".xml"); if (war.exists()) { if (!war.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", war)); } } else if (dir.exists()) { undeployDir(dir); } else { if (!xml.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", xml)); } } // Perform new deployment and remove internal HostConfig state check(contextName); } } /** * Delete the specified directory, including all of its contents and * subdirectories recursively. * * @param dir * File object representing the directory to be deleted */ protected void undeployDir(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()) { undeployDir(file); } else { if (!file.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", file)); } } } if (!dir.delete()) { log.error(sm.getString("farmWarDeployer.deleteFail", dir)); } } /* * Call watcher to check for deploy changes * * @see org.apache.catalina.ha.ClusterDeployer#backgroundProcess() */ @Override public void backgroundProcess() { if (started) { if (watchEnabled) { count = (count + 1) % processDeployFrequency; if (count == 0) { watcher.check(); } } removeInvalidFileFactories(); } } /*--Deployer Operations ------------------------------------*/ /** * Invoke the check method on the deployer. */ protected void check(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "check", params, signature); } /** * Invoke the check method on the deployer. */ protected boolean isServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; Boolean result = (Boolean) mBeanServer.invoke(oname, "isServiced", params, signature); return result.booleanValue(); } /** * Invoke the check method on the deployer. */ protected void addServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "addServiced", params, signature); } /** * Invoke the check method on the deployer. */ protected void removeServiced(String name) throws Exception { String[] params = { name }; String[] signature = { "java.lang.String" }; mBeanServer.invoke(oname, "removeServiced", params, signature); } /*--Instance Getters/Setters--------------------------------*/ @Override public boolean equals(Object listener) { return super.equals(listener); } @Override public int hashCode() { return super.hashCode(); } public String getDeployDir() { return deployDir; } public File getDeployDirFile() { if (deployDirFile != null) return deployDirFile; File dir = getAbsolutePath(getDeployDir()); this.deployDirFile = dir; return dir; } public void setDeployDir(String deployDir) { this.deployDir = deployDir; } public String getTempDir() { return tempDir; } public File getTempDirFile() { if (tempDirFile != null) return tempDirFile; File dir = getAbsolutePath(getTempDir()); this.tempDirFile = dir; return dir; } public void setTempDir(String tempDir) { this.tempDir = tempDir; } public String getWatchDir() { return watchDir; } public File getWatchDirFile() { if (watchDirFile != null) return watchDirFile; File dir = getAbsolutePath(getWatchDir()); this.watchDirFile = dir; return dir; } public void setWatchDir(String watchDir) { this.watchDir = watchDir; } public boolean isWatchEnabled() { return watchEnabled; } public boolean getWatchEnabled() { return watchEnabled; } public void setWatchEnabled(boolean watchEnabled) { this.watchEnabled = watchEnabled; } /** * Return the frequency of watcher checks. */ public int getProcessDeployFrequency() { return (this.processDeployFrequency); } /** * Set the watcher checks frequency. * * @param processExpiresFrequency * the new manager checks frequency */ public void setProcessDeployFrequency(int processExpiresFrequency) { if (processExpiresFrequency <= 0) { return; } this.processDeployFrequency = processExpiresFrequency; } public int getMaxValidTime() { return maxValidTime; } public void setMaxValidTime(int maxValidTime) { this.maxValidTime = maxValidTime; } /** * Copy a file to the specified temp directory. * @param from copy from temp * @param to to host appBase directory * @return true, copy successful */ protected boolean copy(File from, File to) { try { if (!to.exists()) { if (!to.createNewFile()) { log.error(sm.getString("fileNewFail", to)); return false; } } java.io.FileInputStream is = new java.io.FileInputStream(from); java.io.FileOutputStream os = new java.io.FileOutputStream(to, false); byte[] buf = new byte[4096]; while (true) { int len = is.read(buf); if (len < 0) break; os.write(buf, 0, len); } is.close(); os.close(); } catch (IOException e) { log.error(sm.getString("farmWarDeployer.fileCopyFail", from, to), e); return false; } return true; } protected void removeInvalidFileFactories() { String[] fileNames = fileFactories.keySet().toArray(new String[0]); for (String fileName : fileNames) { FileMessageFactory factory = fileFactories.get(fileName); if (!factory.isValid()) { fileFactories.remove(fileName); } } } private File getAbsolutePath(String path) { File dir = new File(path); if (!dir.isAbsolute()) { dir = new File(getCluster().getContainer().getCatalinaBase(), dir.getPath()); } try { dir = dir.getCanonicalFile(); } catch (IOException e) {// ignore } return dir; } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
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.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.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 = StringManager.getManager( Constants.Package, request.getLocales()); // 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 = StringManager.getManager( Constants.Package, request.getLocales()); // 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 = warPart.getSubmittedFileName(); 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; } /** * 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 (manager != 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-2014, 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" + "</td>\n" + "</tr>\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>"; }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/mbeans/MBeanUtils.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.catalina.mbeans; import java.util.Set; import javax.management.DynamicMBean; import javax.management.MBeanException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Group; import org.apache.catalina.Loader; import org.apache.catalina.Role; import org.apache.catalina.Server; import org.apache.catalina.User; import org.apache.catalina.UserDatabase; import org.apache.catalina.util.ContextName; import org.apache.tomcat.util.descriptor.web.ContextEnvironment; import org.apache.tomcat.util.descriptor.web.ContextResource; import org.apache.tomcat.util.descriptor.web.ContextResourceLink; import org.apache.tomcat.util.modeler.ManagedBean; import org.apache.tomcat.util.modeler.Registry; /** * Public utility methods in support of the server side MBeans implementation. * * @author Craig R. McClanahan * @author Amy Roh * @version $Id$ */ public class MBeanUtils { // ------------------------------------------------------- Static Variables /** * The set of exceptions to the normal rules used by * <code>createManagedBean()</code>. The first element of each pair * is a class name, and the second element is the managed bean name. */ private static final String exceptions[][] = { { "org.apache.catalina.users.MemoryGroup", "Group" }, { "org.apache.catalina.users.MemoryRole", "Role" }, { "org.apache.catalina.users.MemoryUser", "User" }, }; /** * The configuration information registry for our managed beans. */ private static Registry registry = createRegistry(); /** * The <code>MBeanServer</code> for this application. */ private static MBeanServer mserver = createServer(); // --------------------------------------------------------- Static Methods /** * Create and return the name of the <code>ManagedBean</code> that * corresponds to this Catalina component. * * @param component The component for which to create a name */ static String createManagedName(Object component) { // Deal with exceptions to the standard rule String className = component.getClass().getName(); for (int i = 0; i < exceptions.length; i++) { if (className.equals(exceptions[i][0])) { return (exceptions[i][1]); } } // Perform the standard transformation int period = className.lastIndexOf('.'); if (period >= 0) className = className.substring(period + 1); return (className); } /** * Create, register, and return an MBean for this * <code>ContextEnvironment</code> object. * * @param environment The ContextEnvironment to be managed * * @exception Exception if an MBean cannot be created or registered */ public static DynamicMBean createMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(environment); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create, register, and return an MBean for this * <code>ContextResource</code> object. * * @param resource The ContextResource to be managed * * @exception Exception if an MBean cannot be created or registered */ public static DynamicMBean createMBean(ContextResource resource) throws Exception { String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resource); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create, register, and return an MBean for this * <code>ContextResourceLink</code> object. * * @param resourceLink The ContextResourceLink to be managed * * @exception Exception if an MBean cannot be created or registered */ public static DynamicMBean createMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(resourceLink); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create, register, and return an MBean for this * <code>Group</code> object. * * @param group The Group to be managed * * @exception Exception if an MBean cannot be created or registered */ static DynamicMBean createMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(group); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create, register, and return an MBean for this * <code>Role</code> object. * * @param role The Role to be managed * * @exception Exception if an MBean cannot be created or registered */ static DynamicMBean createMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(role); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create, register, and return an MBean for this * <code>User</code> object. * * @param user The User to be managed * * @exception Exception if an MBean cannot be created or registered */ static DynamicMBean createMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(user); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create, register, and return an MBean for this * <code>UserDatabase</code> object. * * @param userDatabase The UserDatabase to be managed * * @exception Exception if an MBean cannot be created or registered */ static DynamicMBean createMBean(UserDatabase userDatabase) throws Exception { String mname = createManagedName(userDatabase); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { Exception e = new Exception("ManagedBean is not found with "+mname); throw new MBeanException(e); } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); DynamicMBean mbean = managed.createMBean(userDatabase); ObjectName oname = createObjectName(domain, userDatabase); if( mserver.isRegistered( oname )) { mserver.unregisterMBean(oname); } mserver.registerMBean(mbean, oname); return (mbean); } /** * Create an <code>ObjectName</code> for this * <code>Service</code> object. * * @param domain Domain in which this name is to be created * @param environment The ContextEnvironment to be named * * @exception MalformedObjectNameException if a name cannot be created */ public static ObjectName createObjectName(String domain, ContextEnvironment environment) throws MalformedObjectNameException { ObjectName name = null; Object container = environment.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName(domain + ":type=Environment" + ",resourcetype=Global,name=" + environment.getName()); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=Environment" + ",resourcetype=Context,host=" + host.getName() + ",context=" + cn.getDisplayName() + ",name=" + environment.getName()); } return (name); } /** * Create an <code>ObjectName</code> for this * <code>ContextResource</code> object. * * @param domain Domain in which this name is to be created * @param resource The ContextResource to be named * * @exception MalformedObjectNameException if a name cannot be created */ public static ObjectName createObjectName(String domain, ContextResource resource) throws MalformedObjectNameException { ObjectName name = null; String quotedResourceName = ObjectName.quote(resource.getName()); Object container = resource.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName(domain + ":type=Resource" + ",resourcetype=Global,class=" + resource.getType() + ",name=" + quotedResourceName); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=Resource" + ",resourcetype=Context,host=" + host.getName() + ",context=" + cn.getDisplayName() + ",class=" + resource.getType() + ",name=" + quotedResourceName); } return (name); } /** * Create an <code>ObjectName</code> for this * <code>ContextResourceLink</code> object. * * @param domain Domain in which this name is to be created * @param resourceLink The ContextResourceLink to be named * * @exception MalformedObjectNameException if a name cannot be created */ public static ObjectName createObjectName(String domain, ContextResourceLink resourceLink) throws MalformedObjectNameException { ObjectName name = null; String quotedResourceLinkName = ObjectName.quote(resourceLink.getName()); Object container = resourceLink.getNamingResources().getContainer(); if (container instanceof Server) { name = new ObjectName(domain + ":type=ResourceLink" + ",resourcetype=Global" + ",name=" + quotedResourceLinkName); } else if (container instanceof Context) { Context context = ((Context)container); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=ResourceLink" + ",resourcetype=Context,host=" + host.getName() + ",context=" + cn.getDisplayName() + ",name=" + quotedResourceLinkName); } return (name); } /** * Create an <code>ObjectName</code> for this * <code>Group</code> object. * * @param domain Domain in which this name is to be created * @param group The Group to be named * * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, Group group) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=Group,groupname=" + ObjectName.quote(group.getGroupname()) + ",database=" + group.getUserDatabase().getId()); return (name); } /** * Create an <code>ObjectName</code> for this * <code>Loader</code> object. * * @param domain Domain in which this name is to be created * @param loader The Loader to be named * * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, Loader loader) throws MalformedObjectNameException { ObjectName name = null; Context context = loader.getContext(); ContextName cn = new ContextName(context.getName()); Container host = context.getParent(); name = new ObjectName(domain + ":type=Loader,host=" + host.getName() + ",context=" + cn.getDisplayName()); return name; } /** * Create an <code>ObjectName</code> for this * <code>Role</code> object. * * @param domain Domain in which this name is to be created * @param role The Role to be named * * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, Role role) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=Role,rolename=" + role.getRolename() + ",database=" + role.getUserDatabase().getId()); return (name); } /** * Create an <code>ObjectName</code> for this * <code>User</code> object. * * @param domain Domain in which this name is to be created * @param user The User to be named * * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, User user) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=User,username=" + ObjectName.quote(user.getUsername()) + ",database=" + user.getUserDatabase().getId()); return (name); } /** * Create an <code>ObjectName</code> for this * <code>UserDatabase</code> object. * * @param domain Domain in which this name is to be created * @param userDatabase The UserDatabase to be named * * @exception MalformedObjectNameException if a name cannot be created */ static ObjectName createObjectName(String domain, UserDatabase userDatabase) throws MalformedObjectNameException { ObjectName name = null; name = new ObjectName(domain + ":type=UserDatabase,database=" + userDatabase.getId()); return (name); } /** * Create and configure (if necessary) and return the registry of * managed object descriptions. */ public static synchronized Registry createRegistry() { if (registry == null) { registry = Registry.getRegistry(null, null); ClassLoader cl = MBeanUtils.class.getClassLoader(); registry.loadDescriptors("org.apache.catalina.mbeans", cl); registry.loadDescriptors("org.apache.catalina.authenticator", cl); registry.loadDescriptors("org.apache.catalina.core", cl); registry.loadDescriptors("org.apache.catalina", cl); registry.loadDescriptors("org.apache.catalina.deploy", cl); registry.loadDescriptors("org.apache.catalina.loader", cl); registry.loadDescriptors("org.apache.catalina.realm", cl); registry.loadDescriptors("org.apache.catalina.session", cl); registry.loadDescriptors("org.apache.catalina.startup", cl); registry.loadDescriptors("org.apache.catalina.users", cl); registry.loadDescriptors("org.apache.catalina.ha", cl); registry.loadDescriptors("org.apache.catalina.connector", cl); registry.loadDescriptors("org.apache.catalina.valves", cl); registry.loadDescriptors("org.apache.catalina.storeconfig", cl); registry.loadDescriptors("org.apache.tomcat.util.descriptor.web", cl); } return (registry); } /** * Create and configure (if necessary) and return the * <code>MBeanServer</code> with which we will be * registering our <code>DynamicMBean</code> implementations. */ public static synchronized MBeanServer createServer() { if (mserver == null) { mserver = Registry.getRegistry(null, null).getMBeanServer(); } return (mserver); } /** * Deregister the MBean for this * <code>ContextEnvironment</code> object. * * @param environment The ContextEnvironment to be managed * * @exception Exception if an MBean cannot be deregistered */ public static void destroyMBean(ContextEnvironment environment) throws Exception { String mname = createManagedName(environment); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, environment); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); } /** * Deregister the MBean for this * <code>ContextResource</code> object. * * @param resource The ContextResource to be managed * * @exception Exception if an MBean cannot be deregistered */ public static void destroyMBean(ContextResource resource) throws Exception { // If this is a user database resource need to destroy groups, roles, // users and UserDatabase mbean if ("org.apache.catalina.UserDatabase".equals(resource.getType())) { destroyMBeanUserDatabase(resource.getName()); } String mname = createManagedName(resource); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, resource); if( mserver.isRegistered(oname )) mserver.unregisterMBean(oname); } /** * Deregister the MBean for this * <code>ContextResourceLink</code> object. * * @param resourceLink The ContextResourceLink to be managed * * @exception Exception if an MBean cannot be deregistered */ public static void destroyMBean(ContextResourceLink resourceLink) throws Exception { String mname = createManagedName(resourceLink); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, resourceLink); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); } /** * Deregister the MBean for this * <code>Group</code> object. * * @param group The Group to be managed * * @exception Exception if an MBean cannot be deregistered */ static void destroyMBean(Group group) throws Exception { String mname = createManagedName(group); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, group); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); } /** * Deregister the MBean for this * <code>Role</code> object. * * @param role The Role to be managed * * @exception Exception if an MBean cannot be deregistered */ static void destroyMBean(Role role) throws Exception { String mname = createManagedName(role); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, role); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); } /** * Deregister the MBean for this * <code>User</code> object. * * @param user The User to be managed * * @exception Exception if an MBean cannot be deregistered */ static void destroyMBean(User user) throws Exception { String mname = createManagedName(user); ManagedBean managed = registry.findManagedBean(mname); if (managed == null) { return; } String domain = managed.getDomain(); if (domain == null) domain = mserver.getDefaultDomain(); ObjectName oname = createObjectName(domain, user); if( mserver.isRegistered(oname) ) mserver.unregisterMBean(oname); } /** * Deregister the MBean for the * <code>UserDatabase</code> object with this name. * * @param userDatabase The UserDatabase to be managed * * @exception Exception if an MBean cannot be deregistered */ static void destroyMBeanUserDatabase(String userDatabase) throws Exception { ObjectName query = null; Set<ObjectName> results = null; // Groups query = new ObjectName( "Users:type=Group,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // Roles query = new ObjectName( "Users:type=Role,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // Users query = new ObjectName( "Users:type=User,database=" + userDatabase + ",*"); results = mserver.queryNames(query, null); for(ObjectName result : results) { mserver.unregisterMBean(result); } // The database itself ObjectName db = new ObjectName( "Users:type=UserDatabase,database=" + userDatabase); if( mserver.isRegistered(db) ) { mserver.unregisterMBean(db); } } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/startup/FailedContext.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.beans.PropertyChangeListener; import java.io.File; import java.net.URL; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.ServletContainerInitializer; import javax.servlet.ServletContext; import javax.servlet.ServletRegistration; import javax.servlet.ServletRequest; import javax.servlet.ServletSecurityElement; import javax.servlet.descriptor.JspConfigDescriptor; import org.apache.catalina.AccessLog; 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.Engine; import org.apache.catalina.Host; import org.apache.catalina.LifecycleException; 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.WebResourceRoot; import org.apache.catalina.Wrapper; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.deploy.NamingResourcesImpl; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.LifecycleMBeanBase; import org.apache.juli.logging.Log; import org.apache.tomcat.InstanceManager; import org.apache.tomcat.JarScanner; import org.apache.tomcat.util.descriptor.web.ApplicationListener; import org.apache.tomcat.util.descriptor.web.ApplicationParameter; import org.apache.tomcat.util.descriptor.web.ErrorPage; import org.apache.tomcat.util.descriptor.web.FilterDef; import org.apache.tomcat.util.descriptor.web.FilterMap; import org.apache.tomcat.util.descriptor.web.LoginConfig; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.apache.tomcat.util.res.StringManager; /** * An implementation of {@link Context} that is used as a place-holder for * deployed applications when their deployment fails and a Context instance * (usually {@link org.apache.catalina.core.StandardContext} but may be any * Context implementation) cannot be created. */ public class FailedContext extends LifecycleMBeanBase implements Context { protected static final StringManager sm = StringManager.getManager(Constants.Package); // --------------------- Methods that need to work even for a failed context private URL configFile; @Override public URL getConfigFile() { return configFile; } @Override public void setConfigFile(URL configFile) { this.configFile = configFile; } private String docBase; @Override public String getDocBase() { return docBase; } @Override public void setDocBase(String docBase) { this.docBase = docBase; } private String name = null; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } private Container parent; @Override public Container getParent() { return parent; } @Override public void setParent(Container parent) { this.parent = parent; } private String path = null; @Override public String getPath() { return path; } @Override public void setPath(String path) { this.path = path; } private String webappVersion = null; @Override public String getWebappVersion() { return webappVersion; } @Override public void setWebappVersion(String webappVersion) { this.webappVersion = webappVersion; } @Override protected String getDomainInternal() { Container p = getParent(); if (p == null) { return null; } else { return p.getDomain(); } } @Override public String getMBeanKeyProperties() { Container c = this; StringBuilder keyProperties = new StringBuilder(); int containerCount = 0; // Work up container hierarchy, add a component to the name for // each container while (!(c instanceof Engine)) { if (c instanceof Context) { keyProperties.append(",context="); ContextName cn = new ContextName(c.getName()); keyProperties.append(cn.getDisplayName()); } else if (c instanceof Host) { keyProperties.append(",host="); keyProperties.append(c.getName()); } else if (c == null) { // May happen in unit testing and/or some embedding scenarios keyProperties.append(",container"); keyProperties.append(containerCount++); keyProperties.append("=null"); break; } else { // Should never happen... keyProperties.append(",container"); keyProperties.append(containerCount++); keyProperties.append('='); keyProperties.append(c.getName()); } c = c.getParent(); } return keyProperties.toString(); } @Override protected String getObjectNameKeyProperties() { StringBuilder keyProperties = new StringBuilder("j2eeType=WebModule,name=//"); String hostname = getParent().getName(); if (hostname == null) { keyProperties.append("DEFAULT"); } else { keyProperties.append(hostname); } String contextName = getName(); if (!contextName.startsWith("/")) { keyProperties.append('/'); } keyProperties.append(contextName); keyProperties.append(",J2EEApplication=none,J2EEServer=none"); return keyProperties.toString(); } @Override protected void startInternal() throws LifecycleException { throw new LifecycleException( sm.getString("failedContext.start", getName())); } @Override protected void stopInternal() throws LifecycleException { // NO-OP // Allow stop to complete since it is used for clean-up } // Only need to read these @Override public void addWatchedResource(String name) { /* NO-OP */ } @Override public String[] findWatchedResources() { return new String[0]; } @Override public void removeWatchedResource(String name) { /* NO-OP */ } @Override public void addChild(Container child) { /* NO-OP */ } @Override public Container findChild(String name) { return null; } @Override public Container[] findChildren() { return new Container[0]; } @Override public void removeChild(Container child) { /* NO-OP */ } @Override public String toString() { return getName(); } // -------------------------------------------- All NO-OPs beyond this point @Override public Loader getLoader() { return null; } @Override public void setLoader(Loader loader) { /* NO-OP */ } @Override public Log getLogger() { return null; } @Override public Manager getManager() { return null; } @Override public void setManager(Manager manager) { /* NO-OP */ } @Override public Pipeline getPipeline() { return null; } @Override public Cluster getCluster() { return null; } @Override public void setCluster(Cluster cluster) { /* NO-OP */ } @Override public int getBackgroundProcessorDelay() { return -1; } @Override public void setBackgroundProcessorDelay(int delay) { /* NO-OP */ } @Override public ClassLoader getParentClassLoader() { return null; } @Override public void setParentClassLoader(ClassLoader parent) { /* NO-OP */ } @Override public Realm getRealm() { return null; } @Override public void setRealm(Realm realm) { /* NO-OP */ } @Override public WebResourceRoot getResources() { return null; } @Override public void setResources(WebResourceRoot resources) { /* NO-OP */ } @Override public void backgroundProcess() { /* NO-OP */ } @Override public void addContainerListener(ContainerListener listener) { /* NO-OP */ } @Override public ContainerListener[] findContainerListeners() { return null; } @Override public void removeContainerListener(ContainerListener listener) { /* NO-OP */ } @Override public void addPropertyChangeListener(PropertyChangeListener listener) { /* NO-OP */ } @Override public void removePropertyChangeListener(PropertyChangeListener listener) { /* NO-OP */ } @Override public void fireContainerEvent(String type, Object data) { /* NO-OP */ } @Override public void logAccess(Request request, Response response, long time, boolean useDefault) { /* NO-OP */ } @Override public AccessLog getAccessLog() { return null; } @Override public int getStartStopThreads() { return 0; } @Override public void setStartStopThreads(int startStopThreads) { /* NO-OP */ } @Override public boolean getAllowCasualMultipartParsing() { return false; } @Override public void setAllowCasualMultipartParsing( boolean allowCasualMultipartParsing) { /* NO-OP */ } @Override public Object[] getApplicationEventListeners() { return null; } @Override public void setApplicationEventListeners(Object[] listeners) { /* NO-OP */ } @Override public Object[] getApplicationLifecycleListeners() { return null; } @Override public void setApplicationLifecycleListeners(Object[] listeners) { /* NO-OP */ } @Override public String getCharset(Locale locale) { return null; } @Override public boolean getConfigured() { return false; } @Override public void setConfigured(boolean configured) { /* NO-OP */ } @Override public boolean getCookies() { return false; } @Override public void setCookies(boolean cookies) { /* NO-OP */ } @Override public String getSessionCookieName() { return null; } @Override public void setSessionCookieName(String sessionCookieName) { /* NO-OP */ } @Override public boolean getUseHttpOnly() { return false; } @Override public void setUseHttpOnly(boolean useHttpOnly) { /* NO-OP */ } @Override public String getSessionCookieDomain() { return null; } @Override public void setSessionCookieDomain(String sessionCookieDomain) { /* NO-OP */ } @Override public String getSessionCookiePath() { return null; } @Override public void setSessionCookiePath(String sessionCookiePath) { /* NO-OP */ } @Override public boolean getSessionCookiePathUsesTrailingSlash() { return false; } @Override public void setSessionCookiePathUsesTrailingSlash( boolean sessionCookiePathUsesTrailingSlash) { /* NO-OP */ } @Override public boolean getCrossContext() { return false; } @Override public void setCrossContext(boolean crossContext) { /* NO-OP */ } @Override public String getAltDDName() { return null; } @Override public void setAltDDName(String altDDName) { /* NO-OP */ } @Override public boolean getDenyUncoveredHttpMethods() { return false; } @Override public void setDenyUncoveredHttpMethods(boolean denyUncoveredHttpMethods) { // NO-OP } @Override public String getDisplayName() { return null; } @Override public void setDisplayName(String displayName) { /* NO-OP */ } @Override public boolean getDistributable() { return false; } @Override public void setDistributable(boolean distributable) { /* NO-OP */ } @Override public String getEncodedPath() { return null; } @Override public boolean getIgnoreAnnotations() { return false; } @Override public void setIgnoreAnnotations(boolean ignoreAnnotations) { /* NO-OP */ } @Override public LoginConfig getLoginConfig() { return null; } @Override public void setLoginConfig(LoginConfig config) { /* NO-OP */ } @Override public NamingResourcesImpl getNamingResources() { return null; } @Override public void setNamingResources(NamingResourcesImpl namingResources) { /* NO-OP */ } @Override public String getPublicId() { return null; } @Override public void setPublicId(String publicId) { /* NO-OP */ } @Override public boolean getReloadable() { return false; } @Override public void setReloadable(boolean reloadable) { /* NO-OP */ } @Override public boolean getOverride() { return false; } @Override public void setOverride(boolean override) { /* NO-OP */ } @Override public boolean getPrivileged() { return false; } @Override public void setPrivileged(boolean privileged) { /* NO-OP */ } @Override public ServletContext getServletContext() { return null; } @Override public int getSessionTimeout() { return 0; } @Override public void setSessionTimeout(int timeout) { /* NO-OP */ } @Override public boolean getSwallowAbortedUploads() { return false; } @Override public void setSwallowAbortedUploads(boolean swallowAbortedUploads) { /* NO-OP */ } @Override public boolean getSwallowOutput() { return false; } @Override public void setSwallowOutput(boolean swallowOutput) { /* NO-OP */ } @Override public String getWrapperClass() { return null; } @Override public void setWrapperClass(String wrapperClass) { /* NO-OP */ } @Override public boolean getXmlNamespaceAware() { return false; } @Override public void setXmlNamespaceAware(boolean xmlNamespaceAware) { /* NO-OP */ } @Override public boolean getXmlValidation() { return false; } @Override public void setXmlValidation(boolean xmlValidation) { /* NO-OP */ } @Override public boolean getXmlBlockExternal() { return true; } @Override public void setXmlBlockExternal(boolean xmlBlockExternal) { /* NO-OP */ } @Override public boolean getTldValidation() { return false; } @Override public void setTldValidation(boolean tldValidation){ /* NO-OP */ } @Override public JarScanner getJarScanner() { return null; } @Override public void setJarScanner(JarScanner jarScanner) { /* NO-OP */ } @Override public Authenticator getAuthenticator() { return null; } @Override public void setLogEffectiveWebXml(boolean logEffectiveWebXml) { /* NO-OP */ } @Override public boolean getLogEffectiveWebXml() { return false; } @Override public void addApplicationListener(ApplicationListener listener) { /* NO-OP */ } @Override public ApplicationListener[] findApplicationListeners() { return null; } @Override public void removeApplicationListener(String listener) { /* NO-OP */ } @Override public void addApplicationParameter(ApplicationParameter parameter) { /* NO-OP */ } @Override public ApplicationParameter[] findApplicationParameters() { return null; } @Override public void removeApplicationParameter(String name) { /* NO-OP */ } @Override public void addConstraint(SecurityConstraint constraint) { /* NO-OP */ } @Override public SecurityConstraint[] findConstraints() { return null; } @Override public void removeConstraint(SecurityConstraint constraint) { /* NO-OP */ } @Override public void addErrorPage(ErrorPage errorPage) { /* NO-OP */ } @Override public ErrorPage findErrorPage(int errorCode) { return null; } @Override public ErrorPage findErrorPage(String exceptionType) { return null; } @Override public ErrorPage[] findErrorPages() { return null; } @Override public void removeErrorPage(ErrorPage errorPage) { /* NO-OP */ } @Override public void addFilterDef(FilterDef filterDef) { /* NO-OP */ } @Override public FilterDef findFilterDef(String filterName) { return null; } @Override public FilterDef[] findFilterDefs() { return null; } @Override public void removeFilterDef(FilterDef filterDef) { /* NO-OP */ } @Override public void addFilterMap(FilterMap filterMap) { /* NO-OP */ } @Override public void addFilterMapBefore(FilterMap filterMap) { /* NO-OP */ } @Override public FilterMap[] findFilterMaps() { return null; } @Override public void removeFilterMap(FilterMap filterMap) { /* NO-OP */ } @Override public void addInstanceListener(String listener) { /* NO-OP */ } @Override public String[] findInstanceListeners() { return null; } @Override public void removeInstanceListener(String listener) { /* NO-OP */ } @Override public void addLocaleEncodingMappingParameter(String locale, String encoding) { /* NO-OP */ } @Override public void addMimeMapping(String extension, String mimeType) { /* NO-OP */ } @Override public String findMimeMapping(String extension) { return null; } @Override public String[] findMimeMappings() { return null; } @Override public void removeMimeMapping(String extension) { /* NO-OP */ } @Override public void addParameter(String name, String value) { /* NO-OP */ } @Override public String findParameter(String name) { return null; } @Override public String[] findParameters() { return null; } @Override public void removeParameter(String name) { /* NO-OP */ } @Override public void addRoleMapping(String role, String link) { /* NO-OP */ } @Override public String findRoleMapping(String role) { return null; } @Override public void removeRoleMapping(String role) { /* NO-OP */ } @Override public void addSecurityRole(String role) { /* NO-OP */ } @Override public boolean findSecurityRole(String role) { return false; } @Override public String[] findSecurityRoles() { return null; } @Override public void removeSecurityRole(String role) { /* NO-OP */ } @Override public void addServletMapping(String pattern, String name) { /* NO-OP */ } @Override public void addServletMapping(String pattern, String name, boolean jspWildcard) { /* NO-OP */ } @Override public String findServletMapping(String pattern) { return null; } @Override public String[] findServletMappings() { return null; } @Override public void removeServletMapping(String pattern) { /* NO-OP */ } @Override public void addWelcomeFile(String name) { /* NO-OP */ } @Override public boolean findWelcomeFile(String name) { return false; } @Override public String[] findWelcomeFiles() { return null; } @Override public void removeWelcomeFile(String name) { /* NO-OP */ } @Override public void addWrapperLifecycle(String listener) { /* NO-OP */ } @Override public String[] findWrapperLifecycles() { return null; } @Override public void removeWrapperLifecycle(String listener) { /* NO-OP */ } @Override public void addWrapperListener(String listener) { /* NO-OP */ } @Override public String[] findWrapperListeners() { return null; } @Override public void removeWrapperListener(String listener) { /* NO-OP */ } @Override public Wrapper createWrapper() { return null; } @Override public String findStatusPage(int status) { return null; } @Override public int[] findStatusPages() { return null; } @Override public boolean fireRequestInitEvent(ServletRequest request) { return false; } @Override public boolean fireRequestDestroyEvent(ServletRequest request) { return false; } @Override public void reload() { /* NO-OP */ } @Override public String getRealPath(String path) { return null; } @Override public int getEffectiveMajorVersion() { return 0; } @Override public void setEffectiveMajorVersion(int major) { /* NO-OP */ } @Override public int getEffectiveMinorVersion() { return 0; } @Override public void setEffectiveMinorVersion(int minor) { /* NO-OP */ } @Override public JspConfigDescriptor getJspConfigDescriptor() { return null; } @Override public void setJspConfigDescriptor(JspConfigDescriptor descriptor) { /* NO-OP */ } @Override public void addServletContainerInitializer(ServletContainerInitializer sci, Set<Class<?>> classes) { /* NO-OP */ } @Override public boolean getPaused() { return false; } @Override public boolean isServlet22() { return false; } @Override public Set<String> addServletSecurity( ServletRegistration.Dynamic registration, ServletSecurityElement servletSecurityElement) { return null; } @Override public void setResourceOnlyServlets(String resourceOnlyServlets) { /* NO-OP */ } @Override public String getResourceOnlyServlets() { return null; } @Override public boolean isResourceOnlyServlet(String servletName) { return false; } @Override public String getBaseName() { return null; } @Override public void setFireRequestListenersOnForwards(boolean enable) { /* NO-OP */ } @Override public boolean getFireRequestListenersOnForwards() { return false; } @Override public void setPreemptiveAuthentication(boolean enable) { /* NO-OP */ } @Override public boolean getPreemptiveAuthentication() { return false; } @Override public void setSendRedirectBody(boolean enable) { /* NO-OP */ } @Override public boolean getSendRedirectBody() { return false; } @SuppressWarnings("unused") public synchronized void addValve(Valve valve) { /* NO-OP */ } @Override public File getCatalinaBase() { return null; } @Override public void setAddWebinfClassesResources(boolean addWebinfClassesResources) { // NO-OP } @Override public boolean getAddWebinfClassesResources() { return false; } @Override public void addPostConstructMethod(String clazz, String method) { /* NO-OP */ } @Override public void addPreDestroyMethod(String clazz, String method) { /* NO-OP */ } @Override public void removePostConstructMethod(String clazz) { /* NO-OP */ } @Override public void removePreDestroyMethod(String clazz) { /* NO-OP */ } @Override public String findPostConstructMethod(String clazz) { return null; } @Override public String findPreDestroyMethod(String clazz) { return null; } @Override public Map<String, String> findPostConstructMethods() { return null; } @Override public Map<String, String> findPreDestroyMethods() { return null; } @Override public InstanceManager getInstanceManager() { return null; } @Override public void setInstanceManager(InstanceManager instanceManager) { /* NO-OP */ } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/startup/HostConfig.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.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; 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.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.jar.JarEntry; import java.util.jar.JarFile; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.management.ObjectName; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.DistributedManager; import org.apache.catalina.Host; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.Manager; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardHost; import org.apache.catalina.util.ContextName; import org.apache.catalina.util.IOTools; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.digester.Digester; import org.apache.tomcat.util.modeler.Registry; import org.apache.tomcat.util.res.StringManager; /** * Startup event listener for a <b>Host</b> that configures the properties * of that Host, and the associated defined contexts. * * @author Craig R. McClanahan * @author Remy Maucherat * @version $Id$ */ public class HostConfig implements LifecycleListener { private static final Log log = LogFactory.getLog( HostConfig.class ); // ----------------------------------------------------- Instance Variables /** * The Java class name of the Context implementation we should use. */ protected String contextClass = "org.apache.catalina.core.StandardContext"; /** * The Host we are associated with. */ protected Host host = null; /** * The JMX ObjectName of this component. */ protected ObjectName oname = null; /** * The string resources for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Should we deploy XML Context config files packaged with WAR files and * directories? */ protected boolean deployXML = false; /** * Should XML files be copied to * $CATALINA_BASE/conf/&lt;engine&gt;/&lt;host&gt; by default when * a web application is deployed? */ protected boolean copyXML = false; /** * Should we unpack WAR files when auto-deploying applications in the * <code>appBase</code> directory? */ protected boolean unpackWARs = false; /** * Map of deployed applications. */ protected final Map<String, DeployedApplication> deployed = new ConcurrentHashMap<>(); /** * List of applications which are being serviced, and shouldn't be * deployed/undeployed/redeployed at the moment. */ protected final ArrayList<String> serviced = new ArrayList<>(); /** * The <code>Digester</code> instance used to parse context descriptors. */ protected Digester digester = createDigester(contextClass); private final Object digesterLock = new Object(); /** * The list of Wars in the appBase to be ignored because they are invalid * (e.g. contain /../ sequences). */ protected final Set<String> invalidWars = new HashSet<>(); // ------------------------------------------------------------- Properties /** * Return the Context implementation class name. */ public String getContextClass() { return (this.contextClass); } /** * Set the Context implementation class name. * * @param contextClass The new Context implementation class name. */ public void setContextClass(String contextClass) { String oldContextClass = this.contextClass; this.contextClass = contextClass; if (!oldContextClass.equals(contextClass)) { synchronized (digesterLock) { digester = createDigester(getContextClass()); } } } /** * Return the deploy XML config file flag for this component. */ public boolean isDeployXML() { return (this.deployXML); } /** * Set the deploy XML config file flag for this component. * * @param deployXML The new deploy XML flag */ public void setDeployXML(boolean deployXML) { this.deployXML= deployXML; } /** * Return the copy XML config file flag for this component. */ public boolean isCopyXML() { return (this.copyXML); } /** * Set the copy XML config file flag for this component. * * @param copyXML The new copy XML flag */ public void setCopyXML(boolean copyXML) { this.copyXML= copyXML; } /** * Return the unpack WARs flag. */ public boolean isUnpackWARs() { return (this.unpackWARs); } /** * Set the unpack WARs flag. * * @param unpackWARs The new unpack WARs flag */ public void setUnpackWARs(boolean unpackWARs) { this.unpackWARs = unpackWARs; } // --------------------------------------------------------- Public Methods /** * Process the START event for an associated Host. * * @param event The lifecycle event that has occurred */ @Override public void lifecycleEvent(LifecycleEvent event) { // Identify the host we are associated with try { host = (Host) event.getLifecycle(); if (host instanceof StandardHost) { setCopyXML(((StandardHost) host).isCopyXML()); setDeployXML(((StandardHost) host).isDeployXML()); setUnpackWARs(((StandardHost) host).isUnpackWARs()); setContextClass(((StandardHost) host).getContextClass()); } } catch (ClassCastException e) { log.error(sm.getString("hostConfig.cce", event.getLifecycle()), e); return; } // Process the event that has occurred if (event.getType().equals(Lifecycle.PERIODIC_EVENT)) { check(); } else if (event.getType().equals(Lifecycle.START_EVENT)) { start(); } else if (event.getType().equals(Lifecycle.STOP_EVENT)) { stop(); } } /** * Add a serviced application to the list. */ public synchronized void addServiced(String name) { serviced.add(name); } /** * Is application serviced ? * @return state of the application */ public synchronized boolean isServiced(String name) { return (serviced.contains(name)); } /** * Removed a serviced application from the list. */ public synchronized void removeServiced(String name) { serviced.remove(name); } /** * Get the instant where an application was deployed. * @return 0L if no application with that name is deployed, or the instant * on which the application was deployed */ public long getDeploymentTime(String name) { DeployedApplication app = deployed.get(name); if (app == null) { return 0L; } return app.timestamp; } /** * Has the specified application been deployed? Note applications defined * in server.xml will not have been deployed. * @return <code>true</code> if the application has been deployed and * <code>false</code> if the application has not been deployed or does not * exist */ public boolean isDeployed(String name) { DeployedApplication app = deployed.get(name); if (app == null) { return false; } return true; } // ------------------------------------------------------ Protected Methods /** * Create the digester which will be used to parse context config files. */ protected static Digester createDigester(String contextClassName) { Digester digester = new Digester(); digester.setValidating(false); // Add object creation rule digester.addObjectCreate("Context", contextClassName, "className"); // Set the properties on that object (it doesn't matter if extra // properties are set) digester.addSetProperties("Context"); return (digester); } protected File returnCanonicalPath(String path) { File file = new File(path); if (!file.isAbsolute()) file = new File(host.getCatalinaBase(), path); try { return file.getCanonicalFile(); } catch (IOException e) { return file; } } /** * Get the name of the configBase. * For use with JMX management. */ public String getConfigBaseName() { return host.getConfigBaseFile().getAbsolutePath(); } /** * Deploy applications for any directories or WAR files that are found * in our "application root" directory. */ protected void deployApps() { File appBase = host.getAppBaseFile(); File configBase = host.getConfigBaseFile(); String[] filteredAppPaths = filterAppPaths(appBase.list()); // Deploy XML descriptors from configBase deployDescriptors(configBase, configBase.list()); // Deploy WARs deployWARs(appBase, filteredAppPaths); // Deploy expanded folders deployDirectories(appBase, filteredAppPaths); } /** * Filter the list of application file paths to remove those that match * the regular expression defined by {@link Host#getDeployIgnore()}. * * @param unfilteredAppPaths The list of application paths to filtert * * @return The filtered list of application paths */ protected String[] filterAppPaths(String[] unfilteredAppPaths) { Pattern filter = host.getDeployIgnorePattern(); if (filter == null) { return unfilteredAppPaths; } List<String> filteredList = new ArrayList<>(); Matcher matcher = null; for (String appPath : unfilteredAppPaths) { if (matcher == null) { matcher = filter.matcher(appPath); } else { matcher.reset(appPath); } if (matcher.matches()) { if (log.isDebugEnabled()) { log.debug(sm.getString("hostConfig.ignorePath", appPath)); } } else { filteredList.add(appPath); } } return filteredList.toArray(new String[filteredList.size()]); } /** * Deploy applications for any directories or WAR files that are found * in our "application root" directory. */ protected void deployApps(String name) { File appBase = host.getAppBaseFile(); File configBase = host.getConfigBaseFile(); ContextName cn = new ContextName(name); String baseName = cn.getBaseName(); if (deploymentExists(baseName)) { return; } // Deploy XML descriptor from configBase File xml = new File(configBase, baseName + ".xml"); if (xml.exists()) { deployDescriptor(cn, xml); return; } // Deploy WAR File war = new File(appBase, baseName + ".war"); if (war.exists()) { deployWAR(cn, war); return; } // Deploy expanded folder File dir = new File(appBase, baseName); if (dir.exists()) deployDirectory(cn, dir); } /** * Deploy XML context descriptors. */ protected void deployDescriptors(File configBase, String[] files) { if (files == null) return; ExecutorService es = host.getStartStopExecutor(); List<Future<?>> results = new ArrayList<>(); for (int i = 0; i < files.length; i++) { File contextXml = new File(configBase, files[i]); if (files[i].toLowerCase(Locale.ENGLISH).endsWith(".xml")) { ContextName cn = new ContextName(files[i]); if (isServiced(cn.getName()) || deploymentExists(cn.getName())) continue; results.add( es.submit(new DeployDescriptor(this, cn, contextXml))); } } for (Future<?> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.threaded.error"), e); } } } /** * @param cn * @param contextXml */ @SuppressWarnings("null") // context is not null protected void deployDescriptor(ContextName cn, File contextXml) { DeployedApplication deployedApp = new DeployedApplication(cn.getName(), true); // Assume this is a configuration descriptor and deploy it if(log.isInfoEnabled()) { log.info(sm.getString("hostConfig.deployDescriptor", contextXml.getAbsolutePath())); } Context context = null; boolean isExternalWar = false; boolean isExternal = false; File expandedDocBase = null; try (FileInputStream fis = new FileInputStream(contextXml)) { synchronized (digesterLock) { try { context = (Context) digester.parse(fis); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), e); } finally { if (context == null) { context = new FailedContext(); } digester.reset(); } } Class<?> clazz = Class.forName(host.getConfigClass()); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); context.addLifecycleListener(listener); context.setConfigFile(contextXml.toURI().toURL()); context.setName(cn.getName()); context.setPath(cn.getPath()); context.setWebappVersion(cn.getVersion()); // Add the associated docBase to the redeployed list if it's a WAR if (context.getDocBase() != null) { File docBase = new File(context.getDocBase()); if (!docBase.isAbsolute()) { docBase = new File(host.getAppBaseFile(), context.getDocBase()); } // If external docBase, register .xml as redeploy first if (!docBase.getCanonicalPath().startsWith( host.getAppBaseFile().getAbsolutePath() + File.separator)) { isExternal = true; deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); if (docBase.getAbsolutePath().toLowerCase(Locale.ENGLISH).endsWith(".war")) { isExternalWar = true; } } else { log.warn(sm.getString("hostConfig.deployDescriptor.localDocBaseSpecified", docBase)); // Ignore specified docBase context.setDocBase(null); } } host.addChild(context); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDescriptor.error", contextXml.getAbsolutePath()), t); } finally { // Get paths for WAR and expanded WAR in appBase // default to appBase dir + name expandedDocBase = new File(host.getAppBaseFile(), cn.getBaseName()); if (context.getDocBase() != null) { // first assume docBase is absolute expandedDocBase = new File(context.getDocBase()); if (!expandedDocBase.isAbsolute()) { // if docBase specified and relative, it must be relative to appBase expandedDocBase = new File(host.getAppBaseFile(), context.getDocBase()); } } // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isExternalWar && unpackWARs) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); deployedApp.redeployResources.put(contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { // Find an existing matching war and expanded folder if (!isExternal) { File warDocBase = new File(expandedDocBase.getAbsolutePath() + ".war"); if (warDocBase.exists()) { deployedApp.redeployResources.put(warDocBase.getAbsolutePath(), Long.valueOf(warDocBase.lastModified())); } else { // Trigger a redeploy if a WAR is added deployedApp.redeployResources.put( warDocBase.getAbsolutePath(), Long.valueOf(0)); } } if (expandedDocBase.exists()) { deployedApp.redeployResources.put(expandedDocBase.getAbsolutePath(), Long.valueOf(expandedDocBase.lastModified())); addWatchedResources(deployedApp, expandedDocBase.getAbsolutePath(), context); } else { if (!isExternal && !unpackWARs) { // Trigger a reload if a DIR is added deployedApp.reloadResources.put( expandedDocBase.getAbsolutePath(), Long.valueOf(0)); } addWatchedResources(deployedApp, null, context); } // Add the context XML to the list of files which should trigger a redeployment if (!isExternal) { deployedApp.redeployResources.put( contextXml.getAbsolutePath(), Long.valueOf(contextXml.lastModified())); } } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); } if (host.findChild(context.getName()) != null) { deployed.put(context.getName(), deployedApp); } } /** * Deploy WAR files. */ protected void deployWARs(File appBase, String[] files) { if (files == null) return; ExecutorService es = host.getStartStopExecutor(); List<Future<?>> results = new ArrayList<>(); for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; File war = new File(appBase, files[i]); if (files[i].toLowerCase(Locale.ENGLISH).endsWith(".war") && war.isFile() && !invalidWars.contains(files[i]) ) { ContextName cn = new ContextName(files[i]); if (isServiced(cn.getName())) { continue; } if (deploymentExists(cn.getName())) { DeployedApplication app = deployed.get(cn.getName()); if (!unpackWARs && app != null) { // Need to check for a directory that should not be // there File dir = new File(appBase, cn.getBaseName()); if (dir.exists()) { if (!app.loggedDirWarning) { log.warn(sm.getString( "hostConfig.deployWar.hiddenDir", dir.getAbsoluteFile(), war.getAbsoluteFile())); app.loggedDirWarning = true; } } else { app.loggedDirWarning = false; } } continue; } // Check for WARs with /../ /./ or similar sequences in the name if (!validateContextPath(appBase, cn.getBaseName())) { log.error(sm.getString( "hostConfig.illegalWarName", files[i])); invalidWars.add(files[i]); continue; } results.add(es.submit(new DeployWar(this, cn, war))); } } for (Future<?> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployWar.threaded.error"), e); } } } private boolean validateContextPath(File appBase, String contextPath) { // More complicated than the ideal as the canonical path may or may // not end with File.separator for a directory StringBuilder docBase; String canonicalDocBase = null; try { String canonicalAppBase = appBase.getCanonicalPath(); docBase = new StringBuilder(canonicalAppBase); if (canonicalAppBase.endsWith(File.separator)) { docBase.append(contextPath.substring(1).replace( '/', File.separatorChar)); } else { docBase.append(contextPath.replace('/', File.separatorChar)); } // At this point docBase should be canonical but will not end // with File.separator canonicalDocBase = (new File(docBase.toString())).getCanonicalPath(); // If the canonicalDocBase ends with File.separator, add one to // docBase before they are compared if (canonicalDocBase.endsWith(File.separator)) { docBase.append(File.separator); } } catch (IOException ioe) { return false; } // Compare the two. If they are not the same, the contextPath must // have /../ like sequences in it return canonicalDocBase.equals(docBase.toString()); } /** * @param cn * @param war */ protected void deployWAR(ContextName cn, File war) { // Checking for a nested /META-INF/context.xml JarFile jar = null; InputStream istream = null; FileOutputStream fos = null; BufferedOutputStream ostream = null; File xml = new File(host.getAppBaseFile(), cn.getBaseName() + "/META-INF/context.xml"); boolean xmlInWar = false; JarEntry entry = null; try { jar = new JarFile(war); entry = jar.getJarEntry(Constants.ApplicationContextXml); if (entry != null) { xmlInWar = true; } } catch (IOException e) { /* Ignore */ } finally { entry = null; if (jar != null) { try { jar.close(); } catch (IOException ioe) { // Ignore; } jar = null; } } Context context = null; try { if (deployXML && xml.exists() && !copyXML) { synchronized (digesterLock) { try { context = (Context) digester.parse(xml); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath()), e); } finally { if (context == null) { context = new FailedContext(); } digester.reset(); } } context.setConfigFile(xml.toURI().toURL()); } else if (deployXML && xmlInWar) { synchronized (digesterLock) { try { jar = new JarFile(war); entry = jar.getJarEntry(Constants.ApplicationContextXml); istream = jar.getInputStream(entry); context = (Context) digester.parse(istream); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", war.getAbsolutePath()), e); } finally { if (context == null) { context = new FailedContext(); } context.setConfigFile(new URL("jar:" + war.toURI().toString() + "!/" + Constants.ApplicationContextXml)); if (istream != null) { try { istream.close(); } catch (IOException e) { /* Ignore */ } istream = null; } entry = null; if (jar != null) { try { jar.close(); } catch (IOException e) { /* Ignore */ } jar = null; } digester.reset(); } } } else if (!deployXML && xmlInWar) { // Block deployment as META-INF/context.xml may contain security // configuration necessary for a secure deployment. log.error(sm.getString("hostConfig.deployDescriptor.blocked", cn.getPath(), Constants.ApplicationContextXml, new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml"))); } else { context = (Context) Class.forName(contextClass).newInstance(); } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); } finally { if (context == null) { context = new FailedContext(); } } boolean copyThisXml = false; if (deployXML) { if (host instanceof StandardHost) { copyThisXml = ((StandardHost) host).isCopyXML(); } // If Host is using default value Context can override it. if (!copyThisXml && context instanceof StandardContext) { copyThisXml = ((StandardContext) context).getCopyXML(); } if (xmlInWar && copyThisXml) { // Change location of XML file to config base xml = new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml"); entry = null; try { jar = new JarFile(war); entry = jar.getJarEntry(Constants.ApplicationContextXml); istream = jar.getInputStream(entry); fos = new FileOutputStream(xml); ostream = new BufferedOutputStream(fos, 1024); byte buffer[] = new byte[1024]; while (true) { int n = istream.read(buffer); if (n < 0) { break; } ostream.write(buffer, 0, n); } ostream.flush(); } catch (IOException e) { /* Ignore */ } finally { if (ostream != null) { try { ostream.close(); } catch (IOException ioe) { // Ignore } ostream = null; } if (fos != null) { try { fos.close(); } catch (IOException ioe) { // Ignore } fos = null; } if (istream != null) { try { istream.close(); } catch (IOException ioe) { // Ignore } istream = null; } if (jar != null) { try { jar.close(); } catch (IOException ioe) { // Ignore; } jar = null; } } } } DeployedApplication deployedApp = new DeployedApplication(cn.getName(), xml.exists() && deployXML && copyThisXml); // Deploy the application in this WAR file if(log.isInfoEnabled()) log.info(sm.getString("hostConfig.deployWar", war.getAbsolutePath())); try { // Populate redeploy resources with the WAR file deployedApp.redeployResources.put (war.getAbsolutePath(), Long.valueOf(war.lastModified())); if (deployXML && xml.exists() && copyThisXml) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } else if (!copyThisXml ) { // In case an XML file is added to the config base later deployedApp.redeployResources.put( (new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml")).getAbsolutePath(), Long.valueOf(0)); } Class<?> clazz = Class.forName(host.getConfigClass()); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); context.addLifecycleListener(listener); context.setName(cn.getName()); context.setPath(cn.getPath()); context.setWebappVersion(cn.getVersion()); context.setDocBase(cn.getBaseName() + ".war"); host.addChild(context); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployWar.error", war.getAbsolutePath()), t); } finally { // If we're unpacking WARs, the docBase will be mutated after // starting the context if (unpackWARs && context != null && context.getDocBase() != null) { File docBase = new File(host.getAppBaseFile(), cn.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); if (deployXML && !copyThisXml && (xmlInWar || xml.exists())) { deployedApp.redeployResources.put(xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); } } else { // Passing null for docBase means that no resources will be // watched. This will be logged at debug level. addWatchedResources(deployedApp, null, context); } // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); } deployed.put(cn.getName(), deployedApp); } /** * Deploy directories. */ protected void deployDirectories(File appBase, String[] files) { if (files == null) return; ExecutorService es = host.getStartStopExecutor(); List<Future<?>> results = new ArrayList<>(); for (int i = 0; i < files.length; i++) { if (files[i].equalsIgnoreCase("META-INF")) continue; if (files[i].equalsIgnoreCase("WEB-INF")) continue; File dir = new File(appBase, files[i]); if (dir.isDirectory()) { ContextName cn = new ContextName(files[i]); if (isServiced(cn.getName()) || deploymentExists(cn.getName())) continue; results.add(es.submit(new DeployDirectory(this, cn, dir))); } } for (Future<?> result : results) { try { result.get(); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDir.threaded.error"), e); } } } /** * @param cn * @param dir */ protected void deployDirectory(ContextName cn, File dir) { // Deploy the application in this directory if( log.isInfoEnabled() ) log.info(sm.getString("hostConfig.deployDir", dir.getAbsolutePath())); Context context = null; File xml = new File(dir, Constants.ApplicationContextXml); File xmlCopy = new File(host.getConfigBaseFile(), cn.getBaseName() + ".xml"); DeployedApplication deployedApp; boolean copyThisXml = copyXML; try { if (deployXML && xml.exists()) { synchronized (digesterLock) { try { context = (Context) digester.parse(xml); } catch (Exception e) { log.error(sm.getString( "hostConfig.deployDescriptor.error", xml), e); context = new FailedContext(); } finally { if (context == null) { context = new FailedContext(); } digester.reset(); } } if (copyThisXml == false && context instanceof StandardContext) { // Host is using default value. Context may override it. copyThisXml = ((StandardContext) context).getCopyXML(); } if (copyThisXml) { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(xml); os = new FileOutputStream(xmlCopy); IOTools.flow(is, os); // Don't catch IOE - let the outer try/catch handle it } finally { try { if (is != null) is.close(); } catch (IOException e){ // Ignore } try { if (os != null) os.close(); } catch (IOException e){ // Ignore } } context.setConfigFile(xmlCopy.toURI().toURL()); } else { context.setConfigFile(xml.toURI().toURL()); } } else if (!deployXML && xml.exists()) { // Block deployment as META-INF/context.xml may contain security // configuration necessary for a secure deployment. log.error(sm.getString("hostConfig.deployDescriptor.blocked", cn.getPath(), xml, xmlCopy)); context = new FailedContext(); } else { context = (Context) Class.forName(contextClass).newInstance(); } Class<?> clazz = Class.forName(host.getConfigClass()); LifecycleListener listener = (LifecycleListener) clazz.newInstance(); context.addLifecycleListener(listener); context.setName(cn.getName()); context.setPath(cn.getPath()); context.setWebappVersion(cn.getVersion()); context.setDocBase(cn.getBaseName()); host.addChild(context); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("hostConfig.deployDir.error", dir.getAbsolutePath()), t); } finally { deployedApp = new DeployedApplication(cn.getName(), xml.exists() && deployXML && copyThisXml); // Fake re-deploy resource to detect if a WAR is added at a later // point deployedApp.redeployResources.put(dir.getAbsolutePath() + ".war", Long.valueOf(0)); deployedApp.redeployResources.put(dir.getAbsolutePath(), Long.valueOf(dir.lastModified())); if (deployXML && xml.exists()) { if (copyThisXml) { deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(xmlCopy.lastModified())); } else { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(xml.lastModified())); // Fake re-deploy resource to detect if a context.xml file is // added at a later point deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(0)); } } else { // Fake re-deploy resource to detect if a context.xml file is // added at a later point deployedApp.redeployResources.put( xmlCopy.getAbsolutePath(), Long.valueOf(0)); if (!xml.exists()) { deployedApp.redeployResources.put( xml.getAbsolutePath(), Long.valueOf(0)); } } addWatchedResources(deployedApp, dir.getAbsolutePath(), context); // Add the global redeploy resources (which are never deleted) at // the end so they don't interfere with the deletion process addGlobalRedeployResources(deployedApp); } deployed.put(cn.getName(), deployedApp); } /** * Check if a webapp is already deployed in this host. * * @param contextName of the context which will be checked */ protected boolean deploymentExists(String contextName) { return (deployed.containsKey(contextName) || (host.findChild(contextName) != null)); } /** * Add watched resources to the specified Context. * @param app HostConfig deployed app * @param docBase web app docBase * @param context web application context */ protected void addWatchedResources(DeployedApplication app, String docBase, Context context) { // FIXME: Feature idea. Add support for patterns (ex: WEB-INF/*, // WEB-INF/*.xml), where we would only check if at least one // resource is newer than app.timestamp File docBaseFile = null; if (docBase != null) { docBaseFile = new File(docBase); if (!docBaseFile.isAbsolute()) { docBaseFile = new File(host.getAppBaseFile(), docBase); } } String[] watchedResources = context.findWatchedResources(); for (int i = 0; i < watchedResources.length; i++) { File resource = new File(watchedResources[i]); if (!resource.isAbsolute()) { if (docBase != null) { resource = new File(docBaseFile, watchedResources[i]); } else { if(log.isDebugEnabled()) log.debug("Ignoring non-existent WatchedResource '" + resource.getAbsolutePath() + "'"); continue; } } if(log.isDebugEnabled()) log.debug("Watching WatchedResource '" + resource.getAbsolutePath() + "'"); app.reloadResources.put(resource.getAbsolutePath(), Long.valueOf(resource.lastModified())); } } protected void addGlobalRedeployResources(DeployedApplication app) { // Redeploy resources processing is hard-coded to never delete this file File hostContextXml = new File(getConfigBaseName(), Constants.HostContextXml); if (hostContextXml.isFile()) { app.redeployResources.put(hostContextXml.getAbsolutePath(), Long.valueOf(hostContextXml.lastModified())); } // Redeploy resources in CATALINA_BASE/conf are never deleted File globalContextXml = returnCanonicalPath(Constants.DefaultContextXml); if (globalContextXml.isFile()) { app.redeployResources.put(globalContextXml.getAbsolutePath(), Long.valueOf(globalContextXml.lastModified())); } } /** * Check resources for redeployment and reloading. */ protected synchronized void checkResources(DeployedApplication app) { String[] resources = app.redeployResources.keySet().toArray(new String[0]); for (int i = 0; i < resources.length; i++) { File resource = new File(resources[i]); if (log.isDebugEnabled()) log.debug("Checking context[" + app.name + "] redeploy resource " + resource); long lastModified = app.redeployResources.get(resources[i]).longValue(); if (resource.exists() || lastModified == 0) { if (resource.lastModified() > lastModified) { if (resource.isDirectory()) { // No action required for modified directory app.redeployResources.put(resources[i], Long.valueOf(resource.lastModified())); } else if (app.hasDescriptor && resource.getName().toLowerCase( Locale.ENGLISH).endsWith(".war")) { // Modified WAR triggers a reload if there is an XML // file present // The only resource that should be deleted is the // expanded WAR (if any) Context context = (Context) host.findChild(app.name); String docBase = context.getDocBase(); docBase = docBase.toLowerCase(Locale.ENGLISH); if (!docBase.endsWith(".war")) { // This is an expanded directory File docBaseFile = new File(docBase); if (!docBaseFile.isAbsolute()) { docBaseFile = new File(host.getAppBaseFile(), docBase); } ExpandWar.delete(docBaseFile); // Reset the docBase to trigger re-expansion of the // WAR context.setDocBase(resource.getAbsolutePath()); } reload(app); // Update times app.redeployResources.put(resources[i], Long.valueOf(resource.lastModified())); app.timestamp = System.currentTimeMillis(); if (unpackWARs) { addWatchedResources(app, context.getDocBase(), context); } else { addWatchedResources(app, null, context); } return; } else { // Everything else triggers a redeploy // (just need to undeploy here, deploy will follow) deleteRedeployResources(app, resources, i, false); undeploy(app); return; } } } else { // There is a chance the the resource was only missing // temporarily eg renamed during a text editor save try { Thread.sleep(500); } catch (InterruptedException e1) { // Ignore } // Recheck the resource to see if it was really deleted if (resource.exists()) { continue; } if (lastModified == 0L) { continue; } // Undeploy application undeploy(app); deleteRedeployResources(app, resources, i, true); return; } } resources = app.reloadResources.keySet().toArray(new String[0]); for (int i = 0; i < resources.length; i++) { File resource = new File(resources[i]); if (log.isDebugEnabled()) log.debug("Checking context[" + app.name + "] reload resource " + resource); long lastModified = app.reloadResources.get(resources[i]).longValue(); if ((!resource.exists() && lastModified != 0L) || (resource.lastModified() != lastModified)) { // Reload application reload(app); // Update times app.reloadResources.put(resources[i], Long.valueOf(resource.lastModified())); app.timestamp = System.currentTimeMillis(); return; } } } private void reload(DeployedApplication app) { if(log.isInfoEnabled()) log.info(sm.getString("hostConfig.reload", app.name)); Context context = (Context) host.findChild(app.name); if (context.getState().isAvailable()) { // Reload catches and logs exceptions context.reload(); } else { // If the context was not started (for example an error // in web.xml) we'll still get to try to start try { context.start(); } catch (Exception e) { log.warn(sm.getString ("hostConfig.context.restart", app.name), e); } } } private void undeploy(DeployedApplication app) { if (log.isInfoEnabled()) log.info(sm.getString("hostConfig.undeploy", app.name)); Container context = host.findChild(app.name); try { host.removeChild(context); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString ("hostConfig.context.remove", app.name), t); } deployed.remove(app.name); } private void deleteRedeployResources(DeployedApplication app, String[] resources, int i, boolean deleteReloadResources) { // Delete other redeploy resources for (int j = i + 1; j < resources.length; j++) { try { File current = new File(resources[j]); current = current.getCanonicalFile(); // Never delete per host context.xml defaults if (Constants.HostContextXml.equals( current.getName())) { continue; } // Only delete resources in the appBase or the // host's configBase if (isDeletableResource(current)) { if (log.isDebugEnabled()) log.debug("Delete " + current); ExpandWar.delete(current); } } catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); } } // Delete reload resources (to remove any remaining .xml descriptor) if (deleteReloadResources) { String[] resources2 = app.reloadResources.keySet().toArray(new String[0]); for (int j = 0; j < resources2.length; j++) { try { File current = new File(resources2[j]); current = current.getCanonicalFile(); // Never delete per host context.xml defaults if (Constants.HostContextXml.equals( current.getName())) { continue; } // Only delete resources in the appBase or the host's // configBase if (isDeletableResource(current)) { if (log.isDebugEnabled()) log.debug("Delete " + current); ExpandWar.delete(current); } } catch (IOException e) { log.warn(sm.getString ("hostConfig.canonicalizing", app.name), e); } } } } private boolean isDeletableResource(File resource) { if ((resource.getAbsolutePath().startsWith( host.getAppBaseFile().getAbsolutePath() + File.separator)) || ((resource.getAbsolutePath().startsWith( host.getConfigBaseFile().getAbsolutePath()) && (resource.getAbsolutePath().endsWith(".xml"))))) { return true; } return false; } /** * Process a "start" event for this Host. */ public void start() { if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.start")); try { ObjectName hostON = host.getObjectName(); oname = new ObjectName (hostON.getDomain() + ":type=Deployer,host=" + host.getName()); Registry.getRegistry(null, null).registerComponent (this, oname, this.getClass().getName()); } catch (Exception e) { log.error(sm.getString("hostConfig.jmx.register", oname), e); } if (host.getCreateDirs()) { File[] dirs = new File[] {host.getAppBaseFile(),host.getConfigBaseFile()}; for (int i=0; i<dirs.length; i++) { if (!dirs[i].mkdirs() && !dirs[i].isDirectory()) { log.error(sm.getString("hostConfig.createDirs",dirs[i])); } } } if (!host.getAppBaseFile().isDirectory()) { log.error(sm.getString("hostConfig.appBase", host.getName(), host.getAppBaseFile().getPath())); host.setDeployOnStartup(false); host.setAutoDeploy(false); } if (host.getDeployOnStartup()) deployApps(); } /** * Process a "stop" event for this Host. */ public void stop() { if (log.isDebugEnabled()) log.debug(sm.getString("hostConfig.stop")); if (oname != null) { try { Registry.getRegistry(null, null).unregisterComponent(oname); } catch (Exception e) { log.error(sm.getString("hostConfig.jmx.unregister", oname), e); } } oname = null; } /** * Check status of all webapps. */ protected void check() { if (host.getAutoDeploy()) { // Check for resources modification to trigger redeployment DeployedApplication[] apps = deployed.values().toArray(new DeployedApplication[0]); for (int i = 0; i < apps.length; i++) { if (!isServiced(apps[i].name)) checkResources(apps[i]); } // Check for old versions of applications that can now be undeployed if (host.getUndeployOldVersions()) { checkUndeploy(); } // Hotdeploy applications deployApps(); } } /** * Check status of a specific webapp, for use with stuff like management webapps. */ public void check(String name) { DeployedApplication app = deployed.get(name); if (app != null) { checkResources(app); } deployApps(name); } /** * Check for old versions of applications using parallel deployment that are * now unused (have no active sessions) and undeploy any that are found. */ public synchronized void checkUndeploy() { // Need ordered set of names SortedSet<String> sortedAppNames = new TreeSet<>(); sortedAppNames.addAll(deployed.keySet()); if (sortedAppNames.size() < 2) { return; } Iterator<String> iter = sortedAppNames.iterator(); ContextName previous = new ContextName(iter.next()); do { ContextName current = new ContextName(iter.next()); if (current.getPath().equals(previous.getPath())) { // Current and previous are same path - current will always // be a later version Context previousContext = (Context) host.findChild(previous.getName()); Context currentContext = (Context) host.findChild(previous.getName()); if (previousContext != null && currentContext != null && currentContext.getState().isAvailable() && !isServiced(previous.getName())) { Manager manager = previousContext.getManager(); if (manager != null) { int sessionCount; if (manager instanceof DistributedManager) { sessionCount = ((DistributedManager) manager).getActiveSessionsFull(); } else { sessionCount = manager.getActiveSessions(); } if (sessionCount == 0) { if (log.isInfoEnabled()) { log.info(sm.getString( "hostConfig.undeployVersion", previous.getName())); } DeployedApplication app = deployed.get(previous.getName()); String[] resources = app.redeployResources.keySet().toArray( new String[0]); // Version is unused - undeploy it completely // The -1 is a 'trick' to ensure all redeploy // resources are removed undeploy(app); deleteRedeployResources(app, resources, -1, true); } } } } previous = current; } while (iter.hasNext()); } /** * Add a new Context to be managed by us. * Entry point for the admin webapp, and other JMX Context controllers. */ public void manageApp(Context context) { String contextName = context.getName(); if (deployed.containsKey(contextName)) return; DeployedApplication deployedApp = new DeployedApplication(contextName, false); // Add the associated docBase to the redeployed list if it's a WAR boolean isWar = false; if (context.getDocBase() != null) { File docBase = new File(context.getDocBase()); if (!docBase.isAbsolute()) { docBase = new File(host.getAppBaseFile(), context.getDocBase()); } deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); if (docBase.getAbsolutePath().toLowerCase(Locale.ENGLISH).endsWith(".war")) { isWar = true; } } host.addChild(context); // Add the eventual unpacked WAR and all the resources which will be // watched inside it if (isWar && unpackWARs) { File docBase = new File(host.getAppBaseFile(), context.getBaseName()); deployedApp.redeployResources.put(docBase.getAbsolutePath(), Long.valueOf(docBase.lastModified())); addWatchedResources(deployedApp, docBase.getAbsolutePath(), context); } else { addWatchedResources(deployedApp, null, context); } deployed.put(contextName, deployedApp); } /** * Remove a webapp from our control. * Entry point for the admin webapp, and other JMX Context controllers. */ public void unmanageApp(String contextName) { if(isServiced(contextName)) { deployed.remove(contextName); host.removeChild(host.findChild(contextName)); } } // ----------------------------------------------------- Instance Variables /** * This class represents the state of a deployed application, as well as * the monitored resources. */ protected static class DeployedApplication { public DeployedApplication(String name, boolean hasDescriptor) { this.name = name; this.hasDescriptor = hasDescriptor; } /** * Application context path. The assertion is that * (host.getChild(name) != null). */ public final String name; /** * Does this application have a context.xml descriptor file on the * host's configBase? */ public final boolean hasDescriptor; /** * Any modification of the specified (static) resources will cause a * redeployment of the application. If any of the specified resources is * removed, the application will be undeployed. Typically, this will * contain resources like the context.xml file, a compressed WAR path. * The value is the last modification time. */ public final LinkedHashMap<String, Long> redeployResources = new LinkedHashMap<>(); /** * Any modification of the specified (static) resources will cause a * reload of the application. This will typically contain resources * such as the web.xml of a webapp, but can be configured to contain * additional descriptors. * The value is the last modification time. */ public final HashMap<String, Long> reloadResources = new HashMap<>(); /** * Instant where the application was last put in service. */ public long timestamp = System.currentTimeMillis(); /** * In some circumstances, such as when unpackWARs is true, a directory * may be added to the appBase that is ignored. This flag indicates that * the user has been warned so that the warning is not logged on every * run of the auto deployer. */ public boolean loggedDirWarning = false; } private static class DeployDescriptor implements Runnable { private HostConfig config; private ContextName cn; private File descriptor; public DeployDescriptor(HostConfig config, ContextName cn, File descriptor) { this.config = config; this.cn = cn; this.descriptor= descriptor; } @Override public void run() { config.deployDescriptor(cn, descriptor); } } private static class DeployWar implements Runnable { private HostConfig config; private ContextName cn; private File war; public DeployWar(HostConfig config, ContextName cn, File war) { this.config = config; this.cn = cn; this.war = war; } @Override public void run() { config.deployWAR(cn, war); } } private static class DeployDirectory implements Runnable { private HostConfig config; private ContextName cn; private File dir; public DeployDirectory(HostConfig config, ContextName cn, File dir) { this.config = config; this.cn = cn; this.dir = dir; } @Override public void run() { config.deployDirectory(cn, dir); } } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/storeconfig/StandardContextSF.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.storeconfig; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.apache.catalina.Container; import org.apache.catalina.Context; import org.apache.catalina.Engine; import org.apache.catalina.Host; import org.apache.catalina.LifecycleListener; import org.apache.catalina.Loader; import org.apache.catalina.Manager; import org.apache.catalina.Realm; import org.apache.catalina.Valve; import org.apache.catalina.WebResourceRoot; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.ThreadLocalLeakPreventionListener; import org.apache.catalina.deploy.NamingResourcesImpl; import org.apache.catalina.util.ContextName; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.descriptor.web.ApplicationParameter; /** * Store server.xml Context element with all children * <ul> * <li>Store all context at server.xml</li> * <li>Store existing app.xml context a conf/enginename/hostname/app.xml</li> * <li>Store with backup</li> * </ul> */ public class StandardContextSF extends StoreFactoryBase { private static Log log = LogFactory.getLog(StandardContextSF.class); /* * Store a Context as Separate file as configFile value from context exists. * filename can be relative to catalina.base. * * @see org.apache.catalina.config.IStoreFactory#store(java.io.PrintWriter, * int, java.lang.Object) */ @Override public void store(PrintWriter aWriter, int indent, Object aContext) throws Exception { if (aContext instanceof StandardContext) { StoreDescription desc = getRegistry().findDescription( aContext.getClass()); if (desc.isStoreSeparate()) { URL configFile = ((StandardContext) aContext) .getConfigFile(); if (configFile != null) { if (desc.isExternalAllowed()) { if (desc.isBackup()) storeWithBackup((StandardContext) aContext); else storeContextSeparate(aWriter, indent, (StandardContext) aContext); return; } } else if (desc.isExternalOnly()) { // Set a configFile so that the configuration is actually saved Context context = ((StandardContext) aContext); Host host = (Host) context.getParent(); File configBase = host.getConfigBaseFile(); ContextName cn = new ContextName(context.getName()); String baseName = cn.getBaseName(); File xml = new File(configBase, baseName + ".xml"); context.setConfigFile(xml.toURI().toURL()); if (desc.isBackup()) storeWithBackup((StandardContext) aContext); else storeContextSeparate(aWriter, indent, (StandardContext) aContext); return; } } } super.store(aWriter, indent, aContext); } /** * Store a Context without backup add separate file or when configFile = * null a aWriter. * * @param aWriter * @param indent * @param aContext * @throws Exception */ protected void storeContextSeparate(PrintWriter aWriter, int indent, StandardContext aContext) throws Exception { URL configFile = aContext.getConfigFile(); PrintWriter writer = null; if (configFile != null) { File config = new File(configFile.toURI()); if (!config.isAbsolute()) { config = new File(System.getProperty("catalina.base"), config.getPath()); } if( (!config.isFile()) || (!config.canWrite())) { log.error("Cannot write context output file at " + configFile + ", not saving."); throw new IOException("Context save file at " + configFile + " not a file, or not writable."); } if (log.isInfoEnabled()) log.info("Store Context " + aContext.getPath() + " separate at file " + config); try { writer = new PrintWriter(new OutputStreamWriter( new FileOutputStream(config), getRegistry() .getEncoding())); storeXMLHead(writer); super.store(writer, -2, aContext); } finally { if (writer != null) { try { writer.flush(); } catch (Exception e) { // Ignore } try { writer.close(); } catch (Throwable t) { // Ignore } } } } else { super.store(aWriter, indent, aContext); } } /** * Store the Context with a Backup * * @param aContext * @throws Exception */ protected void storeWithBackup(StandardContext aContext) throws Exception { StoreFileMover mover = getConfigFileWriter(aContext); if (mover != null) { // Bugzilla 37781 Check to make sure we can write this output file if ((mover.getConfigOld() == null) || (mover.getConfigOld().isDirectory()) || (mover.getConfigOld().exists() && !mover.getConfigOld().canWrite())) { log.error("Cannot move orignal context output file at " + mover.getConfigOld()); throw new IOException("Context orginal file at " + mover.getConfigOld() + " is null, not a file or not writable."); } File dir = mover.getConfigSave().getParentFile(); if (dir != null && dir.isDirectory() && (!dir.canWrite())) { log.error("Cannot save context output file at " + mover.getConfigSave()); throw new IOException("Context save file at " + mover.getConfigSave() + " is not writable."); } if (log.isInfoEnabled()) log.info("Store Context " + aContext.getPath() + " separate with backup (at file " + mover.getConfigSave() + " )"); PrintWriter writer = null; try { writer = mover.getWriter(); storeXMLHead(writer); super.store(writer, -2, aContext); } finally { if (writer != null) { // Flush and close the output file try { writer.flush(); } catch (Exception e) { log.error(e); } try { writer.close(); } catch (Exception e) { throw (e); } } } mover.move(); } } /** * Get explicit writer for context (context.getConfigFile()). * * @param context * @return The file mover * @throws IOException */ protected StoreFileMover getConfigFileWriter(Context context) throws Exception { URL configFile = context.getConfigFile(); StoreFileMover mover = null; if (configFile != null) { File config = new File(configFile.toURI()); if (!config.isAbsolute()) { config = new File(System.getProperty("catalina.base"), config.getPath()); } // Open an output writer for the new configuration file mover = new StoreFileMover("", config.getCanonicalPath(), getRegistry().getEncoding()); } return mover; } /** * Store the specified Host properties. * * @param aWriter * PrintWriter to which we are storing * @param indent * Number of spaces to indent this element * @param aContext * Context whose properties are being stored * * @exception Exception * if an exception occurs while storing */ @Override public void storeChildren(PrintWriter aWriter, int indent, Object aContext, StoreDescription parentDesc) throws Exception { if (aContext instanceof StandardContext) { StandardContext context = (StandardContext) aContext; // Store nested <Listener> elements LifecycleListener listeners[] = context.findLifecycleListeners(); ArrayList<LifecycleListener> listenersArray = new ArrayList<>(); for (LifecycleListener listener : listeners) { if (!(listener instanceof ThreadLocalLeakPreventionListener)) { listenersArray.add(listener); } } storeElementArray(aWriter, indent, listenersArray.toArray()); // Store nested <Valve> elements Valve valves[] = context.getPipeline().getValves(); storeElementArray(aWriter, indent, valves); // Store nested <Loader> elements Loader loader = context.getLoader(); storeElement(aWriter, indent, loader); // Store nested <Manager> elements if (context.getCluster() == null || !context.getManager().getDistributable()) { Manager manager = context.getManager(); storeElement(aWriter, indent, manager); } // Store nested <Realm> element Realm realm = context.getRealm(); if (realm != null) { Realm parentRealm = null; // @TODO is this case possible? if (context.getParent() != null) { parentRealm = context.getParent().getRealm(); } if (realm != parentRealm) { storeElement(aWriter, indent, realm); } } // Store nested resources WebResourceRoot resources = context.getResources(); storeElement(aWriter, indent, resources); // Store nested <InstanceListener> elements String iListeners[] = context.findInstanceListeners(); getStoreAppender().printTagArray(aWriter, "InstanceListener", indent + 2, iListeners); // Store nested <WrapperListener> elements String wLifecycles[] = context.findWrapperLifecycles(); getStoreAppender().printTagArray(aWriter, "WrapperListener", indent + 2, wLifecycles); // Store nested <WrapperLifecycle> elements String wListeners[] = context.findWrapperListeners(); getStoreAppender().printTagArray(aWriter, "WrapperLifecycle", indent + 2, wListeners); // Store nested <Parameter> elements ApplicationParameter[] appParams = context .findApplicationParameters(); storeElementArray(aWriter, indent, appParams); // Store nested naming resources elements (EJB,Resource,...) NamingResourcesImpl nresources = context.getNamingResources(); storeElement(aWriter, indent, nresources); // Store nested watched resources <WatchedResource> String[] wresources = context.findWatchedResources(); wresources = filterWatchedResources(context, wresources); getStoreAppender().printTagArray(aWriter, "WatchedResource", indent + 2, wresources); } } /** * Return a File object representing the "configuration root" directory for * our associated Host. */ protected File configBase(Context context) { File file = new File(System.getProperty("catalina.base"), "conf"); Container host = context.getParent(); if ((host != null) && (host instanceof Host)) { Container engine = host.getParent(); if ((engine != null) && (engine instanceof Engine)) { file = new File(file, engine.getName()); } file = new File(file, host.getName()); try { file = file.getCanonicalFile(); } catch (IOException e) { log.error(e); } } return (file); } /** * filter out the default watched resources * * @param context * @param wresources * @return The watched resources * @throws IOException * TODO relative watchedresource * TODO absolute handling configFile * TODO Filename case handling for Windows? * TODO digester variable subsitution $catalina.base, $catalina.home */ protected String[] filterWatchedResources(StandardContext context, String[] wresources) throws Exception { File configBase = configBase(context); String confContext = new File(System.getProperty("catalina.base"), "conf/context.xml").getCanonicalPath(); String confWeb = new File(System.getProperty("catalina.base"), "conf/web.xml").getCanonicalPath(); String confHostDefault = new File(configBase, "context.xml.default") .getCanonicalPath(); String configFile = (context.getConfigFile() != null ? new File(context.getConfigFile().toURI()).getCanonicalPath() : null); String webxml = "WEB-INF/web.xml" ; List<String> resource = new ArrayList<>(); for (int i = 0; i < wresources.length; i++) { if (wresources[i].equals(confContext)) continue; if (wresources[i].equals(confWeb)) continue; if (wresources[i].equals(confHostDefault)) continue; if (wresources[i].equals(configFile)) continue; if (wresources[i].equals(webxml)) continue; resource.add(wresources[i]); } return resource.toArray(new String[resource.size()]); } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
java/org/apache/catalina/util/ContextName.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.util.Locale; /** * Utility class to manage context names so there is one place where the * conversions between baseName, path and version take place. */ public final class ContextName { public static final String ROOT_NAME = "ROOT"; private static final String VERSION_MARKER = "##"; private static final String FWD_SLASH_REPLACEMENT = "#"; private final String baseName; private final String path; private final String version; private final String name; /** * Creates an instance from a context name, display name, base name, * directory name, WAR name or context.xml name. * * @param name The name to use as the basis for this object */ public ContextName(String name) { String tmp1 = name; // Convert Context names and display names to base names // Strip off any leading "/" if (tmp1.startsWith("/")) { tmp1 = tmp1.substring(1); } // Replace any remaining / tmp1 = tmp1.replaceAll("/", FWD_SLASH_REPLACEMENT); // Insert the ROOT name if required if (tmp1.startsWith(VERSION_MARKER) || "".equals(tmp1)) { tmp1 = ROOT_NAME + tmp1; } // Remove any file extensions if (tmp1.toLowerCase(Locale.ENGLISH).endsWith(".war") || tmp1.toLowerCase(Locale.ENGLISH).endsWith(".xml")) { tmp1 = tmp1.substring(0, tmp1.length() -4); } baseName = tmp1; String tmp2; // Extract version number int versionIndex = baseName.indexOf(VERSION_MARKER); if (versionIndex > -1) { version = baseName.substring(versionIndex + 2); tmp2 = baseName.substring(0, versionIndex); } else { version = ""; tmp2 = baseName; } if (ROOT_NAME.equals(tmp2)) { path = ""; } else { path = "/" + tmp2.replaceAll(FWD_SLASH_REPLACEMENT, "/"); } if (versionIndex > -1) { this.name = path + VERSION_MARKER + version; } else { this.name = path; } } /** * Construct an instance from a path and version. * * @param path Context path to use * @param version Context version to use */ public ContextName(String path, String version) { // Path should never be null, '/' or '/ROOT' if (path == null || "/".equals(path) || "/ROOT".equals(path)) { this.path = ""; } else { this.path = path; } // Version should never be null if (version == null) { this.version = ""; } else { this.version = version; } // Name is path + version if ("".equals(this.version)) { name = this.path; } else { name = this.path + VERSION_MARKER + this.version; } // Base name is converted path + version StringBuilder tmp = new StringBuilder(); if ("".equals(this.path)) { tmp.append(ROOT_NAME); } else { tmp.append(this.path.substring(1).replaceAll("/", FWD_SLASH_REPLACEMENT)); } if (this.version.length() > 0) { tmp.append(VERSION_MARKER); tmp.append(this.version); } this.baseName = tmp.toString(); } public String getBaseName() { return baseName; } public String getPath() { return path; } public String getVersion() { return version; } public String getName() { return name; } public String getDisplayName() { StringBuilder tmp = new StringBuilder(); if ("".equals(path)) { tmp.append('/'); } else { tmp.append(path); } if (!"".equals(version)) { tmp.append(VERSION_MARKER); tmp.append(version); } return tmp.toString(); } @Override public String toString() { return getDisplayName(); } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
test/org/apache/catalina/startup/TestHostConfigAutomaticDeployment.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.FileOutputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.attribute.BasicFileAttributes; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.Host; import org.apache.catalina.Lifecycle; import org.apache.catalina.LifecycleEvent; import org.apache.catalina.LifecycleListener; import org.apache.catalina.LifecycleState; import org.apache.catalina.core.StandardContext; import org.apache.catalina.core.StandardHost; import org.apache.catalina.util.ContextName; /** * The purpose of this class is to test the automatic deployment features of the * {@link HostConfig} implementation. */ public class TestHostConfigAutomaticDeployment extends TomcatBaseTest { private static final ContextName APP_NAME = new ContextName("myapp"); private static final File XML_SOURCE = new File("test/deployment/context.xml"); private static final File WAR_XML_SOURCE = new File("test/deployment/context.war"); private static final File WAR_XML_COPYXML_FALSE_SOURCE = new File("test/deployment/contextCopyXMLFalse.war"); private static final File WAR_XML_COPYXML_TRUE_SOURCE = new File("test/deployment/contextCopyXMLTrue.war"); private static final File WAR_XML_UNPACKWAR_FALSE_SOURCE = new File("test/deployment/contextUnpackWARFalse.war"); private static final File WAR_XML_UNPACKWAR_TRUE_SOURCE = new File("test/deployment/contextUnpackWARTrue.war"); private static final File WAR_SOURCE = new File("test/deployment/noContext.war"); private static final File WAR_BROKEN_SOURCE = new File("test/deployment/broken.war"); private static final File DIR_XML_SOURCE = new File("test/deployment/dirContext"); private static final File DIR_XML_SOURCE_META_INF = new File("test/deployment/dirContext/META-INF"); private static final File DIR_SOURCE = new File("test/deployment/dirNoContext"); private static final int XML = 1; private static final int EXT = 2; private static final int WAR = 3; private static final int DIR = 4; private static final int DIR_XML = 5; private static final int NONE = 1; private static final int RELOAD = 2; private static final int REDEPLOY = 3; private static final String XML_COOKIE_NAME = "XML_CONTEXT"; private static final String WAR_COOKIE_NAME = "WAR_CONTEXT"; private static final String DIR_COOKIE_NAME = "DIR_CONTEXT"; // private static final String DEFAULT_COOKIE_NAME = "JSESSIONID"; private File external; @Override public void setUp() throws Exception { super.setUp(); Tomcat tomcat = getTomcatInstance(); external = new File(getTemporaryDirectory(), "external"); if (!external.exists() && !external.mkdir()) { Assert.fail("Unable to create external for test"); } // Disable background thread tomcat.getEngine().setBackgroundProcessorDelay(-1); // Enable deployer tomcat.getHost().addLifecycleListener(new HostConfig()); // Disable deployment on start up tomcat.getHost().setDeployOnStartup(false); // Clean-up after test addDeleteOnTearDown(new File(tomcat.basedir, "/conf")); addDeleteOnTearDown(external); } /* * Expected behaviour for deployment of an XML file. * deployXML copyXML unpackWARs XML WAR DIR * Y/N Y/N Y/N Y N N * * Note: Context will fail to start because no valid docBase is present. */ @Test public void testDeploymentXmlFFF() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(false, false, false, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlFFT() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(false, false, true, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlFTF() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(false, true, false, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlFTT() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(false, true, true, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlTFF() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(true, false, false, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlTFT() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(true, false, true, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlTTF() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(true, true, false, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlTTT() throws Exception { createXmlInConfigBaseForAppbase(); doTestDeployment(true, true, true, LifecycleState.FAILED, XML_COOKIE_NAME, true, false, false); } /* * Expected behaviour for deployment of an XML file that points to an * external WAR. * deployXML copyXML unpackWARs XML WAR DIR * Y/N Y/N Y Y N Y * Y/N Y/N N Y N N * * Notes: No WAR file is present in the appBase because it is an external * WAR. * Any context.xml file embedded in the external WAR file is ignored. */ @Test public void testDeploymentXmlExternalWarXmlFFF() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(false, false, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalWarXmlFFT() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(false, false, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, true); } @Test public void testDeploymentXmlExternalWarXmlFTF() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(false, true, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalWarXmlFTT() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(false, true, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, true); } @Test public void testDeploymentXmlExternalWarXmlTFF() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(true, false, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalWarXmlTFT() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(true, false, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, true); } @Test public void testDeploymentXmlExternalWarXmlTTF() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(true, true, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalWarXmlTTT() throws Exception { File war = createWar(WAR_XML_SOURCE, false); createXmlInConfigBaseForExternal(war); doTestDeployment(true, true, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, true); } /* * Expected behaviour for deployment of an XML file that points to an * external DIR. * deployXML copyXML unpackWARs XML WAR DIR * Y/N Y/N Y/N Y N N * * Notes: Any context.xml file embedded in the external DIR file is ignored. */ @Test public void testDeploymentXmlExternalDirXmlFFF() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(false, false, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlFFT() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(false, false, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlFTF() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(false, true, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlFTT() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(false, true, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlTFF() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(true, false, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlTFT() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(true, false, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlTTF() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(true, true, false, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } @Test public void testDeploymentXmlExternalDirXmlTTT() throws Exception { File dir = createDirInExternal(true); createXmlInConfigBaseForExternal(dir); doTestDeployment(true, true, true, LifecycleState.STARTED, XML_COOKIE_NAME, true, false, false); } /* * Expected behaviour for deployment of a WAR with an embedded XML file. * deployXML copyXML unpackWARs XML WAR DIR * N Y/N N N Y N * N Y/N Y N Y Y * Y N N N Y N * Y N Y N Y Y * Y Y N Y Y N * Y Y Y Y Y Y */ @Test public void testDeploymentWarXmlFFF() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(false, false, false, LifecycleState.FAILED, null, false, true, false); } @Test public void testDeploymentWarXmlFFT() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(false, false, true, LifecycleState.FAILED, null, false, true, true); } @Test public void testDeploymentWarXmlFTF() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(false, true, false, LifecycleState.FAILED, null, false, true, false); } @Test public void testDeploymentWarXmlFTT() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(false, true, true, LifecycleState.FAILED, null, false, true, true); } @Test public void testDeploymentWarXmlTFF() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(true, false, false, LifecycleState.STARTED, WAR_COOKIE_NAME, false, true, false); } @Test public void testDeploymentWarXmlTFT() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(true, false, true, LifecycleState.STARTED, WAR_COOKIE_NAME, false, true, true); } @Test public void testDeploymentWarXmlTTF() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(true, true, false, LifecycleState.STARTED, WAR_COOKIE_NAME, true, true, false); } @Test public void testDeploymentWarXmlTTT() throws Exception { createWar(WAR_XML_SOURCE, true); doTestDeployment(true, true, true, LifecycleState.STARTED, WAR_COOKIE_NAME, true, true, true); } /* * Expected behaviour for deployment of a WAR without an embedded XML file. * deployXML copyXML unpackWARs XML WAR DIR * Y/N Y/N N N Y N * Y/N Y/N Y N Y Y */ @Test public void testDeploymentWarFFF() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(false, false, false, LifecycleState.STARTED, null, false, true, false); } @Test public void testDeploymentWarFFT() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(false, false, true, LifecycleState.STARTED, null, false, true, true); } @Test public void testDeploymentWarFTF() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(false, true, false, LifecycleState.STARTED, null, false, true, false); } @Test public void testDeploymentWarFTT() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(false, true, true, LifecycleState.STARTED, null, false, true, true); } @Test public void testDeploymentWarTFF() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(true, false, false, LifecycleState.STARTED, null, false, true, false); } @Test public void testDeploymentWarTFT() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(true, false, true, LifecycleState.STARTED, null, false, true, true); } @Test public void testDeploymentWarTTF() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(true, true, false, LifecycleState.STARTED, null, false, true, false); } @Test public void testDeploymentWarTTT() throws Exception { createWar(WAR_SOURCE, true); doTestDeployment(true, true, true, LifecycleState.STARTED, null, false, true, true); } /* * Expected behaviour for deployment of a DIR with an embedded XML file. * deployXML copyXML unpackWARs XML WAR DIR * N Y/N Y/N N N Y * Y N Y/N N N Y * Y Y Y/N Y N Y */ @Test public void testDeploymentDirXmlFFF() throws Exception { createDirInAppbase(true); doTestDeployment(false, false, false, LifecycleState.FAILED, null, false, false, true); } @Test public void testDeploymentDirXmlFFT() throws Exception { createDirInAppbase(true); doTestDeployment(false, false, true, LifecycleState.FAILED, null, false, false, true); } @Test public void testDeploymentDirXmlFTF() throws Exception { createDirInAppbase(true); doTestDeployment(false, true, false, LifecycleState.FAILED, null, false, false, true); } @Test public void testDeploymentDirXmlFTT() throws Exception { createDirInAppbase(true); doTestDeployment(false, true, true, LifecycleState.FAILED, null, false, false, true); } @Test public void testDeploymentDirXmlTFF() throws Exception { createDirInAppbase(true); doTestDeployment(true, false, false, LifecycleState.STARTED, DIR_COOKIE_NAME, false, false, true); } @Test public void testDeploymentDirXmlTFT() throws Exception { createDirInAppbase(true); doTestDeployment(true, false, true, LifecycleState.STARTED, DIR_COOKIE_NAME, false, false, true); } @Test public void testDeploymentDirXmlTTF() throws Exception { createDirInAppbase(true); doTestDeployment(true, true, false, LifecycleState.STARTED, DIR_COOKIE_NAME, true, false, true); } @Test public void testDeploymentDirXmlTTT() throws Exception { createDirInAppbase(true); doTestDeployment(true, true, true, LifecycleState.STARTED, DIR_COOKIE_NAME, true, false, true); } /* * Expected behaviour for deployment of a DIR without an embedded XML file. * deployXML copyXML unpackWARs XML WAR DIR * Y/N Y/N Y/N N N Y */ @Test public void testDeploymentDirFFF() throws Exception { createDirInAppbase(false); doTestDeployment(false, false, false, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirFFT() throws Exception { createDirInAppbase(false); doTestDeployment(false, false, true, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirFTF() throws Exception { createDirInAppbase(false); doTestDeployment(false, true, false, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirFTT() throws Exception { createDirInAppbase(false); doTestDeployment(false, true, true, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirTFF() throws Exception { createDirInAppbase(false); doTestDeployment(true, false, false, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirTFT() throws Exception { createDirInAppbase(false); doTestDeployment(true, false, true, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirTTF() throws Exception { createDirInAppbase(false); doTestDeployment(true, true, false, LifecycleState.STARTED, null, false, false, true); } @Test public void testDeploymentDirTTT() throws Exception { createDirInAppbase(false); doTestDeployment(true, true, true, LifecycleState.STARTED, null, false, false, true); } private void doTestDeployment(boolean deployXML, boolean copyXML, boolean unpackWARs, LifecycleState resultState, String cookieName, boolean resultXml, boolean resultWar, boolean resultDir) throws Exception { Tomcat tomcat = getTomcatInstance(); // Start the instance tomcat.start(); // Set the attributes StandardHost host = (StandardHost) tomcat.getHost(); host.setDeployXML(deployXML); host.setCopyXML(copyXML); host.setUnpackWARs(unpackWARs); // Trigger automatic deployment host.backgroundProcess(); // Test the results Context ctxt = (Context) tomcat.getHost().findChild(APP_NAME.getPath()); if (resultState == null) { Assert.assertNull(ctxt); } else { Assert.assertNotNull(ctxt); Assert.assertEquals(resultState, ctxt.getState()); Assert.assertEquals(cookieName, ctxt.getSessionCookieName()); } File xml = new File( host.getConfigBaseFile(), APP_NAME.getBaseName() + ".xml"); Assert.assertEquals( Boolean.valueOf(resultXml), Boolean.valueOf(xml.isFile())); File war = new File( host.getAppBaseFile(), APP_NAME.getBaseName() + ".war"); Assert.assertEquals( Boolean.valueOf(resultWar), Boolean.valueOf(war.isFile())); File dir = new File(host.getAppBase(), APP_NAME.getBaseName()); Assert.assertEquals( Boolean.valueOf(resultDir), Boolean.valueOf(dir.isDirectory())); } /* * Expected behaviour for the deletion of files. * * Artifacts present Artifact Artifacts remaining * XML WAR EXT DIR Removed XML WAR EXT DIR Notes * N N N Y DIR - - - N * N Y N N WAR - N - - * N Y N Y DIR - Y - R 1 * N Y N Y WAR - N - N * Y N N N XML N - - - * Y N N Y DIR N - - N * Y N N Y XML R - - Y 2 * Y N Y N EXT Y - N - * Y N Y N XML N - Y - * Y N Y Y DIR R - Y R 1,2 * Y N Y Y EXT Y - N N * Y N Y Y XML N - Y N * Y Y N N WAR N N - - * Y Y N N XML N N - - * Y Y N Y DIR R Y - R 1,2 * Y Y N Y WAR N N - - * Y Y N Y XML R Y - Y * * Notes: 1. The DIR will be re-created since unpackWARs is true. * 2. The XML will be extracted from the WAR/DIR if deployXML and * copyXML are true. */ @Test public void testDeleteDirRemoveDir() throws Exception { doTestDelete(false, false, false, false, true, DIR, false, false, false, null); } @Test public void testDeleteWarRemoveWar() throws Exception { doTestDelete(false, false, false, true, false, WAR, false, false, false, null); } @Test public void testDeleteWarDirRemoveDir() throws Exception { doTestDelete(false, false, false, true, true, DIR, false, true, true, WAR_COOKIE_NAME); } @Test public void testDeleteWarDirRemoveWar() throws Exception { doTestDelete(false, false, false, true, true, WAR, false, false, false, null); } @Test public void testDeleteXmlRemoveXml() throws Exception { doTestDelete(true, false, false, false, false, XML, false, false, false, null); } @Test public void testDeleteXmlDirRemoveDir() throws Exception { doTestDelete(true, false, false, false, true, DIR, false, false, false, null); } @Test public void testDeleteXmlDirRemoveXml() throws Exception { doTestDelete(true, false, false, false, true, XML, false, false, true, DIR_COOKIE_NAME); } @Test public void testDeleteXmlDirRemoveXmlCopyXml() throws Exception { ((StandardHost) getTomcatInstance().getHost()).setCopyXML(true); doTestDelete(true, false, false, false, true, XML, true, false, true, DIR_COOKIE_NAME); } @Test public void testDeleteXmlExtwarRemoveExt() throws Exception { doTestDelete(true, true, false, false, false, EXT, true, false, false, XML_COOKIE_NAME); } @Test public void testDeleteXmlExtdirRemoveExt() throws Exception { doTestDelete(true, false, true, false, false, EXT, true, false, false, XML_COOKIE_NAME); } @Test public void testDeleteXmlExtwarRemoveXml() throws Exception { doTestDelete(true, true, false, false, false, XML, false, false, false, null); } @Test public void testDeleteXmlExtdirRemoveXml() throws Exception { doTestDelete(true, false, true, false, false, XML, false, false, false, null); } @Test public void testDeleteXmlExtwarDirRemoveDir() throws Exception { doTestDelete(true, true, false, false, true, DIR, true, false, true, XML_COOKIE_NAME); } @Test public void testDeleteXmlExtwarDirRemoveExt() throws Exception { doTestDelete(true, true, false, false, true, EXT, true, false, false, XML_COOKIE_NAME); } @Test public void testDeleteXmlExtwarDirRemoveXml() throws Exception { doTestDelete(true, true, false, false, true, XML, false, false, false, null); } @Test public void testDeleteXmlWarRemoveWar() throws Exception { doTestDelete(true, false, false, true, false, WAR, false, false, false, null); } @Test public void testDeleteXmlWarRemoveXml() throws Exception { doTestDelete(true, false, false, true, false, XML, false, true, false, WAR_COOKIE_NAME); } @Test public void testDeleteXmlWarRemoveXmlCopyXml() throws Exception { ((StandardHost) getTomcatInstance().getHost()).setCopyXML(true); doTestDelete(true, false, false, true, false, XML, true, true, false, WAR_COOKIE_NAME); } @Test public void testDeleteXmlWarDirRemoveDir() throws Exception { doTestDelete(true, false, false, true, true, DIR, false, true, true, WAR_COOKIE_NAME); } @Test public void testDeleteXmlWarDirRemoveDirCopyXml() throws Exception { ((StandardHost) getTomcatInstance().getHost()).setCopyXML(true); doTestDelete(true, false, false, true, true, DIR, true, true, true, WAR_COOKIE_NAME); } @Test public void testDeleteXmlWarDirRemoveWar() throws Exception { doTestDelete(true, false, false, true, true, WAR, false, false, false, null); } @Test public void testDeleteXmlWarDirRemoveWarCopyXml() throws Exception { ((StandardHost) getTomcatInstance().getHost()).setCopyXML(true); doTestDelete(true, false, false, true, true, WAR, false, false, false, null); } @Test public void testDeleteXmlWarDirRemoveXml() throws Exception { doTestDelete(true, false, false, true, true, XML, false, true, true, DIR_COOKIE_NAME); } @Test public void testDeleteXmlWarDirRemoveXmlCopyXml() throws Exception { ((StandardHost) getTomcatInstance().getHost()).setCopyXML(true); doTestDelete(true, false, false, true, true, XML, true, true, true, WAR_COOKIE_NAME); } private void doTestDelete(boolean startXml, boolean startExternalWar, boolean startExternalDir, boolean startWar, boolean startDir, int toDelete, boolean resultXml, boolean resultWar, boolean resultDir, String resultCookieName) throws Exception { Tomcat tomcat = getTomcatInstance(); StandardHost host = (StandardHost) tomcat.getHost(); // Init File xml = null; File ext = null; File war = null; File dir = null; if (startXml && !startExternalWar && !startExternalDir) { xml = createXmlInConfigBaseForAppbase(); } if (startExternalWar) { ext = createWar(WAR_XML_SOURCE, false); xml = createXmlInConfigBaseForExternal(ext); } if (startExternalDir) { ext = createDirInExternal(true); xml = createXmlInConfigBaseForExternal(ext); } if (startWar) { war = createWar(WAR_XML_SOURCE, true); } if (startDir) { dir = createDirInAppbase(true); } if ((startWar || startExternalWar) && !startDir) { host.setUnpackWARs(false); } // Deploy the files we copied tomcat.start(); host.backgroundProcess(); // Remove the specified file switch (toDelete) { case XML: ExpandWar.delete(xml); break; case EXT: ExpandWar.delete(ext); break; case WAR: ExpandWar.delete(war); break; case DIR: ExpandWar.delete(dir); break; default: Assert.fail(); } // Trigger an auto-deployment cycle host.backgroundProcess(); Context ctxt = (Context) host.findChild(APP_NAME.getName()); // Check the results // External WAR and DIR should only be deleted if the test is testing // behaviour when the external resource is deleted if (toDelete == EXT) { if (ext == null) { Assert.fail(); } else { Assert.assertFalse(ext.exists()); } } else { if (startExternalWar) { if (ext == null) { Assert.fail(); } else { Assert.assertTrue(ext.isFile()); } } if (startExternalDir) { if (ext == null) { Assert.fail(); } else { Assert.assertTrue(ext.isDirectory()); } } } if (resultXml) { if (xml == null) { Assert.fail(); } else { Assert.assertTrue(xml.isFile()); } } if (resultWar) { if (war == null) { Assert.fail(); } else { Assert.assertTrue(war.isFile()); } } if (resultDir) { if (dir == null) { Assert.fail(); } else { Assert.assertTrue(dir.isDirectory()); } } if (!resultXml && (startExternalWar || startExternalDir)) { Assert.assertNull(ctxt); } if (!resultWar && !resultDir) { if (resultXml) { Assert.assertEquals(LifecycleState.FAILED, ctxt.getState()); } else { Assert.assertNull(ctxt); } } if (ctxt != null) { Assert.assertEquals(resultCookieName, ctxt.getSessionCookieName()); } } /* * Expected behaviour for modification of files. * * Artifacts present Artifact Artifacts remaining * XML WAR EXT DIR Modified XML WAR EXT DIR Action * N N N Y DIR - - - M None * N Y N N WAR - M - - Redeploy * N Y N Y DIR - Y - M None * N Y N Y WAR - M - R Redeploy * Y N N N XML M - - - Redeploy * Y N N Y DIR Y - - M None * Y N N Y XML M - - Y Redeploy * Y N Y N EXT Y - M - Reload if WAR * Y N Y N XML M - Y - Redeploy * Y N Y Y DIR Y - Y M None * Y N Y Y EXT Y - M R Reload * Y N Y Y XML M - Y Y Redeploy * Y Y N N WAR Y M - - Reload * Y Y N N XML M Y - - Redeploy * Y Y N Y DIR Y Y - M None * Y Y N Y WAR Y M - - Reload * Y Y N Y XML M Y - Y Redeploy */ @Test public void testModifyDirUpdateDir() throws Exception { doTestModify(false, false, false, false, true, DIR, false, false, true, DIR_COOKIE_NAME, NONE); } @Test public void testModifyWarUpdateWar() throws Exception { doTestModify(false, false, false, true, false, WAR, false, true, false, WAR_COOKIE_NAME, REDEPLOY); } @Test public void testModifyWarDirUpdateDir() throws Exception { // DIR_COOKIE_NAME since Tomcat is going to assume DIR is expanded WAR doTestModify(false, false, false, true, true, DIR, false, true, true, DIR_COOKIE_NAME, NONE); } @Test public void testModifyWarDirUpdateWar() throws Exception { doTestModify(false, false, false, true, true, WAR, false, true, true, WAR_COOKIE_NAME, REDEPLOY); } @Test public void testModifyXmlUpdateXml() throws Exception { doTestModify(true, false, false, false, false, XML, true, false, false, XML_COOKIE_NAME, REDEPLOY, LifecycleState.FAILED); } @Test public void testModifyXmlDirUpdateDir() throws Exception { doTestModify(true, false, false, false, true, DIR, true, false, true, XML_COOKIE_NAME, NONE); } @Test public void testModifyXmlDirUpdateXml() throws Exception { doTestModify(true, false, false, false, true, XML, true, false, true, XML_COOKIE_NAME, REDEPLOY); } @Test public void testModifyXmlExtwarUpdateExtwar() throws Exception { doTestModify(true, true, false, false, false, EXT, true, false, false, XML_COOKIE_NAME, RELOAD); } @Test public void testModifyXmlExtdirUpdateExtdir() throws Exception { doTestModify(true, false, true, false, false, EXT, true, false, false, XML_COOKIE_NAME, NONE); } @Test public void testModifyXmlExtwarUpdateXml() throws Exception { doTestModify(true, true, false, false, false, XML, true, false, false, XML_COOKIE_NAME, REDEPLOY); } @Test public void testModifyXmlExtdirUpdateXml() throws Exception { doTestModify(true, false, true, false, false, XML, true, false, false, XML_COOKIE_NAME, REDEPLOY); } @Test public void testModifyXmlExtwarDirUpdateDir() throws Exception { doTestModify(true, true, false, false, true, DIR, true, false, false, XML_COOKIE_NAME, NONE); } @Test public void testModifyXmlExtwarDirUpdateExt() throws Exception { doTestModify(true, true, false, false, true, EXT, true, false, true, XML_COOKIE_NAME, RELOAD); } @Test public void testModifyXmlExtwarDirUpdateXml() throws Exception { doTestModify(true, true, false, false, true, XML, true, false, false, XML_COOKIE_NAME, REDEPLOY); } @Test public void testModifyXmlWarUpdateWar() throws Exception { doTestModify(true, false, false, true, false, WAR, true, true, false, XML_COOKIE_NAME, RELOAD); } @Test public void testModifyXmlWarUpdateXml() throws Exception { doTestModify(true, false, false, true, false, XML, true, true, false, XML_COOKIE_NAME, REDEPLOY); } @Test public void testModifyXmlWarDirUpdateDir() throws Exception { doTestModify(true, false, false, true, true, DIR, true, true, true, XML_COOKIE_NAME, NONE); } @Test public void testModifyXmlWarDirUpdateWar() throws Exception { doTestModify(true, false, false, true, true, WAR, true, true, true, XML_COOKIE_NAME, RELOAD); } @Test public void testModifyXmlWarDirUpdateXml() throws Exception { doTestModify(true, false, false, true, true, XML, true, true, true, XML_COOKIE_NAME, REDEPLOY); } private void doTestModify(boolean startXml, boolean startExternalWar, boolean startExternalDir, boolean startWar, boolean startDir, int toModify, boolean resultXml, boolean resultWar, boolean resultDir, String resultCookieName, int resultAction) throws Exception { doTestModify(startXml, startExternalWar, startExternalDir, startWar, startDir, toModify, resultXml, resultWar, resultDir, resultCookieName, resultAction, LifecycleState.STARTED); } private void doTestModify(boolean startXml, boolean startExternalWar, boolean startExternalDir, boolean startWar, boolean startDir, int toModify, boolean resultXml, boolean resultWar, boolean resultDir, String resultCookieName, int resultAction, LifecycleState resultState) throws Exception { Tomcat tomcat = getTomcatInstance(); StandardHost host = (StandardHost) tomcat.getHost(); // Init File xml = null; File ext = null; File war = null; File dir = null; if (startXml && !startExternalWar && !startExternalDir) { xml = createXmlInConfigBaseForAppbase(); } if (startExternalWar) { ext = createWar(WAR_XML_SOURCE, false); xml = createXmlInConfigBaseForExternal(ext); } if (startExternalDir) { ext = createDirInAppbase(true); xml = createXmlInConfigBaseForExternal(ext); } if (startWar) { war = createWar(WAR_XML_SOURCE, true); } if (startDir) { dir = createDirInAppbase(true); } if ((startWar || startExternalWar) && !startDir) { host.setUnpackWARs(false); } // Deploy the files we copied tomcat.start(); host.backgroundProcess(); // Update the last modified time. Add a few seconds to make sure that // the OS reports a change in modification time. switch (toModify) { case XML: if (xml == null) { Assert.fail(); } else { xml.setLastModified(System.currentTimeMillis() + 5000); } break; case EXT: if (ext == null) { Assert.fail(); } else { ext.setLastModified(System.currentTimeMillis() + 5000); } break; case WAR: if (war == null) { Assert.fail(); } else { war.setLastModified(System.currentTimeMillis() + 5000); } break; case DIR: if (dir == null) { Assert.fail(); } else { dir.setLastModified(System.currentTimeMillis() + 5000); } break; default: Assert.fail(); } Context oldContext = (Context) host.findChild(APP_NAME.getName()); StateTracker tracker = new StateTracker(); oldContext.addLifecycleListener(tracker); // Trigger an auto-deployment cycle host.backgroundProcess(); Context newContext = (Context) host.findChild(APP_NAME.getName()); // Check the results if (resultXml) { if (xml == null) { Assert.fail(); } else { Assert.assertTrue(xml.isFile()); } } if (resultWar) { if (war == null) { Assert.fail(); } else { Assert.assertTrue(war.isFile()); } } if (resultDir) { if (dir == null) { Assert.fail(); } else { Assert.assertTrue(dir.isDirectory()); } } if (!resultXml && (startExternalWar || startExternalDir)) { Assert.assertNull(newContext); } if (!resultWar && !resultDir) { if (resultXml) { if (!startExternalWar && !startExternalDir) { Assert.assertEquals(LifecycleState.FAILED, newContext.getState()); } else { Assert.assertEquals(LifecycleState.STARTED, newContext.getState()); } } else { Assert.assertNull(newContext); } } if (newContext != null) { Assert.assertEquals(resultCookieName, newContext.getSessionCookieName()); Assert.assertEquals(resultState, newContext.getState()); } if (resultAction == NONE) { Assert.assertSame(oldContext, newContext); Assert.assertEquals("", tracker.getHistory()); } else if (resultAction == RELOAD) { Assert.assertSame(oldContext, newContext); Assert.assertEquals("stopstart", tracker.getHistory()); } else if (resultAction == REDEPLOY) { Assert.assertNotSame(oldContext, newContext); // No init or start as that will be in a new context object Assert.assertEquals("stopafter_destroy", tracker.getHistory()); } else { Assert.fail(); } } /* * Expected behaviour for the addition of files. * * Artifacts present copyXML deployXML Artifact Artifacts remaining * XML WAR EXT DIR Added XML WAR EXT DIR Action * N Y N N N Y DIR - Y - A None * N N N Y N Y WAR - A - R Redeploy * Y N N N N Y DIR Y - - A None * N N N Y N Y XML A - - Y Redeploy * Y N N N N Y WAR Y A - - Reload * N Y N N N Y XML A Y - - Redeploy * Y Y N N N Y DIR Y Y - A None * Y N N Y N Y WAR Y A - N Reload * N Y N Y N Y XML A Y - Y Redeploy * Y N Y N N Y DIR Y - Y A None * Y N Y N N Y WAR Y A Y - None * N N N Y N Y EXT A - A R Redeploy * N Y N N N Y EXT A Y A - Redeploy * * N N N Y Y/N N DIR+XML - - - Y Redeploy (failed) * N N N Y Y Y DIR+XML A - - Y Redeploy * N N N Y N Y DIR+XML - - - Y Redeploy * * Addition of a file is treated as if the added file has been modified * with the following additional actions: * - If a WAR is added, any DIR is removed and may be recreated depending on * unpackWARs. * - If an XML file is added that refers to an external docBase any WAR or * DIR in the appBase will be removed. The DIR may be recreated if the * external resource is a WAR and unpackWARs is true. * - If a DIR is added when a WAR already exists and unpackWARs is false, * the DIR will be ignored but a warning will be logged when the DIR is * first detected. If the WAR is removed, the DIR will be left and may be * deployed via automatic deployment. * - If a WAR is added when an external WAR already exists for the same * context, the WAR will be treated the same way as a DIR is treated in * the previous bullet point. */ @Test public void testAdditionWarAddDir() throws Exception { doTestAddition(false, false, false, true, false, DIR, false, true, true, WAR_COOKIE_NAME, NONE); } @Test public void testAdditionDirAddWar() throws Exception { doTestAddition(false, false, false, false, true, WAR, false, true, true, WAR_COOKIE_NAME, REDEPLOY); } @Test public void testAdditionXmlAddDir() throws Exception { doTestAddition(true, false, false, false, false, DIR, true, false, true, XML_COOKIE_NAME, NONE); } @Test public void testAdditionDirAddXml() throws Exception { doTestAddition(false, false, false, false, true, XML, true, false, true, XML_COOKIE_NAME, REDEPLOY); } @Test public void testAdditionXmlAddWar() throws Exception { doTestAddition(true, false, false, false, false, WAR, true, true, false, XML_COOKIE_NAME, RELOAD); } @Test public void testAdditionWarAddXml() throws Exception { doTestAddition(false, false, false, true, false, XML, true, true, false, XML_COOKIE_NAME, REDEPLOY); } @Test public void testAdditionXmlWarAddDir() throws Exception { doTestAddition(true, false, false, true, false, DIR, true, true, true, XML_COOKIE_NAME, NONE); } @Test public void testAdditionXmlDirAddWar() throws Exception { doTestAddition(true, false, false, false, true, WAR, true, true, false, XML_COOKIE_NAME, RELOAD); } @Test public void testAdditionWarDirAddXml() throws Exception { doTestAddition(false, false, false, true, true, XML, true, true, true, XML_COOKIE_NAME, REDEPLOY); } @Test public void testAdditionXmlExtwarAddDir() throws Exception { doTestAddition(true, true, false, false, false, DIR, true, false, true, XML_COOKIE_NAME, NONE); } @Test public void testAdditionXmlExtdirAddDir() throws Exception { doTestAddition(true, false, true, false, false, DIR, true, false, true, XML_COOKIE_NAME, NONE); } @Test public void testAdditionXmlExtwarAddWar() throws Exception { doTestAddition(true, true, false, false, false, WAR, true, true, false, XML_COOKIE_NAME, NONE); } @Test public void testAdditionXmlExtdirAddWar() throws Exception { doTestAddition(true, false, true, false, false, WAR, true, true, false, XML_COOKIE_NAME, NONE); } @Test public void testAdditionDirAddXmlExtwar() throws Exception { doTestAddition(false, false, false, false, true, EXT, true, false, true, XML_COOKIE_NAME, REDEPLOY); } @Test public void testAdditionWarAddXmlExtwar() throws Exception { doTestAddition(false, false, false, true, false, EXT, true, true, false, XML_COOKIE_NAME, REDEPLOY); } @Test public void testAdditionDirAddDirXmlTF() throws Exception { doTestAddition(false, false, false, false, true, true, false, DIR_XML, false, false, true, null, REDEPLOY, LifecycleState.FAILED); } @Test public void testAdditionDirAddDirXmlFF() throws Exception { doTestAddition(false, false, false, false, true, false, false, DIR_XML, false, false, true, null, REDEPLOY, LifecycleState.FAILED); } @Test public void testAdditionDirAddDirXmlTT() throws Exception { doTestAddition(false, false, false, false, true, true, true, DIR_XML, true, false, true, DIR_COOKIE_NAME, REDEPLOY, LifecycleState.STARTED); } @Test public void testAdditionDirAddDirXmlFT() throws Exception { doTestAddition(false, false, false, false, true, false, true, DIR_XML, false, false, true, DIR_COOKIE_NAME, REDEPLOY, LifecycleState.STARTED); } private void doTestAddition(boolean startXml, boolean startExternalWar, boolean startExternalDir, boolean startWar, boolean startDir, int toAdd, boolean resultXml, boolean resultWar, boolean resultDir, String resultCookieName, int resultAction) throws Exception { doTestAddition(startXml, startExternalWar, startExternalDir, startWar, startDir, false, true, toAdd, resultXml, resultWar, resultDir, resultCookieName, resultAction, LifecycleState.STARTED); } private void doTestAddition(boolean startXml, boolean startExternalWar, boolean startExternalDir, boolean startWar, boolean startDir, boolean copyXML, boolean deployXML, int toAdd, boolean resultXml, boolean resultWar, boolean resultDir, String resultCookieName, int resultAction, LifecycleState state) throws Exception { Tomcat tomcat = getTomcatInstance(); StandardHost host = (StandardHost) tomcat.getHost(); // Init File xml = null; File ext = null; File war = null; File dir = null; if (startXml && !startExternalWar && !startExternalDir) { xml = createXmlInConfigBaseForAppbase(); } if (startExternalWar) { ext = createWar(WAR_XML_SOURCE, false); xml = createXmlInConfigBaseForExternal(ext); } if (startExternalDir) { ext = createDirInExternal(true); xml = createXmlInConfigBaseForExternal(ext); } if (startWar) { war = createWar(WAR_XML_SOURCE, true); } if (startDir) { dir = createDirInAppbase(toAdd != DIR_XML); } if ((startWar || startExternalWar) && !startDir) { host.setUnpackWARs(false); } host.setCopyXML(copyXML); host.setDeployXML(deployXML); // Deploy the files we copied tomcat.start(); host.backgroundProcess(); // Change the specified file switch (toAdd) { case XML: if (xml == null) { xml = createXmlInConfigBaseForAppbase(); } else { Assert.fail(); } break; case EXT: if (ext == null && xml == null) { ext = createWar(WAR_XML_SOURCE, false); xml = createXmlInConfigBaseForExternal(ext); } else { Assert.fail(); } break; case WAR: if (war == null) { war = createWar(WAR_XML_SOURCE, true); } else { Assert.fail(); } break; case DIR: if (dir == null) { dir = createDirInAppbase(true); } else { Assert.fail(); } break; case DIR_XML: dir = createDirXmlInAppbase(); xml = getXmlInConfigBaseForAppbase(); break; default: Assert.fail(); } Context oldContext = (Context) host.findChild(APP_NAME.getName()); StateTracker tracker = new StateTracker(); oldContext.addLifecycleListener(tracker); // Trigger an auto-deployment cycle host.backgroundProcess(); Context newContext = (Context) host.findChild(APP_NAME.getName()); // Check the results if (resultXml) { if (xml == null) { Assert.fail(); } else { Assert.assertTrue(xml.isFile()); } } if (resultWar) { if (war == null) { Assert.fail(); } else { Assert.assertTrue(war.isFile()); } } if (resultDir) { if (dir == null) { Assert.fail(); } else { Assert.assertTrue(dir.isDirectory()); } } if (!resultXml && (startExternalWar || startExternalDir)) { Assert.assertNull(newContext); } if (!resultWar && !resultDir) { if (resultXml) { if (!startExternalWar && !startExternalDir) { Assert.assertEquals(LifecycleState.FAILED, newContext.getState()); } else { Assert.assertEquals(LifecycleState.STARTED, newContext.getState()); } } else { Assert.assertNull(newContext); } } if (newContext != null) { Assert.assertEquals(resultCookieName, newContext.getSessionCookieName()); } if (resultAction == NONE) { Assert.assertSame(oldContext, newContext); Assert.assertEquals("", tracker.getHistory()); } else if (resultAction == RELOAD) { Assert.assertSame(oldContext, newContext); Assert.assertEquals("stopstart", tracker.getHistory()); } else if (resultAction == REDEPLOY) { if (newContext == null) { Assert.fail(); } else { Assert.assertEquals(state, newContext.getState()); } Assert.assertNotSame(oldContext, newContext); // No init or start as that will be in a new context object Assert.assertEquals("stopafter_destroy", tracker.getHistory()); } else { Assert.fail(); } } /* * Test context unpackWAR setting. * If context.getUnpackWAR != Host.getUnpackWARs the Host wins. */ @Test public void testUnpackWARFFF() throws Exception { doTestUnpackWAR(false, false, false, false); } @Test public void testUnpackWARFFT() throws Exception { doTestUnpackWAR(false, false, true, false); } @Test public void testUnpackWARFTF() throws Exception { doTestUnpackWAR(false, true, false, false); } @Test public void testUnpackWARFTT() throws Exception { doTestUnpackWAR(false, true, true, false); } @Test public void testUnpackWARTFF() throws Exception { doTestUnpackWAR(true, false, false, false); } @Test public void testUnpackWARTFT() throws Exception { // External WAR - therefore XML in WAR will be ignored doTestUnpackWAR(true, false, true, true); } @Test public void testUnpackWARTTF() throws Exception { doTestUnpackWAR(true, true, false, true); } @Test public void testUnpackWARTTT() throws Exception { doTestUnpackWAR(true, true, true, true); } private void doTestUnpackWAR(boolean unpackWARs, boolean unpackWAR, boolean external, boolean resultDir) throws Exception { Tomcat tomcat = getTomcatInstance(); StandardHost host = (StandardHost) tomcat.getHost(); host.setUnpackWARs(unpackWARs); tomcat.start(); File war; if (unpackWAR) { war = createWar(WAR_XML_UNPACKWAR_TRUE_SOURCE, !external); } else { war = createWar(WAR_XML_UNPACKWAR_FALSE_SOURCE, !external); } if (external) { createXmlInConfigBaseForExternal(war); } host.backgroundProcess(); File dir = new File(host.getAppBase(), APP_NAME.getBaseName()); Assert.assertEquals( Boolean.valueOf(resultDir), Boolean.valueOf(dir.isDirectory())); } @Test public void testBrokenAppWithAntiLockingF() throws Exception { testBrokenAppWithAntiLocking(false); } @Test public void testBrokenAppWithAntiLockingT() throws Exception { testBrokenAppWithAntiLocking(true); } private void testBrokenAppWithAntiLocking(boolean unpackWARs) throws Exception { Tomcat tomcat = getTomcatInstance(); StandardHost host = (StandardHost) tomcat.getHost(); host.setUnpackWARs(unpackWARs); File war = createWar(WAR_BROKEN_SOURCE, false); createXmlInConfigBaseForExternal(war, true); File dir = new File(host.getAppBaseFile(), APP_NAME.getBaseName()); tomcat.start(); // Simulate deploy on start-up tomcat.getHost().backgroundProcess(); Assert.assertTrue(war.isFile()); if (unpackWARs) { Assert.assertTrue(dir.isDirectory()); } } private File createDirInAppbase(boolean withXml) throws IOException { File dir = new File(getTomcatInstance().getHost().getAppBaseFile(), APP_NAME.getBaseName()); if (withXml) { recurrsiveCopy(DIR_XML_SOURCE.toPath(), dir.toPath()); } else { recurrsiveCopy(DIR_SOURCE.toPath(), dir.toPath()); } return dir; } private File createDirXmlInAppbase() throws IOException { File dir = new File(getTomcatInstance().getHost().getAppBaseFile(), APP_NAME.getBaseName() + "/META-INF"); recurrsiveCopy(DIR_XML_SOURCE_META_INF.toPath(), dir.toPath()); return dir; } private File createDirInExternal(boolean withXml) throws IOException { File ext = new File(external, "external" + ".war"); if (withXml) { recurrsiveCopy(DIR_XML_SOURCE.toPath(), ext.toPath()); } else { recurrsiveCopy(DIR_SOURCE.toPath(), ext.toPath()); } return ext; } private File createWar(File src, boolean useAppbase) throws IOException { File dest; if (useAppbase) { dest = new File(getTomcatInstance().getHost().getAppBaseFile(), APP_NAME.getBaseName() + ".war"); } else { dest = new File(external, "external" + ".war"); } Files.copy(src.toPath(), dest.toPath()); return dest; } private File createXmlInConfigBaseForAppbase() throws IOException { File xml = getXmlInConfigBaseForAppbase(); File parent = xml.getParentFile(); if (!parent.isDirectory()) { Assert.assertTrue(parent.mkdirs()); } Files.copy(XML_SOURCE.toPath(), xml.toPath()); return xml; } private File getXmlInConfigBaseForAppbase() { Host host = getTomcatInstance().getHost(); return new File(host.getConfigBaseFile(), APP_NAME + ".xml"); } private File createXmlInConfigBaseForExternal(File ext) throws IOException { return createXmlInConfigBaseForExternal(ext, false); } private File createXmlInConfigBaseForExternal(File ext, boolean antiLocking) throws IOException { File xml = new File(getTomcatInstance().getHost().getConfigBaseFile(), APP_NAME + ".xml"); File parent = xml.getParentFile(); if (!parent.isDirectory()) { Assert.assertTrue(parent.mkdirs()); } try (FileOutputStream fos = new FileOutputStream(xml)) { StringBuilder context = new StringBuilder(); context.append("<Context sessionCookieName=\""); context.append(XML_COOKIE_NAME); context.append("\" docBase=\""); context.append(ext.getAbsolutePath()); if (antiLocking) { context.append("\" antiResourceLocking=\"true"); } context.append("\" />"); fos.write(context.toString().getBytes(StandardCharsets.ISO_8859_1)); } return xml; } private static void recurrsiveCopy(final Path src, final Path dest) throws IOException { Files.walkFileTree(src, new FileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { Files.copy(dir, dest.resolve(src.relativize(dir))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Files.copy(file, dest.resolve(src.relativize(file))); return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException ioe) throws IOException { throw ioe; } @Override public FileVisitResult postVisitDirectory(Path dir, IOException ioe) throws IOException { // NO-OP return FileVisitResult.CONTINUE; }}); } private static class StateTracker implements LifecycleListener { private StringBuilder stateHistory = new StringBuilder(); @Override public void lifecycleEvent(LifecycleEvent event) { String type = event.getType(); if (type.equals(Lifecycle.START_EVENT) || type.equals(Lifecycle.STOP_EVENT) || type.equals(Lifecycle.AFTER_DESTROY_EVENT)) { stateHistory.append(type); } } public String getHistory() { return stateHistory.toString(); } } /* * Test context copyXML setting. * If context.copyXML != Host.copyXML the Host wins. * For external WARs, a context.xml must always already exist */ @Test public void testCopyXMLFFF() throws Exception { doTestCopyXML(false, false, false, false); } @Test public void testCopyXMLFFT() throws Exception { doTestCopyXML(false, false, true, true); } @Test public void testCopyXMLFTF() throws Exception { doTestCopyXML(false, true, false, true); } @Test public void testCopyXMLFTT() throws Exception { doTestCopyXML(false, true, true, true); } @Test public void testCopyXMLTFF() throws Exception { doTestCopyXML(true, false, false, true); } @Test public void testCopyXMLTFT() throws Exception { doTestCopyXML(true, false, true, true); } @Test public void testCopyXMLTTF() throws Exception { doTestCopyXML(true, true, false, true); } @Test public void testCopyXMLTTT() throws Exception { doTestCopyXML(true, true, true, true); } private void doTestCopyXML(boolean copyXmlHost, boolean copyXmlWar, boolean external, boolean resultXml) throws Exception { Tomcat tomcat = getTomcatInstance(); StandardHost host = (StandardHost) tomcat.getHost(); host.setCopyXML(copyXmlHost); tomcat.start(); File war; if (copyXmlWar) { war = createWar(WAR_XML_COPYXML_TRUE_SOURCE, !external); } else { war = createWar(WAR_XML_COPYXML_FALSE_SOURCE, !external); } if (external) { createXmlInConfigBaseForExternal(war); } host.backgroundProcess(); File xml = new File(host.getConfigBaseFile(), APP_NAME.getBaseName() + ".xml"); Assert.assertEquals( Boolean.valueOf(resultXml), Boolean.valueOf(xml.isFile())); Context context = (Context) host.findChild(APP_NAME.getName()); if (external) { Assert.assertEquals(XML_COOKIE_NAME, context.getSessionCookieName()); } else { Assert.assertEquals(WAR_COOKIE_NAME, context.getSessionCookieName()); } } @Test public void testSetContextClassName() throws Exception { Tomcat tomcat = getTomcatInstance(); Host host = tomcat.getHost(); if (host instanceof StandardHost) { StandardHost standardHost = (StandardHost) host; standardHost.setContextClass(TesterContext.class.getName()); } // Copy the WAR file File war = new File(host.getAppBaseFile(), APP_NAME.getBaseName() + ".war"); Files.copy(WAR_XML_SOURCE.toPath(), war.toPath()); // Deploy the copied war tomcat.start(); host.backgroundProcess(); // Check the Context class Context ctxt = (Context) host.findChild(APP_NAME.getName()); Assert.assertTrue(ctxt instanceof TesterContext); } public static class TesterContext extends StandardContext { // No functional change } }
55,958
Bug 55958 Tomcat tries to deploy dir as zip archive even when it is a directory if the name ends with .war
Webapp deployment fails if the dirname ends with .war because it is automatically considered as zip archive.
resolved fixed
5964a52
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T13:59:10Z
2014-01-06T14:53:20Z
test/org/apache/catalina/util/TestContextName.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 static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; public class TestContextName { private ContextName cn1; private ContextName cn2; private ContextName cn3; private ContextName cn4; private ContextName cn5; private ContextName cn6; private ContextName cn7; private ContextName cn8; private ContextName cn9; private ContextName cn10; private ContextName cn11; private ContextName cn12; private ContextName cn13; private ContextName cn14; private ContextName cn15; private ContextName cn16; private ContextName cn17; private ContextName cn18; private ContextName cn19; private ContextName cn20; @Before public void setUp() throws Exception { cn1 = new ContextName(null, null); cn2 = new ContextName("", null); cn3 = new ContextName("/", null); cn4 = new ContextName("/foo", null); cn5 = new ContextName("/foo/bar", null); cn6 = new ContextName(null, "A"); cn7 = new ContextName("", "B"); cn8 = new ContextName("/", "C"); cn9 = new ContextName("/foo", "D"); cn10 = new ContextName("/foo/bar", "E"); cn11 = new ContextName("ROOT"); cn12 = new ContextName("foo"); cn13 = new ContextName("foo#bar"); cn14 = new ContextName("ROOT##A"); cn15 = new ContextName("foo##D"); cn16 = new ContextName("foo#bar##E"); cn17 = new ContextName("/ROOT", null); cn18 = new ContextName("/ROOT#bar"); cn19 = new ContextName("/ROOT#bar##A"); cn20 = new ContextName("/ROOT##A"); } @Test public void testGetBaseName() { assertEquals("ROOT", cn1.getBaseName()); assertEquals("ROOT", cn2.getBaseName()); assertEquals("ROOT", cn3.getBaseName()); assertEquals("foo", cn4.getBaseName()); assertEquals("foo#bar", cn5.getBaseName()); assertEquals("ROOT##A", cn6.getBaseName()); assertEquals("ROOT##B", cn7.getBaseName()); assertEquals("ROOT##C", cn8.getBaseName()); assertEquals("foo##D", cn9.getBaseName()); assertEquals("foo#bar##E", cn10.getBaseName()); assertEquals("ROOT", cn11.getBaseName()); assertEquals("foo", cn12.getBaseName()); assertEquals("foo#bar", cn13.getBaseName()); assertEquals("ROOT##A", cn14.getBaseName()); assertEquals("foo##D", cn15.getBaseName()); assertEquals("foo#bar##E", cn16.getBaseName()); assertEquals("ROOT", cn17.getBaseName()); assertEquals("ROOT#bar", cn18.getBaseName()); assertEquals("ROOT#bar##A", cn19.getBaseName()); assertEquals("ROOT##A", cn20.getBaseName()); } @Test public void testGetPath() { assertEquals("", cn1.getPath()); assertEquals("", cn2.getPath()); assertEquals("", cn3.getPath()); assertEquals("/foo", cn4.getPath()); assertEquals("/foo/bar", cn5.getPath()); assertEquals("", cn6.getPath()); assertEquals("", cn7.getPath()); assertEquals("", cn8.getPath()); assertEquals("/foo", cn9.getPath()); assertEquals("/foo/bar", cn10.getPath()); assertEquals("", cn11.getPath()); assertEquals("/foo", cn12.getPath()); assertEquals("/foo/bar", cn13.getPath()); assertEquals("", cn14.getPath()); assertEquals("/foo", cn15.getPath()); assertEquals("/foo/bar", cn16.getPath()); assertEquals("", cn17.getPath()); assertEquals("/ROOT/bar", cn18.getPath()); assertEquals("/ROOT/bar", cn19.getPath()); assertEquals("", cn20.getPath()); } @Test public void testGetVersion() { assertEquals("", cn1.getVersion()); assertEquals("", cn2.getVersion()); assertEquals("", cn3.getVersion()); assertEquals("", cn4.getVersion()); assertEquals("", cn5.getVersion()); assertEquals("A", cn6.getVersion()); assertEquals("B", cn7.getVersion()); assertEquals("C", cn8.getVersion()); assertEquals("D", cn9.getVersion()); assertEquals("E", cn10.getVersion()); assertEquals("", cn11.getVersion()); assertEquals("", cn12.getVersion()); assertEquals("", cn13.getVersion()); assertEquals("A", cn14.getVersion()); assertEquals("D", cn15.getVersion()); assertEquals("E", cn16.getVersion()); assertEquals("", cn17.getVersion()); assertEquals("", cn18.getVersion()); assertEquals("A", cn19.getVersion()); assertEquals("A", cn20.getVersion()); } @Test public void testGetName() { assertEquals("", cn1.getName()); assertEquals("", cn2.getName()); assertEquals("", cn3.getName()); assertEquals("/foo", cn4.getName()); assertEquals("/foo/bar", cn5.getName()); assertEquals("##A", cn6.getName()); assertEquals("##B", cn7.getName()); assertEquals("##C", cn8.getName()); assertEquals("/foo##D", cn9.getName()); assertEquals("/foo/bar##E", cn10.getName()); assertEquals("", cn11.getName()); assertEquals("/foo", cn12.getName()); assertEquals("/foo/bar", cn13.getName()); assertEquals("##A", cn14.getName()); assertEquals("/foo##D", cn15.getName()); assertEquals("/foo/bar##E", cn16.getName()); assertEquals("", cn17.getName()); assertEquals("/ROOT/bar", cn18.getName()); assertEquals("/ROOT/bar##A", cn19.getName()); assertEquals("##A", cn20.getName()); } @Test public void testGetDisplayName() { assertEquals("/", cn1.getDisplayName()); assertEquals("/", cn2.getDisplayName()); assertEquals("/", cn3.getDisplayName()); assertEquals("/foo", cn4.getDisplayName()); assertEquals("/foo/bar", cn5.getDisplayName()); assertEquals("/##A", cn6.getDisplayName()); assertEquals("/##B", cn7.getDisplayName()); assertEquals("/##C", cn8.getDisplayName()); assertEquals("/foo##D", cn9.getDisplayName()); assertEquals("/foo/bar##E", cn10.getDisplayName()); assertEquals("/", cn11.getDisplayName()); assertEquals("/foo", cn12.getDisplayName()); assertEquals("/foo/bar", cn13.getDisplayName()); assertEquals("/##A", cn14.getDisplayName()); assertEquals("/foo##D", cn15.getDisplayName()); assertEquals("/foo/bar##E", cn16.getDisplayName()); assertEquals("/", cn17.getDisplayName()); assertEquals("/ROOT/bar", cn18.getDisplayName()); assertEquals("/ROOT/bar##A", cn19.getDisplayName()); assertEquals("/##A", cn20.getDisplayName()); } @Test public void testConstructorString() { doTestConstructorString(cn1); doTestConstructorString(cn2); doTestConstructorString(cn3); doTestConstructorString(cn4); doTestConstructorString(cn5); doTestConstructorString(cn6); doTestConstructorString(cn7); doTestConstructorString(cn8); doTestConstructorString(cn9); doTestConstructorString(cn10); doTestConstructorString(cn11); doTestConstructorString(cn12); doTestConstructorString(cn13); doTestConstructorString(cn14); doTestConstructorString(cn15); doTestConstructorString(cn16); doTestConstructorString(cn17); doTestConstructorString(cn18); doTestConstructorString(cn19); doTestConstructorString(cn20); } private void doTestConstructorString(ContextName src) { doCompare(src, new ContextName(src.getBaseName())); doCompare(src, new ContextName(src.getDisplayName())); doCompare(src, new ContextName(src.getName())); } private void doCompare(ContextName cn1, ContextName cn2) { assertEquals(cn1.getBaseName(), cn2.getBaseName()); assertEquals(cn1.getDisplayName(), cn2.getDisplayName()); assertEquals(cn1.getName(), cn2.getName()); assertEquals(cn1.getPath(), cn2.getPath()); assertEquals(cn1.getVersion(), cn2.getVersion()); } }
55,960
Bug 55960 TestSSOnonLoginAndBasicAuthenticator is flawed and incomplete
null
resolved fixed
ad129f8
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T15:01:41Z
2014-01-06T20:26:40Z
test/org/apache/catalina/authenticator/TestSSOnonLoginAndBasicAuthenticator.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.nio.charset.StandardCharsets; 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.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.apache.catalina.Context; import org.apache.catalina.startup.TesterServlet; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.codec.binary.Base64; import org.apache.tomcat.util.descriptor.web.LoginConfig; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; /** * Test BasicAuthenticator and NonLoginAuthenticator when a * SingleSignOn Valve is active. * * <p> * In the absence of SSO support, a webapp using NonLoginAuthenticator * simply cannot access protected resources. These tests exercise the * the way successfully authenticating a different webapp under the * BasicAuthenticator triggers the additional SSO logic for both webapps. */ public class TestSSOnonLoginAndBasicAuthenticator extends TomcatBaseTest { private static final String USER = "user"; private static final String PWD = "pwd"; private static final String ROLE = "role"; private static final String HTTP_PREFIX = "http://localhost:"; private static final String CONTEXT_PATH_NOLOGIN = "/nologin"; private static final String CONTEXT_PATH_LOGIN = "/login"; private static final String URI_PROTECTED = "/protected"; private static final String URI_PUBLIC = "/anyoneCanAccess"; private static final int SHORT_TIMEOUT_SECS = 4; private static final long SHORT_TIMEOUT_DELAY_MSECS = ((SHORT_TIMEOUT_SECS + 3) * 1000); private static final int LONG_TIMEOUT_SECS = 10; private static final long LONG_TIMEOUT_DELAY_MSECS = ((LONG_TIMEOUT_SECS + 5) * 1000); private static String CLIENT_AUTH_HEADER = "authorization"; private static String SERVER_COOKIES = "Set-Cookie"; private static String BROWSER_COOKIES = "Cookie"; private List<String> cookies; /* * Try to access an unprotected resource without an established * SSO session. * This should be permitted. */ @Test public void testAcceptPublicNonLogin() throws Exception { doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PUBLIC, false, false, 200); } /* * Try to access a protected resource without an established * SSO session. * This should be rejected with SC_FORBIDDEN 403 status. */ @Test public void testRejectProtectedNonLogin() throws Exception { doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, false, true, 403); } /* * Logon to access a protected resource using BASIC authentication, * which will establish an SSO session. * Wait until the SSO session times-out, then try to re-access * the resource. * This should be rejected with SC_FORBIDDEN 401 status, which * will then be followed by successful re-authentication. */ @Test public void testBasicLoginSessionTimeout() throws Exception { doTestBasic(USER, PWD, CONTEXT_PATH_LOGIN + URI_PROTECTED, true, 401, false, 200); // wait long enough for my session to expire Thread.sleep(SHORT_TIMEOUT_DELAY_MSECS); doTestBasic(USER, PWD, CONTEXT_PATH_LOGIN + URI_PROTECTED, true, 401, false, 200); } /* * Logon to access a protected resource using BASIC authentication, * which will establish an SSO session. * Immediately try to access a protected resource in the NonLogin * webapp, but without sending the SSO session cookie. * This should be rejected with SC_FORBIDDEN 403 status. */ @Test public void testBasicLoginRejectProtectedWithoutCookies() throws Exception { doTestBasic(USER, PWD, CONTEXT_PATH_LOGIN + URI_PROTECTED, true, 401, false, 200); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, false, true, 403); } /* * Logon to access a protected resource using BASIC authentication, * which will establish an SSO session. * Immediately try to access a protected resource in the NonLogin * webapp while sending the SSO session cookie provided by the * first webapp. * This should be successful with SC_OK 200 status. */ @Test public void testBasicLoginAcceptProtectedWithCookies() throws Exception { doTestBasic(USER, PWD, CONTEXT_PATH_LOGIN + URI_PROTECTED, true, 401, false, 200); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, true, false, 200); } /* * Logon to access a protected resource using BASIC authentication, * which will establish an SSO session. * Immediately try to access a protected resource in the NonLogin * webapp while sending the SSO session cookie provided by the * first webapp. * This should be successful with SC_OK 200 status. * * Then, wait long enough for the BASIC session to expire. (The SSO * session should remain active because the NonLogin session has * not yet expired). * * Try to access the protected resource again, before the SSO session * has expired. * This should be successful with SC_OK 200 status. * * Finally, wait for the non-login session to expire and try again.. * This should be rejected with SC_FORBIDDEN 403 status. * * (see bugfix https://issues.apache.org/bugzilla/show_bug.cgi?id=52303) */ @Test public void testBasicExpiredAcceptProtectedWithCookies() throws Exception { doTestBasic(USER, PWD, CONTEXT_PATH_LOGIN + URI_PROTECTED, true, 401, false, 200); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, true, false, 200); // wait long enough for the BASIC session to expire, // but not long enough for NonLogin session expiry Thread.sleep(SHORT_TIMEOUT_DELAY_MSECS); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, true, false, 200); // wait long enough for my NonLogin session to expire // and tear down the SSO session at the same time. Thread.sleep(LONG_TIMEOUT_DELAY_MSECS); doTestNonLogin(CONTEXT_PATH_NOLOGIN + URI_PROTECTED, false, true, 403); } public void doTestNonLogin(String uri, boolean addCookies, boolean expectedReject, int expectedRC) throws Exception { Map<String,List<String>> reqHeaders = new HashMap<>(); if (addCookies) { addCookies(reqHeaders); } Map<String,List<String>> respHeaders = new HashMap<>(); ByteChunk bc = new ByteChunk(); int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders, respHeaders); if (expectedReject) { assertEquals(expectedRC, rc); assertTrue(bc.getLength() > 0); } else { assertEquals(200, rc); assertEquals("OK", bc.toString()); saveCookies(respHeaders); } } public void doTestBasic(String user, String pwd, String uri, boolean expectedReject1, int expectedRC1, boolean expectedReject2, int expectedRC2) throws Exception { // the first access attempt should be challenged Map<String,List<String>> reqHeaders1 = new HashMap<>(); Map<String,List<String>> respHeaders1 = new HashMap<>(); ByteChunk bc = new ByteChunk(); int rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders1, respHeaders1); if (expectedReject1) { assertEquals(expectedRC1, rc); assertTrue(bc.getLength() > 0); } else { assertEquals(200, rc); assertEquals("OK", bc.toString()); return; } // the second access attempt should be successful String credentials = user + ":" + pwd; String base64auth = Base64.encodeBase64String( credentials.getBytes(StandardCharsets.ISO_8859_1)); String authLine = "Basic " + base64auth; List<String> auth = new ArrayList<>(); auth.add(authLine); Map<String,List<String>> reqHeaders2 = new HashMap<>(); reqHeaders2.put(CLIENT_AUTH_HEADER, auth); Map<String,List<String>> respHeaders2 = new HashMap<>(); bc.recycle(); rc = getUrl(HTTP_PREFIX + getPort() + uri, bc, reqHeaders2, respHeaders2); if (expectedReject2) { assertEquals(expectedRC2, rc); assertNull(bc.toString()); } else { assertEquals(200, rc); assertEquals("OK", bc.toString()); saveCookies(respHeaders2); } } @Override public void setUp() throws Exception { super.setUp(); // create a tomcat server using the default in-memory Realm Tomcat tomcat = getTomcatInstance(); // associate the SingeSignOn Valve before the Contexts SingleSignOn sso = new SingleSignOn(); tomcat.getHost().getPipeline().addValve(sso); // add the test user and role to the Realm tomcat.addUser(USER, PWD); tomcat.addRole(USER, ROLE); // setup both NonLogin and Login webapps setUpNonLogin(tomcat); setUpLogin(tomcat); tomcat.start(); } private void setUpNonLogin(Tomcat tomcat) throws Exception { // Must have a real docBase for webapps - just use temp Context ctxt = tomcat.addContext(CONTEXT_PATH_NOLOGIN, System.getProperty("java.io.tmpdir")); ctxt.setSessionTimeout(LONG_TIMEOUT_SECS); // Add protected servlet Tomcat.addServlet(ctxt, "TesterServlet1", new TesterServlet()); ctxt.addServletMapping(URI_PROTECTED, "TesterServlet1"); SecurityCollection collection1 = new SecurityCollection(); collection1.addPattern(URI_PROTECTED); SecurityConstraint sc1 = new SecurityConstraint(); sc1.addAuthRole(ROLE); sc1.addCollection(collection1); ctxt.addConstraint(sc1); // Add unprotected servlet Tomcat.addServlet(ctxt, "TesterServlet2", new TesterServlet()); ctxt.addServletMapping(URI_PUBLIC, "TesterServlet2"); SecurityCollection collection2 = new SecurityCollection(); collection2.addPattern(URI_PUBLIC); SecurityConstraint sc2 = new SecurityConstraint(); // do not add a role - which signals access permitted without one sc2.addCollection(collection2); ctxt.addConstraint(sc2); // Configure the authenticator and inherit the Realm from Engine LoginConfig lc = new LoginConfig(); lc.setAuthMethod("NONE"); ctxt.setLoginConfig(lc); ctxt.getPipeline().addValve(new NonLoginAuthenticator()); } private void setUpLogin(Tomcat tomcat) throws Exception { // Must have a real docBase for webapps - just use temp Context ctxt = tomcat.addContext(CONTEXT_PATH_LOGIN, System.getProperty("java.io.tmpdir")); ctxt.setSessionTimeout(SHORT_TIMEOUT_SECS); // Add protected servlet Tomcat.addServlet(ctxt, "TesterServlet3", new TesterServlet()); ctxt.addServletMapping(URI_PROTECTED, "TesterServlet3"); SecurityCollection collection = new SecurityCollection(); collection.addPattern(URI_PROTECTED); SecurityConstraint sc = new SecurityConstraint(); sc.addAuthRole(ROLE); sc.addCollection(collection); ctxt.addConstraint(sc); // Configure the appropriate authenticator LoginConfig lc = new LoginConfig(); lc.setAuthMethod("BASIC"); ctxt.setLoginConfig(lc); ctxt.getPipeline().addValve(new BasicAuthenticator()); } /* * extract and save the server cookies from the incoming response */ protected void saveCookies(Map<String,List<String>> respHeaders) { // we only save the Cookie values, not header prefix cookies = respHeaders.get(SERVER_COOKIES); } /* * add all saved cookies to the outgoing request */ protected void addCookies(Map<String,List<String>> reqHeaders) { if ((cookies != null) && (cookies.size() > 0)) { reqHeaders.put(BROWSER_COOKIES + ":", cookies); } } }
55,960
Bug 55960 TestSSOnonLoginAndBasicAuthenticator is flawed and incomplete
null
resolved fixed
ad129f8
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T15:01:41Z
2014-01-06T20:26:40Z
test/org/apache/catalina/startup/TesterServletEncodeUrl.java
55,970
Bug 55970 A reloadable context is reloaded repeatedly if WEB-INF/lib contains non-jar files
null
resolved fixed
5594699
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T15:25:14Z
2014-01-08T00: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.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; 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.Collections; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; 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.catalina.webresources.TomcatURLStreamHandlerFactory; import org.apache.tomcat.InstrumentableClassLoader; 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> * <strong>IMPLEMENTATION NOTE</strong> - As of 8.0, this class * loader implements {@link InstrumentableClassLoader}, permitting web * application classes to instrument other classes in the same web * application. It does not permit instrumentation of system or container * classes or classes in other web apps. * * @author Remy Maucherat * @author Craig R. McClanahan * @version $Id$ */ public class WebappClassLoader extends URLClassLoader implements Lifecycle, InstrumentableClassLoader { private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog( WebappClassLoader.class ); /** * 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"; private static final String CLASS_FILE_SUFFIX = ".class"; 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 /** * Regular expression of package names which are not allowed to be loaded * from a webapp class loader without delegating first. */ protected final Matcher packageTriggersDeny = Pattern.compile( "^javax\\.el\\.|" + "^javax\\.servlet\\.|" + "^org\\.apache\\.(catalina|coyote|el|jasper|juli|naming|tomcat)\\." ).matcher(""); /** * Regular expression of package names which are allowed to be loaded from a * webapp class loader without delegating first and override any set by * {@link #packageTriggersDeny}. */ protected final Matcher packageTriggersPermit = Pattern.compile("^javax\\.servlet\\.jsp\\.jstl\\.").matcher(""); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------------- 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 web resources for this webapp. * TODO Review the use of resources in this class to see if further * simplifications can be made. */ protected WebResourceRoot resources = null; /** * The cache of ResourceEntry for classes and resources we have loaded, * keyed by resource path, not binary name. Path is used as the key since * resources may be requested by binary name (classes) or path (other * resources such as property files) and the mapping from binary name to * path is unambiguous but the reverse mapping is ambiguous. */ protected final Map<String, ResourceEntry> resourceEntries = new ConcurrentHashMap<>(); /** * 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; private final HashMap<String,Long> jarModificationTimes = new HashMap<>(); /** * 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<>(); /** * 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; /** * Holds the class file transformers decorating this class loader. The * CopyOnWriteArrayList is thread safe. It is expensive on writes, but * those should be rare. It is very fast on reads, since synchronization * is not actually used. Importantly, the ClassLoader will never block * iterating over the transformers while loading a class. */ private final List<ClassFileTransformer> transformers = new CopyOnWriteArrayList<>(); // ------------------------------------------------------------- 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; } /** * If there is a Java SecurityManager create a read permission for the * target of the given URL as appropriate. * * @param url URL for a file or directory on local system */ void addPermission(URL url) { if (url == null) { return; } if (securityManager != null) { String protocol = url.getProtocol(); if ("file".equalsIgnoreCase(protocol)) { URI uri; File f; String path; try { uri = url.toURI(); f = new File(uri); path = f.getCanonicalPath(); } catch (IOException | URISyntaxException e) { log.warn(sm.getString( "webappClassLoader.addPermisionNoCanonicalFile", url.toExternalForm())); return; } if (f.isFile()) { // Allow the file to be read addPermission(new FilePermission(path, "read")); } else if (f.isDirectory()) { addPermission(new FilePermission(path, "read")); addPermission(new FilePermission( path + File.separator + "-", "read")); } else { // File does not exist - ignore (shouldn't happen) } } else { // Unsupported URL protocol log.warn(sm.getString( "webappClassLoader.addPermisionNoProtocol", protocol, url.toExternalForm())); } } } /** * If there is a Java SecurityManager create a Permission. * * @param permission The permission */ void addPermission(Permission permission) { if ((securityManager != null) && (permission != null)) { permissionList.add(permission); } } /** * 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 /** * Adds the specified class file transformer to this class loader. The * transformer will then be able to modify the bytecode of any classes * loaded by this class loader after the invocation of this method. * * @param transformer The transformer to add to the class loader */ @Override public void addTransformer(ClassFileTransformer transformer) { if (transformer == null) { throw new IllegalArgumentException(sm.getString( "webappClassLoader.addTransformer.illegalArgument", getContextName())); } if (this.transformers.contains(transformer)) { // if the same instance of this transformer was already added, bail out log.warn(sm.getString("webappClassLoader.addTransformer.duplicate", transformer, getContextName())); return; } this.transformers.add(transformer); log.info(sm.getString("webappClassLoader.addTransformer", transformer, getContextName())); } /** * Removes the specified class file transformer from this class loader. * It will no longer be able to modify the byte code of any classes * loaded by the class loader after the invocation of this method. * However, any classes already modified by this transformer will * remain transformed. * * @param transformer The transformer to remove */ @Override public void removeTransformer(ClassFileTransformer transformer) { if (transformer == null) { return; } if (this.transformers.remove(transformer)) { log.info(sm.getString("webappClassLoader.removeTransformer", transformer, getContextName())); return; } } /** * Returns a copy of this class loader without any class file * transformers. This is a tool often used by Java Persistence API * providers to inspect entity classes in the absence of any * instrumentation, something that can't be guaranteed within the * context of a {@link ClassFileTransformer}'s * {@link ClassFileTransformer#transform(ClassLoader, String, Class, * ProtectionDomain, byte[]) transform} method. * <p> * The returned class loader's resource cache will have been cleared * so that classes already instrumented will not be retained or * returned. * * @return the transformer-free copy of this class loader. */ @Override public WebappClassLoader copyWithoutTransformers() { WebappClassLoader result = new WebappClassLoader(this.parent); result.resources = this.resources; result.delegate = this.delegate; result.started = this.started; result.needConvert = this.needConvert; result.clearReferencesStatic = this.clearReferencesStatic; result.clearReferencesStopThreads = this.clearReferencesStopThreads; result.clearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads; result.clearReferencesLogFactoryRelease = this.clearReferencesLogFactoryRelease; result.clearReferencesHttpClientKeepAliveThread = this.clearReferencesHttpClientKeepAliveThread; result.jarModificationTimes.putAll(this.jarModificationTimes); result.permissionList.addAll(this.permissionList); result.loaderPC.putAll(this.loaderPC); try { result.start(); } catch (LifecycleException e) { throw new IllegalStateException(e); } return result; } /** * Have one or more classes or resources been modified so that a reload * is appropriate? */ public boolean modified() { if (log.isDebugEnabled()) log.debug("modified()"); for (Entry<String,ResourceEntry> entry : resourceEntries.entrySet()) { long cachedLastModified = entry.getValue().lastModified; long lastModified = resources.getClassLoaderResource( entry.getKey()).getLastModified(); if (lastModified != cachedLastModified) { if( log.isDebugEnabled() ) log.debug(sm.getString("webappClassLoader.resourceModified", entry.getKey(), new Date(cachedLastModified), new Date(lastModified))); return true; } } // Check if JARs have been added or removed WebResource[] jars = resources.listResources("/WEB-INF/lib"); if (jars.length > jarModificationTimes.size()) { log.info(sm.getString("webappClassLoader.jarsAdded", resources.getContext().getName())); return true; } else if (jars.length < jarModificationTimes.size()){ log.info(sm.getString("webappClassLoader.jarsRemoved", resources.getContext().getName())); return true; } for (WebResource jar : jars) { if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) { Long recordedLastModified = jarModificationTimes.get(jar.getName()); if (recordedLastModified == null) { // Jars have been added and removed log.info(sm.getString("webappClassLoader.jarsAdded", resources.getContext().getName())); return true; } if (recordedLastModified.longValue() != jar.getLastModified()) { // Jar has been changed log.info(sm.getString("webappClassLoader.jarsModified", resources.getContext().getName())); return true; } jarModificationTimes.put( jar.getName(), Long.valueOf(jar.getLastModified())); } } // 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"); if (this.parent != null) { sb.append("----------> Parent Classloader:\r\n"); sb.append(this.parent.toString()); sb.append("\r\n"); } if (this.transformers.size() > 0) { sb.append("----------> Class file transformers:\r\n"); for (ClassFileTransformer transformer : this.transformers) { sb.append(transformer).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 The binary 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; String path = nameToPath(name); ResourceEntry entry = resourceEntries.get(path); if (entry == null) { if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, path); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, path); } } 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<>(); String path = nameToPath(name); WebResource[] webResources = resources.getClassLoaderResources(path); for (WebResource webResource : webResources) { if (webResource.exists()) { result.add(webResource.getURL()); } } return Collections.enumeration(result); } /** * 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) { 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 The binary 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 The binary 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 String resourceName = binaryNameToPath(name, false); if (system.getResource(resourceName) != null) { 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); } /** * {@inheritDoc} * <p> * Note that list of URLs returned by this method may not be complete. The * web application class loader accesses class loader resources via the * {@link WebResourceRoot} which supports the arbitrary mapping of * additional files, directories and contents of JAR files under * WEB-INF/classes. Any such resources will not be included in the URLs * returned here. */ @Override public URL[] getURLs() { return super.getURLs(); } // ------------------------------------------------------ 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 { WebResource classes = resources.getResource("/WEB-INF/classes"); if (classes.isDirectory() && classes.canRead()) { addURL(classes.getURL()); } WebResource[] jars = resources.listResources("/WEB-INF/lib"); for (WebResource jar : jars) { if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) { addURL(jar.getURL()); jarModificationTimes.put( jar.getName(), Long.valueOf(jar.getLastModified())); } } 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; resourceEntries.clear(); jarModificationTimes.clear(); resources = null; parent = null; permissionList.clear(); loaderPC.clear(); } @Override public void destroy() { // NOOP } // ------------------------------------------------------ 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(); // Clear any custom URLStreamHandlers TomcatURLStreamHandlerFactory.release(this); } /** * 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(); @SuppressWarnings("unchecked") 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 = resourceEntries.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(); List<Thread> executorThreadsToStop = new ArrayList<>(); // 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 boolean usingExecutor = false; 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(); usingExecutor = true; } } } 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); } if (usingExecutor) { // Executor may take a short time to stop all the // threads. Make a note of threads that should be // stopped and check them at the end of the method. executorThreadsToStop.add(thread); } else { // 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(); } } } } // If thread stopping is enabled, executor threads should have been // stopped above when the executor was shut down but that depends on the // thread correctly handling the interrupt. Give all the executor // threads a few seconds shutdown and if they are still running // Give threads up to 2 seconds to shutdown int count = 0; for (Thread t : executorThreadsToStop) { while (t.isAlive() && count < 100) { try { Thread.sleep(20); } catch (InterruptedException e) { // Quit the while loop break; } count++; } if (t.isAlive()) { // 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. t.stop(); } } } /* * Look at a threads stack trace to see if it is a request thread or not. It * isn't perfect, but it should be good-enough for most cases. */ private boolean isRequestThread(Thread thread) { StackTraceElement[] elements = thread.getStackTrace(); if (elements == null || elements.length == 0) { // Must have stopped already. Too late to ignore it. Assume not a // request processing thread. return false; } // Step through the methods in reverse order looking for calls to any // CoyoteAdapter method. All request threads will have this unless // Tomcat has been heavily modified - in which case there isn't much we // can do. for (int i = 0; i < elements.length; i++) { StackTraceElement element = elements[elements.length - (i+1)]; if ("org.apache.catalina.connector.CoyoteAdapter".equals( element.getClassName())) { return true; } } return false; } private void clearReferencesStopTimerThread(Thread thread) { // Need to get references to: // in Sun/Oracle JDK: // - newTasksMayBeScheduled field (in java.util.TimerThread) // - queue field // - queue.clear() // in IBM JDK, Apache Harmony: // - cancel() method (in java.util.Timer$TimerImpl) try { try { Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled"); newTasksMayBeScheduledField.setAccessible(true); Field queueField = thread.getClass().getDeclaredField("queue"); queueField.setAccessible(true); Object queue = queueField.get(thread); Method clearMethod = queue.getClass().getDeclaredMethod("clear"); clearMethod.setAccessible(true); synchronized(queue) { newTasksMayBeScheduledField.setBoolean(thread, false); clearMethod.invoke(queue); queue.notify(); // In case queue was already empty. } }catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } log.error(sm.getString("webappClassLoader.warnTimerThread", getContextName(), thread.getName())); } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), getContextName()), t); } } private void checkThreadLocalsForLeaks() { Thread[] threads = getThreads(); try { // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); expungeStaleEntriesMethod.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } // Clear the second map threadLocalMap =inheritableThreadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), t); } } /** * Analyzes the given thread local map object. Also pass in the field that * points to the internal table to save re-calculating it on every * call to this method. */ private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { Object obj = table[j]; if (obj != null) { boolean potentialLeak = false; // Check the key Object key = ((Reference<?>) obj).get(); if (this.equals(key) || loadedByThisOrChild(key)) { potentialLeak = true; } // Check the value Field valueField = obj.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(obj); if (this.equals(value) || loadedByThisOrChild(value)) { potentialLeak = true; } if (potentialLeak) { Object[] args = new Object[5]; args[0] = getContextName(); if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksDebug", args)); } } else { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } } } } } } } private String getPrettyClassName(Class<?> clazz) { String name = clazz.getCanonicalName(); if (name==null){ name = clazz.getName(); } return name; } /** * @param o object to test, may be null * @return <code>true</code> if o has been loaded by the current classloader * or one of its descendants. */ private boolean loadedByThisOrChild(Object o) { if (o == null) { return false; } Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>) o; } else { clazz = o.getClass(); } ClassLoader cl = clazz.getClassLoader(); while (cl != null) { if (cl == this) { return true; } cl = cl.getParent(); } if (o instanceof Collection<?>) { Iterator<?> iter = ((Collection<?>) o).iterator(); try { while (iter.hasNext()) { Object entry = iter.next(); if (loadedByThisOrChild(entry)) { return true; } } } catch (ConcurrentModificationException e) { log.warn(sm.getString( "webappClassLoader", clazz.getName(), getContextName()), e); } } 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 try { while (tg.getParent() != null) { tg = tg.getParent(); } } catch (SecurityException se) { String msg = sm.getString( "webappClassLoader.getThreadGroupError", tg.getName()); if (log.isDebugEnabled()) { log.debug(msg, se); } else { log.warn(msg); } } 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); } } /** * Find specified class in local repositories. * * @param name The binary name of the class to be loaded * * @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 path = binaryNameToPath(name, true); ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, path); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, path); } 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)); } // Now the class has been defined, clear the elements of the local // resource cache that are no longer required. entry.loadedClass = clazz; entry.binaryContent = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; // Retain entry.source in case of a getResourceAsStream() call on // the class file after the class has been defined. } return clazz; } private String binaryNameToPath(String binaryName, boolean withLeadingSlash) { StringBuilder path = new StringBuilder( 1 + binaryName.length() + CLASS_FILE_SUFFIX.length()); if (withLeadingSlash) { path.append('/'); } path.append(binaryName.replace('.', '/')); path.append(CLASS_FILE_SUFFIX); return path.toString(); } private String nameToPath(String name) { if (name.startsWith("/")) { return name; } StringBuilder path = new StringBuilder( 1 + name.length()); path.append('/'); path.append(name); return path.toString(); } /** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found */ protected ResourceEntry findResourceInternal(final String name, final String path) { if (!started) { log.info(sm.getString("webappClassLoader.stopped", name)); return null; } if ((name == null) || (path == null)) return null; ResourceEntry entry = resourceEntries.get(path); if (entry != null) return entry; boolean isClassResource = path.endsWith(CLASS_FILE_SUFFIX); WebResource resource = null; boolean fileNeedConvert = false; resource = resources.getClassLoaderResource(path); if (!resource.exists()) { return null; } entry = new ResourceEntry(); entry.source = resource.getURL(); entry.codeBase = entry.source; entry.lastModified = resource.getLastModified(); if (needConvert) { if (path.endsWith(".properties")) { fileNeedConvert = true; } } /* 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 (isClassResource || fileNeedConvert) { byte[] binaryContent = resource.getContent(); if (binaryContent != 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); try { binaryContent = str.getBytes(StandardCharsets.UTF_8); } catch (Exception e) { return null; } } entry.binaryContent = binaryContent; // The certificates and manifest are made available as a side // effect of reading the binary content entry.certificates = resource.getCertificates(); } } entry.manifest = resource.getManifest(); if (isClassResource && entry.binaryContent != null && this.transformers.size() > 0) { // If the resource is a class just being loaded, decorate it // with any attached transformers String className = name.endsWith(CLASS_FILE_SUFFIX) ? name.substring(0, name.length() - CLASS_FILE_SUFFIX.length()) : name; String internalName = className.replace(".", "/"); for (ClassFileTransformer transformer : this.transformers) { try { byte[] transformed = transformer.transform( this, internalName, null, null, entry.binaryContent ); if (transformed != null) { entry.binaryContent = transformed; } } catch (IllegalClassFormatException e) { log.error(sm.getString("webappClassLoader.transformError", name), e); return null; } } } // 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(path); if (entry2 == null) { resourceEntries.put(path, 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) { String path = nameToPath(name); ResourceEntry entry = resourceEntries.get(path); 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 The binary name of the resource to return */ protected Class<?> findLoadedClass0(String name) { String path = binaryNameToPath(name, true); ResourceEntry entry = resourceEntries.get(path); if (entry != null) { return entry.loadedClass; } return null; } /** * 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 synchronized 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; packageTriggersPermit.reset(packageName); if (packageTriggersPermit.lookingAt()) { return false; } packageTriggersDeny.reset(packageName); if (packageTriggersDeny.lookingAt()) { 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; } }
55,974
Bug 55974 Honor the order when reporting XML parsing errors and warnings in XmlErrorHandler class
null
resolved fixed
328adb1
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T15:29:45Z
2014-01-08T03:00:00Z
java/org/apache/tomcat/util/descriptor/XmlErrorHandler.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.tomcat.util.descriptor; import java.util.HashSet; import java.util.Set; import org.apache.juli.logging.Log; import org.apache.tomcat.util.res.StringManager; import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; public class XmlErrorHandler implements ErrorHandler { private static final StringManager sm = StringManager.getManager(Constants.PACKAGE_NAME); private final Set<SAXParseException> errors = new HashSet<>(); private final Set<SAXParseException> warnings = new HashSet<>(); @Override public void error(SAXParseException exception) throws SAXException { // Collect non-fatal errors errors.add(exception); } @Override public void fatalError(SAXParseException exception) throws SAXException { // Re-throw fatal errors throw exception; } @Override public void warning(SAXParseException exception) throws SAXException { // Collect warnings warnings.add(exception); } public Set<SAXParseException> getErrors() { // Internal use only - don't worry about immutability return errors; } public Set<SAXParseException> getWarnings() { // Internal use only - don't worry about immutability return warnings; } public void logFindings(Log log, String source) { for (SAXParseException e : getWarnings()) { log.warn(sm.getString( "xmlErrorHandler.warning", e.getMessage(), source)); } for (SAXParseException e : getErrors()) { log.warn(sm.getString( "xmlErrorHandler.error", e.getMessage(), source)); } } }
55,976
Bug 55976 Broken response from NIO connector in Tomcat 7.0.50
null
closed fixed
d423ae2
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-09T21:32:25Z
2014-01-08T14:06:40Z
java/org/apache/coyote/http11/Http11NioProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.nio.channels.SelectionKey; import javax.net.ssl.SSLEngine; import org.apache.coyote.ActionCode; import org.apache.coyote.RequestInfo; import org.apache.coyote.http11.filters.BufferedInputFilter; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.NioChannel; import org.apache.tomcat.util.net.NioEndpoint; import org.apache.tomcat.util.net.NioEndpoint.KeyAttachment; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SecureNioChannel; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; /** * Processes HTTP requests. * * @author Remy Maucherat * @author Filip Hanik */ public class Http11NioProcessor extends AbstractHttp11Processor<NioChannel> { private static final Log log = LogFactory.getLog(Http11NioProcessor.class); @Override protected Log getLog() { return log; } /** * SSL information. */ protected SSLSupport sslSupport; // ----------------------------------------------------------- Constructors public Http11NioProcessor(int maxHttpHeaderSize, NioEndpoint endpoint, int maxTrailerSize, int maxExtensionSize) { super(endpoint); inputBuffer = new InternalNioInputBuffer(request, maxHttpHeaderSize); request.setInputBuffer(inputBuffer); outputBuffer = new InternalNioOutputBuffer(response, maxHttpHeaderSize); response.setOutputBuffer(outputBuffer); initializeFilters(maxTrailerSize, maxExtensionSize); } // ----------------------------------------------------- Instance Variables /** * Sendfile data. */ protected NioEndpoint.SendfileData sendfileData = null; // --------------------------------------------------------- Public Methods /** * Process pipelined HTTP requests using the specified input and output * streams. * * @throws IOException error during an I/O operation */ @Override public SocketState event(SocketStatus status) throws IOException { long soTimeout = endpoint.getSoTimeout(); RequestInfo rp = request.getRequestProcessor(); final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socketWrapper.getSocket().getAttachment(false); try { rp.setStage(org.apache.coyote.Constants.STAGE_SERVICE); error = !getAdapter().event(request, response, status); if ( !error ) { if (attach != null) { attach.setComet(comet); if (comet) { Integer comettimeout = (Integer) request.getAttribute( org.apache.coyote.Constants.COMET_TIMEOUT_ATTR); if (comettimeout != null) { attach.setTimeout(comettimeout.longValue()); } } else { //reset the timeout if (keepAlive) { attach.setTimeout(keepAliveTimeout); } else { attach.setTimeout(soTimeout); } } } } } catch (InterruptedIOException e) { error = true; } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.error(sm.getString("http11processor.request.process"), t); // 500 - Internal Server Error response.setStatus(500); getAdapter().log(request, response, 0); error = true; } rp.setStage(org.apache.coyote.Constants.STAGE_ENDED); if (error || status==SocketStatus.STOP) { return SocketState.CLOSED; } else if (!comet) { if (keepAlive) { inputBuffer.nextRequest(); outputBuffer.nextRequest(); return SocketState.OPEN; } else { return SocketState.CLOSED; } } else { return SocketState.LONG; } } @Override protected void registerForEvent(boolean read, boolean write) { final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socketWrapper.getSocket().getAttachment( false); if (attach == null) { return; } if (read) { attach.interestOps(attach.interestOps() | SelectionKey.OP_READ); } if (write) { attach.interestOps(attach.interestOps() | SelectionKey.OP_WRITE); } } @Override protected void resetTimeouts() { final NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socketWrapper.getSocket().getAttachment(false); if (!error && attach != null && asyncStateMachine.isAsyncDispatching()) { long soTimeout = endpoint.getSoTimeout(); //reset the timeout if (keepAlive) { attach.setTimeout(keepAliveTimeout); } else { attach.setTimeout(soTimeout); } } } @Override protected boolean disableKeepAlive() { return false; } @Override protected void setRequestLineReadTimeout() throws IOException { // socket.setTimeout() // - timeout used by poller // socket.getSocket().getIOChannel().socket().setSoTimeout() // - timeout used for blocking reads // When entering the processing loop there will always be data to read // so no point changing timeouts at this point // For the second and subsequent executions of the processing loop, a // non-blocking read is used so again no need to set the timeouts // Because NIO supports non-blocking reading of the request line and // headers the timeouts need to be set when returning the socket to // the poller rather than here. // NO-OP } @Override protected boolean handleIncompleteRequestLineRead() { // Haven't finished reading the request so keep the socket // open openSocket = true; // Check to see if we have read any of the request line yet if (((InternalNioInputBuffer) inputBuffer).getParsingRequestLinePhase() < 2) { if (socketWrapper.getLastAccess() > -1 || keptAlive) { // Haven't read the request line and have previously processed a // request. Must be keep-alive. Make sure poller uses keepAlive. socketWrapper.setTimeout(endpoint.getKeepAliveTimeout()); } } else { // Started to read request line. Need to keep processor // associated with socket readComplete = false; // Make sure poller uses soTimeout from here onwards socketWrapper.setTimeout(endpoint.getSoTimeout()); } if (endpoint.isPaused()) { // 503 - Service unavailable response.setStatus(503); getAdapter().log(request, response, 0); error = true; } else { return true; } return false; } @Override protected void setSocketTimeout(int timeout) throws IOException { socketWrapper.getSocket().getIOChannel().socket().setSoTimeout(timeout); } @Override protected void setCometTimeouts(SocketWrapper<NioChannel> socketWrapper) { // Comet support SelectionKey key = socketWrapper.getSocket().getIOChannel().keyFor( socketWrapper.getSocket().getPoller().getSelector()); if (key != null) { NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment) key.attachment(); if (attach != null) { attach.setComet(comet); if (comet) { Integer comettimeout = (Integer) request.getAttribute( org.apache.coyote.Constants.COMET_TIMEOUT_ATTR); if (comettimeout != null) { attach.setTimeout(comettimeout.longValue()); } } } } } @Override protected boolean breakKeepAliveLoop( SocketWrapper<NioChannel> socketWrapper) { // Do sendfile as needed: add socket to sendfile and end if (sendfileData != null && !error) { ((KeyAttachment) socketWrapper).setSendfileData(sendfileData); sendfileData.keepAlive = keepAlive; SelectionKey key = socketWrapper.getSocket().getIOChannel().keyFor( socketWrapper.getSocket().getPoller().getSelector()); //do the first write on this thread, might as well openSocket = socketWrapper.getSocket().getPoller().processSendfile(key, (KeyAttachment) socketWrapper, true); return true; } return false; } @Override public void recycleInternal() { socketWrapper = null; sendfileData = null; } // ----------------------------------------------------- ActionHook Methods /** * Send an action to the connector. * * @param actionCode Type of the action * @param param Action parameter */ @Override public void actionInternal(ActionCode actionCode, Object param) { if (actionCode == ActionCode.REQ_HOST_ADDR_ATTRIBUTE) { if (socketWrapper == null) { request.remoteAddr().recycle(); } else { if (socketWrapper.getRemoteAddr() == null) { InetAddress inetAddr = socketWrapper.getSocket().getIOChannel().socket().getInetAddress(); if (inetAddr != null) { socketWrapper.setRemoteAddr(inetAddr.getHostAddress()); } } request.remoteAddr().setString(socketWrapper.getRemoteAddr()); } } else if (actionCode == ActionCode.REQ_LOCAL_NAME_ATTRIBUTE) { if (socketWrapper == null) { request.localName().recycle(); } else { if (socketWrapper.getLocalName() == null) { InetAddress inetAddr = socketWrapper.getSocket().getIOChannel().socket().getLocalAddress(); if (inetAddr != null) { socketWrapper.setLocalName(inetAddr.getHostName()); } } request.localName().setString(socketWrapper.getLocalName()); } } else if (actionCode == ActionCode.REQ_HOST_ATTRIBUTE) { if (socketWrapper == null) { request.remoteHost().recycle(); } else { if (socketWrapper.getRemoteHost() == null) { InetAddress inetAddr = socketWrapper.getSocket().getIOChannel().socket().getInetAddress(); if (inetAddr != null) { socketWrapper.setRemoteHost(inetAddr.getHostName()); } if (socketWrapper.getRemoteHost() == null) { if (socketWrapper.getRemoteAddr() == null && inetAddr != null) { socketWrapper.setRemoteAddr(inetAddr.getHostAddress()); } if (socketWrapper.getRemoteAddr() != null) { socketWrapper.setRemoteHost(socketWrapper.getRemoteAddr()); } } } request.remoteHost().setString(socketWrapper.getRemoteHost()); } } else if (actionCode == ActionCode.REQ_LOCAL_ADDR_ATTRIBUTE) { if (socketWrapper == null) { request.localAddr().recycle(); } else { if (socketWrapper.getLocalAddr() == null) { socketWrapper.setLocalAddr( socketWrapper.getSocket().getIOChannel().socket().getLocalAddress().getHostAddress()); } request.localAddr().setString(socketWrapper.getLocalAddr()); } } else if (actionCode == ActionCode.REQ_REMOTEPORT_ATTRIBUTE) { if (socketWrapper == null) { request.setRemotePort(0); } else { if (socketWrapper.getRemotePort() == -1) { socketWrapper.setRemotePort(socketWrapper.getSocket().getIOChannel().socket().getPort()); } request.setRemotePort(socketWrapper.getRemotePort()); } } else if (actionCode == ActionCode.REQ_LOCALPORT_ATTRIBUTE) { if (socketWrapper == null) { request.setLocalPort(0); } else { if (socketWrapper.getLocalPort() == -1) { socketWrapper.setLocalPort(socketWrapper.getSocket().getIOChannel().socket().getLocalPort()); } request.setLocalPort(socketWrapper.getLocalPort()); } } else if (actionCode == ActionCode.REQ_SSL_ATTRIBUTE ) { try { if (sslSupport != null) { Object sslO = sslSupport.getCipherSuite(); if (sslO != null) { request.setAttribute (SSLSupport.CIPHER_SUITE_KEY, sslO); } sslO = sslSupport.getPeerCertificateChain(false); if (sslO != null) { request.setAttribute (SSLSupport.CERTIFICATE_KEY, sslO); } sslO = sslSupport.getKeySize(); if (sslO != null) { request.setAttribute (SSLSupport.KEY_SIZE_KEY, sslO); } sslO = sslSupport.getSessionId(); if (sslO != null) { request.setAttribute (SSLSupport.SESSION_ID_KEY, sslO); } request.setAttribute(SSLSupport.SESSION_MGR, sslSupport); } } catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); } } else if (actionCode == ActionCode.REQ_SSL_CERTIFICATE) { if( sslSupport != null) { /* * Consume and buffer the request body, so that it does not * interfere with the client's handshake messages */ InputFilter[] inputFilters = inputBuffer.getFilters(); ((BufferedInputFilter) inputFilters[Constants.BUFFERED_FILTER]) .setLimit(maxSavePostSize); inputBuffer.addActiveFilter (inputFilters[Constants.BUFFERED_FILTER]); SecureNioChannel sslChannel = (SecureNioChannel) socketWrapper.getSocket(); SSLEngine engine = sslChannel.getSslEngine(); if (!engine.getNeedClientAuth()) { // Need to re-negotiate SSL connection engine.setNeedClientAuth(true); try { sslChannel.rehandshake(endpoint.getSoTimeout()); sslSupport = ((NioEndpoint)endpoint).getHandler() .getSslImplementation().getSSLSupport( engine.getSession()); } catch (IOException ioe) { log.warn(sm.getString("http11processor.socket.sslreneg",ioe)); } } try { // use force=false since re-negotiation is handled above // (and it is a NO-OP for NIO anyway) Object sslO = sslSupport.getPeerCertificateChain(false); if( sslO != null) { request.setAttribute (SSLSupport.CERTIFICATE_KEY, sslO); } } catch (Exception e) { log.warn(sm.getString("http11processor.socket.ssl"), e); } } } else if (actionCode == ActionCode.COMET_BEGIN) { comet = true; } else if (actionCode == ActionCode.COMET_END) { comet = false; } else if (actionCode == ActionCode.COMET_CLOSE) { if (socketWrapper==null || socketWrapper.getSocket().getAttachment(false)==null) { return; } RequestInfo rp = request.getRequestProcessor(); if (rp.getStage() != org.apache.coyote.Constants.STAGE_SERVICE) { // Close event for this processor triggered by request // processing in another processor, a non-Tomcat thread (i.e. // an application controlled thread) or similar. socketWrapper.getSocket().getPoller().add(socketWrapper.getSocket()); } } else if (actionCode == ActionCode.COMET_SETTIMEOUT) { if (param==null) { return; } if (socketWrapper==null || socketWrapper.getSocket().getAttachment(false)==null) { return; } NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socketWrapper.getSocket().getAttachment(false); long timeout = ((Long)param).longValue(); //if we are not piggy backing on a worker thread, set the timeout RequestInfo rp = request.getRequestProcessor(); if ( rp.getStage() != org.apache.coyote.Constants.STAGE_SERVICE ) { attach.setTimeout(timeout); } } else if (actionCode == ActionCode.ASYNC_COMPLETE) { socketWrapper.clearDispatches(); if (asyncStateMachine.asyncComplete()) { ((NioEndpoint)endpoint).dispatchForEvent(this.socketWrapper.getSocket(),SocketStatus.OPEN_READ, true); } } else if (actionCode == ActionCode.ASYNC_SETTIMEOUT) { if (param==null) { return; } if (socketWrapper==null || socketWrapper.getSocket().getAttachment(false)==null) { return; } NioEndpoint.KeyAttachment attach = (NioEndpoint.KeyAttachment)socketWrapper.getSocket().getAttachment(false); long timeout = ((Long)param).longValue(); //if we are not piggy backing on a worker thread, set the timeout attach.setTimeout(timeout); } else if (actionCode == ActionCode.ASYNC_DISPATCH) { if (asyncStateMachine.asyncDispatch()) { ((NioEndpoint)endpoint).dispatchForEvent(this.socketWrapper.getSocket(),SocketStatus.OPEN_READ, true); } } } // ------------------------------------------------------ Protected Methods @Override protected void prepareRequestInternal() { sendfileData = null; } @Override protected boolean prepareSendfile(OutputFilter[] outputFilters) { String fileName = (String) request.getAttribute( org.apache.coyote.Constants.SENDFILE_FILENAME_ATTR); if (fileName != null) { // No entity body sent here outputBuffer.addActiveFilter(outputFilters[Constants.VOID_FILTER]); contentDelimitation = true; sendfileData = new NioEndpoint.SendfileData(); sendfileData.fileName = fileName; sendfileData.pos = ((Long) request.getAttribute( org.apache.coyote.Constants.SENDFILE_FILE_START_ATTR)).longValue(); sendfileData.length = ((Long) request.getAttribute( org.apache.coyote.Constants.SENDFILE_FILE_END_ATTR)).longValue() - sendfileData.pos; return true; } return false; } @Override protected AbstractInputBuffer<NioChannel> getInputBuffer() { return inputBuffer; } @Override protected AbstractOutputBuffer<NioChannel> getOutputBuffer() { return outputBuffer; } /** * Set the SSL information for this HTTP connection. */ @Override public void setSslSupport(SSLSupport sslSupport) { this.sslSupport = sslSupport; } }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
java/org/apache/coyote/AbstractProtocol.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote; import java.io.IOException; import java.net.InetAddress; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import javax.management.InstanceNotFoundException; import javax.management.MBeanRegistration; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.ObjectName; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; import org.apache.juli.logging.Log; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.collections.SynchronizedStack; import org.apache.tomcat.util.modeler.Registry; import org.apache.tomcat.util.net.AbstractEndpoint; import org.apache.tomcat.util.net.AbstractEndpoint.Handler; import org.apache.tomcat.util.net.DispatchType; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractProtocol<S> implements ProtocolHandler, MBeanRegistration { /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); /** * Counter used to generate unique JMX names for connectors using automatic * port binding. */ private static final AtomicInteger nameCounter = new AtomicInteger(0); /** * Name of MBean for the Global Request Processor. */ protected ObjectName rgOname = null; /** * Name of MBean for the ThreadPool. */ protected ObjectName tpOname = null; /** * Unique ID for this connector. Only used if the connector is configured * to use a random port as the port will change if stop(), start() is * called. */ private int nameIndex = 0; /** * Endpoint that provides low-level network I/O - must be matched to the * ProtocolHandler implementation (ProtocolHandler using BIO, requires BIO * Endpoint etc.). */ protected AbstractEndpoint<S> endpoint = null; // ----------------------------------------------- Generic property handling /** * Generic property setter used by the digester. Other code should not need * to use this. The digester will only use this method if it can't find a * more specific setter. That means the property belongs to the Endpoint, * the ServerSocketFactory or some other lower level component. This method * ensures that it is visible to both. */ public boolean setProperty(String name, String value) { return endpoint.setProperty(name, value); } /** * Generic property getter used by the digester. Other code should not need * to use this. */ public String getProperty(String name) { return endpoint.getProperty(name); } // ------------------------------- Properties managed by the ProtocolHandler /** * The adapter provides the link between the ProtocolHandler and the * connector. */ protected Adapter adapter; @Override public void setAdapter(Adapter adapter) { this.adapter = adapter; } @Override public Adapter getAdapter() { return adapter; } /** * The maximum number of idle processors that will be retained in the cache * and re-used with a subsequent request. The default is 200. A value of -1 * means unlimited. In the unlimited case, the theoretical maximum number of * cached Processor objects is {@link #getMaxConnections()} although it will * usually be closer to {@link #getMaxThreads()}. */ protected int processorCache = 200; public int getProcessorCache() { return this.processorCache; } public void setProcessorCache(int processorCache) { this.processorCache = processorCache; } /** * When client certificate information is presented in a form other than * instances of {@link java.security.cert.X509Certificate} it needs to be * converted before it can be used and this property controls which JSSE * provider is used to perform the conversion. For example it is used with * the AJP connectors, the HTTP APR connector and with the * {@link org.apache.catalina.valves.SSLValve}. If not specified, the * default provider will be used. */ protected String clientCertProvider = null; public String getClientCertProvider() { return clientCertProvider; } public void setClientCertProvider(String s) { this.clientCertProvider = s; } @Override public boolean isAprRequired() { return false; } @Override public boolean isCometSupported() { return endpoint.getUseComet(); } @Override public boolean isCometTimeoutSupported() { return endpoint.getUseCometTimeout(); } @Override public boolean isSendfileSupported() { return endpoint.getUseSendfile(); } // ---------------------- Properties that are passed through to the EndPoint @Override public Executor getExecutor() { return endpoint.getExecutor(); } public void setExecutor(Executor executor) { endpoint.setExecutor(executor); } public int getMaxThreads() { return endpoint.getMaxThreads(); } public void setMaxThreads(int maxThreads) { endpoint.setMaxThreads(maxThreads); } public int getMaxConnections() { return endpoint.getMaxConnections(); } public void setMaxConnections(int maxConnections) { endpoint.setMaxConnections(maxConnections); } public int getMinSpareThreads() { return endpoint.getMinSpareThreads(); } public void setMinSpareThreads(int minSpareThreads) { endpoint.setMinSpareThreads(minSpareThreads); } public int getThreadPriority() { return endpoint.getThreadPriority(); } public void setThreadPriority(int threadPriority) { endpoint.setThreadPriority(threadPriority); } public int getBacklog() { return endpoint.getBacklog(); } public void setBacklog(int backlog) { endpoint.setBacklog(backlog); } public boolean getTcpNoDelay() { return endpoint.getTcpNoDelay(); } public void setTcpNoDelay(boolean tcpNoDelay) { endpoint.setTcpNoDelay(tcpNoDelay); } public int getSoLinger() { return endpoint.getSoLinger(); } public void setSoLinger(int soLinger) { endpoint.setSoLinger(soLinger); } public int getKeepAliveTimeout() { return endpoint.getKeepAliveTimeout(); } public void setKeepAliveTimeout(int keepAliveTimeout) { endpoint.setKeepAliveTimeout(keepAliveTimeout); } public InetAddress getAddress() { return endpoint.getAddress(); } public void setAddress(InetAddress ia) { endpoint.setAddress(ia); } public int getPort() { return endpoint.getPort(); } public void setPort(int port) { endpoint.setPort(port); } public int getLocalPort() { return endpoint.getLocalPort(); } /* * When Tomcat expects data from the client, this is the time Tomcat will * wait for that data to arrive before closing the connection. */ public int getConnectionTimeout() { // Note that the endpoint uses the alternative name return endpoint.getSoTimeout(); } public void setConnectionTimeout(int timeout) { // Note that the endpoint uses the alternative name endpoint.setSoTimeout(timeout); } /* * Alternative name for connectionTimeout property */ public int getSoTimeout() { return getConnectionTimeout(); } public void setSoTimeout(int timeout) { setConnectionTimeout(timeout); } public int getMaxHeaderCount() { return endpoint.getMaxHeaderCount(); } public void setMaxHeaderCount(int maxHeaderCount) { endpoint.setMaxHeaderCount(maxHeaderCount); } public long getConnectionCount() { return endpoint.getConnectionCount(); } // ---------------------------------------------------------- Public methods public synchronized int getNameIndex() { if (nameIndex == 0) { nameIndex = nameCounter.incrementAndGet(); } return nameIndex; } /** * The name will be prefix-address-port if address is non-null and * prefix-port if the address is null. The name will be appropriately quoted * so it can be used directly in an ObjectName. */ public String getName() { StringBuilder name = new StringBuilder(getNamePrefix()); name.append('-'); if (getAddress() != null) { name.append(getAddress().getHostAddress()); name.append('-'); } int port = getPort(); if (port == 0) { // Auto binding is in use. Check if port is known name.append("auto-"); name.append(getNameIndex()); port = getLocalPort(); if (port != -1) { name.append('-'); name.append(port); } } else { name.append(port); } return ObjectName.quote(name.toString()); } // -------------------------------------------------------- Abstract methods /** * Concrete implementations need to provide access to their logger to be * used by the abstract classes. */ protected abstract Log getLog(); /** * Obtain the prefix to be used when construction a name for this protocol * handler. The name will be prefix-address-port. */ protected abstract String getNamePrefix(); /** * Obtain the name of the protocol, (Http, Ajp, etc.). Used with JMX. */ protected abstract String getProtocolName(); /** * Obtain the handler associated with the underlying Endpoint */ protected abstract Handler getHandler(); // ----------------------------------------------------- JMX related methods protected String domain; protected ObjectName oname; protected MBeanServer mserver; public ObjectName getObjectName() { return oname; } public String getDomain() { return domain; } @Override public ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception { oname = name; mserver = server; domain = name.getDomain(); return name; } @Override public void postRegister(Boolean registrationDone) { // NOOP } @Override public void preDeregister() throws Exception { // NOOP } @Override public void postDeregister() { // NOOP } private ObjectName createObjectName() throws MalformedObjectNameException { // Use the same domain as the connector domain = getAdapter().getDomain(); if (domain == null) { return null; } StringBuilder name = new StringBuilder(getDomain()); name.append(":type=ProtocolHandler,port="); int port = getPort(); if (port > 0) { name.append(getPort()); } else { name.append("auto-"); name.append(getNameIndex()); } InetAddress address = getAddress(); if (address != null) { name.append(",address="); name.append(ObjectName.quote(address.getHostAddress())); } return new ObjectName(name.toString()); } // ------------------------------------------------------- Lifecycle methods /* * NOTE: There is no maintenance of state or checking for valid transitions * within this class. It is expected that the connector will maintain state * and prevent invalid state transitions. */ @Override public void init() throws Exception { if (getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.init", getName())); if (oname == null) { // Component not pre-registered so register it oname = createObjectName(); if (oname != null) { Registry.getRegistry(null, null).registerComponent(this, oname, null); } } if (this.domain != null) { try { tpOname = new ObjectName(domain + ":" + "type=ThreadPool,name=" + getName()); Registry.getRegistry(null, null).registerComponent(endpoint, tpOname, null); } catch (Exception e) { getLog().error(sm.getString( "abstractProtocolHandler.mbeanRegistrationFailed", tpOname, getName()), e); } rgOname=new ObjectName(domain + ":type=GlobalRequestProcessor,name=" + getName()); Registry.getRegistry(null, null).registerComponent( getHandler().getGlobal(), rgOname, null ); } String endpointName = getName(); endpoint.setName(endpointName.substring(1, endpointName.length()-1)); try { endpoint.init(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.initError", getName()), ex); throw ex; } } @Override public void start() throws Exception { if (getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.start", getName())); try { endpoint.start(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.startError", getName()), ex); throw ex; } } @Override public void pause() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.pause", getName())); try { endpoint.pause(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.pauseError", getName()), ex); throw ex; } } @Override public void resume() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.resume", getName())); try { endpoint.resume(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.resumeError", getName()), ex); throw ex; } } @Override public void stop() throws Exception { if(getLog().isInfoEnabled()) getLog().info(sm.getString("abstractProtocolHandler.stop", getName())); try { endpoint.stop(); } catch (Exception ex) { getLog().error(sm.getString("abstractProtocolHandler.stopError", getName()), ex); throw ex; } } @Override public void destroy() { if(getLog().isInfoEnabled()) { getLog().info(sm.getString("abstractProtocolHandler.destroy", getName())); } try { endpoint.destroy(); } catch (Exception e) { getLog().error(sm.getString("abstractProtocolHandler.destroyError", getName()), e); } if (oname != null) { if (mserver == null) { Registry.getRegistry(null, null).unregisterComponent(oname); } else { // Possibly registered with a different MBeanServer try { mserver.unregisterMBean(oname); } catch (MBeanRegistrationException | InstanceNotFoundException e) { getLog().info(sm.getString( "abstractProtocol.mbeanDeregistrationFailed", oname, mserver)); } } } if (tpOname != null) Registry.getRegistry(null, null).unregisterComponent(tpOname); if (rgOname != null) Registry.getRegistry(null, null).unregisterComponent(rgOname); } // ------------------------------------------- Connection handler base class protected abstract static class AbstractConnectionHandler<S,P extends Processor<S>> implements AbstractEndpoint.Handler { protected abstract Log getLog(); protected final RequestGroupInfo global = new RequestGroupInfo(); protected final AtomicLong registerCount = new AtomicLong(0); protected final ConcurrentHashMap<S,Processor<S>> connections = new ConcurrentHashMap<>(); protected final RecycledProcessors<P,S> recycledProcessors = new RecycledProcessors<>(this); protected abstract AbstractProtocol<S> getProtocol(); @Override public Object getGlobal() { return global; } @Override public void recycle() { recycledProcessors.clear(); } public SocketState process(SocketWrapper<S> wrapper, SocketStatus status) { if (wrapper == null) { // Nothing to do. Socket has been closed. return SocketState.CLOSED; } S socket = wrapper.getSocket(); if (socket == null) { // Nothing to do. Socket has been closed. return SocketState.CLOSED; } Processor<S> processor = connections.get(socket); if (status == SocketStatus.DISCONNECT && processor == null) { // Nothing to do. Endpoint requested a close and there is no // longer a processor associated with this socket. return SocketState.CLOSED; } wrapper.setAsync(false); try { if (processor == null) { processor = recycledProcessors.pop(); } if (processor == null) { processor = createProcessor(); } initSsl(wrapper, processor); SocketState state = SocketState.CLOSED; Iterator<DispatchType> dispatches = null; do { if (dispatches != null) { // Associate the processor with the connection as // these calls may result in a nested call to process() connections.put(socket, processor); DispatchType nextDispatch = dispatches.next(); state = processor.asyncDispatch( nextDispatch.getSocketStatus()); } else if (status == SocketStatus.DISCONNECT && !processor.isComet()) { // Do nothing here, just wait for it to get recycled // Don't do this for Comet we need to generate an end // event (see BZ 54022) } else if (processor.isAsync() || state == SocketState.ASYNC_END) { state = processor.asyncDispatch(status); } else if (processor.isComet()) { state = processor.event(status); } else if (processor.isUpgrade()) { state = processor.upgradeDispatch(status); } else { state = processor.process(wrapper); } if (state != SocketState.CLOSED && processor.isAsync()) { state = processor.asyncPostProcess(); } if (state == SocketState.UPGRADING) { // Get the HTTP upgrade handler HttpUpgradeHandler httpUpgradeHandler = processor.getHttpUpgradeHandler(); // Release the Http11 processor to be re-used release(wrapper, processor, false, false); // Create the upgrade processor processor = createUpgradeProcessor( wrapper, httpUpgradeHandler); // Mark the connection as upgraded wrapper.setUpgraded(true); // Associate with the processor with the connection connections.put(socket, processor); // Initialise the upgrade handler (which may trigger // some IO using the new protocol which is why the lines // above are necessary) // This cast should be safe. If it fails the error // handling for the surrounding try/catch will deal with // it. httpUpgradeHandler.init((WebConnection) processor); } if (getLog().isDebugEnabled()) { getLog().debug("Socket: [" + wrapper + "], Status in: [" + status + "], State out: [" + state + "]"); } if (dispatches == null || !dispatches.hasNext()) { // Only returns non-null iterator if there are // dispatches to process. dispatches = wrapper.getIteratorAndClearDispatches(); } } while (state == SocketState.ASYNC_END || state == SocketState.UPGRADING || dispatches != null && state != SocketState.CLOSED); if (state == SocketState.LONG) { // In the middle of processing a request/response. Keep the // socket associated with the processor. Exact requirements // depend on type of long poll connections.put(socket, processor); longPoll(wrapper, processor); } else if (state == SocketState.OPEN) { // In keep-alive but between requests. OK to recycle // processor. Continue to poll for the next request. connections.remove(socket); release(wrapper, processor, false, true); } else if (state == SocketState.SENDFILE) { // Sendfile in progress. If it fails, the socket will be // closed. If it works, the socket will be re-added to the // poller connections.remove(socket); release(wrapper, processor, false, false); } else if (state == SocketState.UPGRADED) { // Don't add sockets back to the poller if this was a // non-blocking write otherwise the poller may trigger // multiple read events which may lead to thread starvation // in the connector. The write() method will add this socket // to the poller if necessary. if (status != SocketStatus.OPEN_WRITE) { longPoll(wrapper, processor); } } else { // Connection closed. OK to recycle the processor. Upgrade // processors are not recycled. connections.remove(socket); if (processor.isUpgrade()) { processor.getHttpUpgradeHandler().destroy(); } else { release(wrapper, processor, true, false); } } return state; } catch(java.net.SocketException e) { // SocketExceptions are normal getLog().debug(sm.getString( "abstractConnectionHandler.socketexception.debug"), e); } catch (java.io.IOException e) { // IOExceptions are normal getLog().debug(sm.getString( "abstractConnectionHandler.ioexception.debug"), e); } // Future developers: if you discover any other // rare-but-nonfatal exceptions, catch them here, and log as // above. catch (Throwable e) { ExceptionUtils.handleThrowable(e); // any other exception or error is odd. Here we log it // with "ERROR" level, so it will show up even on // less-than-verbose logs. getLog().error( sm.getString("abstractConnectionHandler.error"), e); } // Make sure socket/processor is removed from the list of current // connections connections.remove(socket); // Don't try to add upgrade processors back into the pool if (processor !=null && !processor.isUpgrade()) { release(wrapper, processor, true, false); } return SocketState.CLOSED; } protected abstract P createProcessor(); protected abstract void initSsl(SocketWrapper<S> socket, Processor<S> processor); protected abstract void longPoll(SocketWrapper<S> socket, Processor<S> processor); protected abstract void release(SocketWrapper<S> socket, Processor<S> processor, boolean socketClosing, boolean addToPoller); protected abstract Processor<S> createUpgradeProcessor( SocketWrapper<S> socket, HttpUpgradeHandler httpUpgradeProcessor) throws IOException; protected void register(AbstractProcessor<S> processor) { if (getProtocol().getDomain() != null) { synchronized (this) { try { long count = registerCount.incrementAndGet(); RequestInfo rp = processor.getRequest().getRequestProcessor(); rp.setGlobalProcessor(global); ObjectName rpName = new ObjectName( getProtocol().getDomain() + ":type=RequestProcessor,worker=" + getProtocol().getName() + ",name=" + getProtocol().getProtocolName() + "Request" + count); if (getLog().isDebugEnabled()) { getLog().debug("Register " + rpName); } Registry.getRegistry(null, null).registerComponent(rp, rpName, null); rp.setRpName(rpName); } catch (Exception e) { getLog().warn("Error registering request"); } } } } protected void unregister(Processor<S> processor) { if (getProtocol().getDomain() != null) { synchronized (this) { try { Request r = processor.getRequest(); if (r == null) { // Probably an UpgradeProcessor return; } RequestInfo rp = r.getRequestProcessor(); rp.setGlobalProcessor(null); ObjectName rpName = rp.getRpName(); if (getLog().isDebugEnabled()) { getLog().debug("Unregister " + rpName); } Registry.getRegistry(null, null).unregisterComponent( rpName); rp.setRpName(null); } catch (Exception e) { getLog().warn("Error unregistering request", e); } } } } } protected static class RecycledProcessors<P extends Processor<S>, S> extends SynchronizedStack<Processor<S>> { private final transient AbstractConnectionHandler<S,P> handler; protected final AtomicInteger size = new AtomicInteger(0); public RecycledProcessors(AbstractConnectionHandler<S,P> handler) { this.handler = handler; } @SuppressWarnings("sync-override") // Size may exceed cache size a bit @Override public boolean push(Processor<S> processor) { int cacheSize = handler.getProtocol().getProcessorCache(); boolean offer = cacheSize == -1 ? true : size.get() < cacheSize; //avoid over growing our cache or add after we have stopped boolean result = false; if (offer) { result = super.push(processor); if (result) { size.incrementAndGet(); } } if (!result) handler.unregister(processor); return result; } @SuppressWarnings("sync-override") // OK if size is too big briefly @Override public Processor<S> pop() { Processor<S> result = super.pop(); if (result != null) { size.decrementAndGet(); } return result; } @Override public synchronized void clear() { Processor<S> next = pop(); while (next != null) { handler.unregister(next); next = pop(); } super.clear(); size.set(0); } } }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
java/org/apache/coyote/http11/upgrade/AbstractProcessor.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.IOException; import java.util.concurrent.Executor; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; import org.apache.coyote.Processor; import org.apache.coyote.Request; import org.apache.juli.logging.Log; import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState; import org.apache.tomcat.util.net.SSLSupport; import org.apache.tomcat.util.net.SocketStatus; import org.apache.tomcat.util.net.SocketWrapper; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractProcessor<S> implements Processor<S>, WebConnection { protected static final StringManager sm = StringManager.getManager(Constants.Package); protected abstract Log getLog(); private final HttpUpgradeHandler httpUpgradeHandler; private final AbstractServletInputStream upgradeServletInputStream; private final AbstractServletOutputStream upgradeServletOutputStream; protected AbstractProcessor (HttpUpgradeHandler httpUpgradeHandler, AbstractServletInputStream upgradeServletInputStream, AbstractServletOutputStream upgradeServletOutputStream) { this.httpUpgradeHandler = httpUpgradeHandler; this.upgradeServletInputStream = upgradeServletInputStream; this.upgradeServletOutputStream = upgradeServletOutputStream; } // --------------------------------------------------- AutoCloseable methods @Override public void close() throws Exception { upgradeServletInputStream.close(); upgradeServletOutputStream.close(); } // --------------------------------------------------- WebConnection methods @Override public ServletInputStream getInputStream() throws IOException { return upgradeServletInputStream; } @Override public ServletOutputStream getOutputStream() throws IOException { return upgradeServletOutputStream; } // ------------------------------------------- Implemented Processor methods @Override public final boolean isUpgrade() { return true; } @Override public HttpUpgradeHandler getHttpUpgradeHandler() { return httpUpgradeHandler; } @Override public final SocketState upgradeDispatch(SocketStatus status) throws IOException { if (status == SocketStatus.OPEN_READ) { upgradeServletInputStream.onDataAvailable(); } else if (status == SocketStatus.OPEN_WRITE) { upgradeServletOutputStream.onWritePossible(); } else if (status == SocketStatus.STOP) { try { upgradeServletInputStream.close(); } catch (IOException ioe) { getLog().debug(sm.getString( "abstractProcessor.isCloseFail", ioe)); } try { upgradeServletOutputStream.close(); } catch (IOException ioe) { getLog().debug(sm.getString( "abstractProcessor.osCloseFail", ioe)); } return SocketState.CLOSED; } else { // Unexpected state return SocketState.CLOSED; } if (upgradeServletInputStream.isCloseRequired() || upgradeServletOutputStream.isCloseRequired()) { return SocketState.CLOSED; } return SocketState.UPGRADED; } @Override public final void recycle(boolean socketClosing) { // Currently a NO-OP as upgrade processors are not recycled. } // ---------------------------- Processor methods that are NO-OP for upgrade @Override public final Executor getExecutor() { return null; } @Override public final SocketState process(SocketWrapper<S> socketWrapper) throws IOException { return null; } @Override public final SocketState event(SocketStatus status) throws IOException { return null; } @Override public final SocketState asyncDispatch(SocketStatus status) { return null; } @Override public final SocketState asyncPostProcess() { return null; } @Override public final boolean isComet() { return false; } @Override public final boolean isAsync() { return false; } @Override public final Request getRequest() { return null; } @Override public final void setSslSupport(SSLSupport sslSupport) { // NOOP } }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
java/org/apache/coyote/http11/upgrade/AbstractServletOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.IOException; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; public abstract class AbstractServletOutputStream extends ServletOutputStream { protected static final StringManager sm = StringManager.getManager(Constants.Package); private final Object fireListenerLock = new Object(); private final Object writeLock = new Object(); private volatile boolean closeRequired = false; // Start in blocking-mode private volatile WriteListener listener = null; private volatile boolean fireListener = false; private volatile ClassLoader applicationLoader = null; private volatile byte[] buffer; @Override public final boolean isReady() { if (listener == null) { throw new IllegalStateException( sm.getString("upgrade.sos.canWrite.is")); } // Make sure isReady() and onWritePossible() have a consistent view of // buffer and fireListener when determining if the listener should fire synchronized (fireListenerLock) { boolean result = (buffer == null); fireListener = !result; return result; } } @Override public final void setWriteListener(WriteListener listener) { if (listener == null) { throw new IllegalArgumentException( sm.getString("upgrade.sos.writeListener.null")); } if (this.listener != null) { throw new IllegalArgumentException( sm.getString("upgrade.sos.writeListener.set")); } this.listener = listener; this.applicationLoader = Thread.currentThread().getContextClassLoader(); } protected final boolean isCloseRequired() { return closeRequired; } @Override public void write(int b) throws IOException { synchronized (writeLock) { preWriteChecks(); writeInternal(new byte[] { (byte) b }, 0, 1); } } @Override public void write(byte[] b, int off, int len) throws IOException { synchronized (writeLock) { preWriteChecks(); writeInternal(b, off, len); } } @Override public void close() throws IOException { closeRequired = true; doClose(); } private void preWriteChecks() { if (buffer != null) { throw new IllegalStateException( sm.getString("upgrade.sis.write.ise")); } } /** * Must hold writeLock to call this method. */ private void writeInternal(byte[] b, int off, int len) throws IOException { if (listener == null) { // Simple case - blocking IO doWrite(true, b, off, len); } else { // Non-blocking IO // If the non-blocking read does not complete, doWrite() will add // the socket back into the poller. The poller may trigger a new // write event before this method has finished updating buffer. The // writeLock sync makes sure that buffer is updated before the next // write executes. int written = doWrite(false, b, off, len); if (written < len) { // TODO: - Reuse the buffer // - Only reallocate if it gets too big (>8k?) buffer = new byte[len - written]; System.arraycopy(b, off + written, buffer, 0, len - written); } else { buffer = null; } } } protected final void onWritePossible() throws IOException { synchronized (writeLock) { try { writeInternal(buffer, 0, buffer.length); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); Thread thread = Thread.currentThread(); ClassLoader originalClassLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(applicationLoader); listener.onError(t); } finally { thread.setContextClassLoader(originalClassLoader); } if (t instanceof IOException) { throw t; } else { throw new IOException(t); } } // Make sure isReady() and onWritePossible() have a consistent view of // buffer and fireListener when determining if the listener should fire boolean fire = false; synchronized (fireListenerLock) { if (buffer == null && fireListener) { fireListener = false; fire = true; } } if (fire) { Thread thread = Thread.currentThread(); ClassLoader originalClassLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(applicationLoader); listener.onWritePossible(); } finally { thread.setContextClassLoader(originalClassLoader); } } } } /** * Abstract method to be overridden by concrete implementations. The base * class will ensure that there are no concurrent calls to this method for * the same socket. */ protected abstract int doWrite(boolean block, byte[] b, int off, int len) throws IOException; protected abstract void doFlush() throws IOException; protected abstract void doClose() throws IOException; }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
java/org/apache/coyote/http11/upgrade/AprServletOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.EOFException; import java.io.IOException; import java.nio.ByteBuffer; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; import org.apache.tomcat.jni.OS; import org.apache.tomcat.jni.Socket; import org.apache.tomcat.jni.Status; import org.apache.tomcat.util.net.AprEndpoint; import org.apache.tomcat.util.net.SocketWrapper; public class AprServletOutputStream extends AbstractServletOutputStream { private static final int SSL_OUTPUT_BUFFER_SIZE = 8192; private final AprEndpoint endpoint; private final SocketWrapper<Long> wrapper; private final long socket; private volatile boolean closed = false; private final ByteBuffer sslOutputBuffer; public AprServletOutputStream(SocketWrapper<Long> wrapper, AprEndpoint endpoint) { this.endpoint = endpoint; this.wrapper = wrapper; this.socket = wrapper.getSocket().longValue(); if (endpoint.isSSLEnabled()) { sslOutputBuffer = ByteBuffer.allocateDirect(SSL_OUTPUT_BUFFER_SIZE); sslOutputBuffer.position(SSL_OUTPUT_BUFFER_SIZE); } else { sslOutputBuffer = null; } } @Override protected int doWrite(boolean block, byte[] b, int off, int len) throws IOException { if (closed) { throw new IOException(sm.getString("apr.closed", Long.valueOf(socket))); } Lock readLock = wrapper.getBlockingStatusReadLock(); WriteLock writeLock = wrapper.getBlockingStatusWriteLock(); try { readLock.lock(); if (wrapper.getBlockingStatus() == block) { return doWriteInternal(b, off, len); } } finally { readLock.unlock(); } try { writeLock.lock(); // Set the current settings for this socket wrapper.setBlockingStatus(block); if (block) { Socket.timeoutSet(socket, endpoint.getSoTimeout() * 1000); } else { Socket.timeoutSet(socket, 0); } // Downgrade the lock try { readLock.lock(); writeLock.unlock(); return doWriteInternal(b, off, len); } finally { readLock.unlock(); } } finally { // Should have been released above but may not have been on some // exception paths if (writeLock.isHeldByCurrentThread()) { writeLock.unlock(); } } } private int doWriteInternal(byte[] b, int off, int len) throws IOException { int start = off; int left = len; int written; do { if (endpoint.isSSLEnabled()) { if (sslOutputBuffer.remaining() == 0) { // Buffer was fully written last time around sslOutputBuffer.clear(); if (left < SSL_OUTPUT_BUFFER_SIZE) { sslOutputBuffer.put(b, start, left); } else { sslOutputBuffer.put(b, start, SSL_OUTPUT_BUFFER_SIZE); } sslOutputBuffer.flip(); } else { // Buffer still has data from previous attempt to write // APR + SSL requires that exactly the same parameters are // passed when re-attempting the write } written = Socket.sendb(socket, sslOutputBuffer, sslOutputBuffer.position(), sslOutputBuffer.limit()); if (written > 0) { sslOutputBuffer.position( sslOutputBuffer.position() + written); } } else { written = Socket.send(socket, b, start, left); } if (Status.APR_STATUS_IS_EAGAIN(-written)) { written = 0; } else if (-written == Status.APR_EOF) { throw new EOFException(sm.getString("apr.clientAbort")); } else if ((OS.IS_WIN32 || OS.IS_WIN64) && (-written == Status.APR_OS_START_SYSERR + 10053)) { // 10053 on Windows is connection aborted throw new EOFException(sm.getString("apr.clientAbort")); } else if (written < 0) { throw new IOException(sm.getString("apr.write.error", Integer.valueOf(-written), Long.valueOf(socket), wrapper)); } start += written; left -= written; } while (written > 0 && left > 0); if (left > 0) { endpoint.getPoller().add(socket, -1, false, true); } return len - left; } @Override protected void doFlush() throws IOException { // TODO Auto-generated method stub } @Override protected void doClose() throws IOException { closed = true; // AbstractProcessor needs to trigger the close as multiple closes for // APR/native sockets will cause problems. } }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
java/org/apache/coyote/http11/upgrade/BioServletOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.IOException; import java.io.OutputStream; import java.net.Socket; import org.apache.tomcat.util.net.SocketWrapper; public class BioServletOutputStream extends AbstractServletOutputStream { private final OutputStream os; public BioServletOutputStream(SocketWrapper<Socket> wrapper) throws IOException { os = wrapper.getSocket().getOutputStream(); } @Override protected int doWrite(boolean block, byte[] b, int off, int len) throws IOException { os.write(b, off, len); return len; } @Override protected void doFlush() throws IOException { os.flush(); } @Override protected void doClose() throws IOException { os.close(); } }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
java/org/apache/coyote/http11/upgrade/NioServletOutputStream.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.IOException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import org.apache.tomcat.util.net.NioChannel; import org.apache.tomcat.util.net.NioEndpoint; import org.apache.tomcat.util.net.NioSelectorPool; import org.apache.tomcat.util.net.SocketWrapper; public class NioServletOutputStream extends AbstractServletOutputStream { private final NioChannel channel; private final NioSelectorPool pool; private final int maxWrite; public NioServletOutputStream( SocketWrapper<NioChannel> wrapper, NioSelectorPool pool) { channel = wrapper.getSocket(); this.pool = pool; maxWrite = channel.getBufHandler().getWriteBuffer().capacity(); } @Override protected int doWrite(boolean block, byte[] b, int off, int len) throws IOException { int leftToWrite = len; int count = 0; int offset = off; while (leftToWrite > 0) { int writeThisLoop; int writtenThisLoop; if (leftToWrite > maxWrite) { writeThisLoop = maxWrite; } else { writeThisLoop = leftToWrite; } writtenThisLoop = doWriteInternal(block, b, offset, writeThisLoop); count += writtenThisLoop; offset += writtenThisLoop; leftToWrite -= writtenThisLoop; if (writtenThisLoop < writeThisLoop) { break; } } return count; } private int doWriteInternal (boolean block, byte[] b, int off, int len) throws IOException { channel.getBufHandler().getWriteBuffer().clear(); channel.getBufHandler().getWriteBuffer().put(b, off, len); channel.getBufHandler().getWriteBuffer().flip(); int written = 0; NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) channel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getWriteTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { written = pool.write(channel.getBufHandler().getWriteBuffer(), channel, selector, writeTimeout, block); } finally { if (selector != null) { pool.put(selector); } } if (written < len) { channel.getPoller().add(channel, SelectionKey.OP_WRITE); } return written; } @Override protected void doFlush() throws IOException { NioEndpoint.KeyAttachment att = (NioEndpoint.KeyAttachment) channel.getAttachment(false); if (att == null) { throw new IOException("Key must be cancelled"); } long writeTimeout = att.getWriteTimeout(); Selector selector = null; try { selector = pool.get(); } catch ( IOException x ) { //ignore } try { do { if (channel.flush(true, selector, writeTimeout)) { break; } } while (true); } finally { if (selector != null) { pool.put(selector); } } } @Override protected void doClose() throws IOException { channel.close(); } }
55,978
Bug 55978 Initial call to onWritePossible() not made by container when using HTTP upgrade
When using a WriteListener and non-blocking IO with the Servlet async API, the container makes the first call to onWritePossible() as per the spec. When using a WriteListener and non-blocking IO with the Servlet HTTP upgrade API the container does not make the initial call to onWritePossible(). When fixing this bug it is worth checking the initial call to onDataAvailable() as well.
resolved fixed
bd24edc
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T11:43:02Z
2014-01-08T16:53:20Z
test/org/apache/coyote/http11/upgrade/TestUpgrade.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.coyote.http11.upgrade; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Writer; import java.net.Socket; import javax.net.SocketFactory; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.WriteListener; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpUpgradeHandler; import javax.servlet.http.WebConnection; import org.junit.Assert; import org.junit.Test; import static org.apache.catalina.startup.SimpleHttpClient.CRLF; import org.apache.catalina.Context; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.catalina.util.IOTools; public class TestUpgrade extends TomcatBaseTest { private static final String MESSAGE = "This is a test."; @Test public void testSimpleUpgradeBlocking() throws Exception { doUpgrade(EchoBlocking.class); } @Test public void testSimpleUpgradeNonBlocking() throws Exception { doUpgrade(EchoNonBlocking.class); } @Test public void testMessagesBlocking() throws Exception { doTestMessages(EchoBlocking.class); } @Test public void testMessagesNonBlocking() throws Exception { doTestMessages(EchoNonBlocking.class); } @Test public void testSetNullReadListener() throws Exception { doTestCheckClosed(SetNullReadListener.class); } @Test public void testSetNullWriteListener() throws Exception { doTestCheckClosed(SetNullWriteListener.class); } @Test public void testSetReadListenerTwice() throws Exception { doTestCheckClosed(SetReadListenerTwice.class); } @Test public void testSetWriteListenerTwice() throws Exception { doTestCheckClosed(SetWriteListenerTwice.class); } private void doTestCheckClosed( Class<? extends HttpUpgradeHandler> upgradeHandlerClass) throws Exception { UpgradeConnection conn = doUpgrade(upgradeHandlerClass); Reader r = conn.getReader(); int c = r.read(); Assert.assertEquals(-1, c); } private void doTestMessages ( Class<? extends HttpUpgradeHandler> upgradeHandlerClass) throws Exception { UpgradeConnection conn = doUpgrade(upgradeHandlerClass); PrintWriter pw = new PrintWriter(conn.getWriter()); BufferedReader reader = conn.getReader(); pw.println(MESSAGE); pw.flush(); Thread.sleep(500); pw.println(MESSAGE); pw.flush(); // Note: BufferedReader.readLine() strips new lines // ServletInputStream.readLine() does not strip new lines String response = reader.readLine(); Assert.assertEquals(MESSAGE, response); response = reader.readLine(); Assert.assertEquals(MESSAGE, response); } private UpgradeConnection doUpgrade( Class<? extends HttpUpgradeHandler> upgradeHandlerClass) 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")); UpgradeServlet servlet = new UpgradeServlet(upgradeHandlerClass); Tomcat.addServlet(ctx, "servlet", servlet); ctx.addServletMapping("/", "servlet"); tomcat.start(); // Use raw socket so the necessary control is available after the HTTP // upgrade Socket socket = SocketFactory.getDefault().createSocket("localhost", getPort()); socket.setSoTimeout(5000); InputStream is = socket.getInputStream(); OutputStream os = socket.getOutputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); Writer writer = new OutputStreamWriter(os); writer.write("GET / HTTP/1.1" + CRLF); writer.write("Host: whatever" + CRLF); writer.write(CRLF); writer.flush(); String status = reader.readLine(); Assert.assertNotNull(status); Assert.assertEquals("HTTP/1.1 101 Switching Protocols", status.substring(0, 32)); // Skip the remaining response headers String line = reader.readLine(); while (line != null && line.length() > 0) { // Skip line = reader.readLine(); } return new UpgradeConnection(writer, reader); } private static class UpgradeServlet extends HttpServlet { private static final long serialVersionUID = 1L; private final Class<? extends HttpUpgradeHandler> upgradeHandlerClass; public UpgradeServlet(Class<? extends HttpUpgradeHandler> upgradeHandlerClass) { this.upgradeHandlerClass = upgradeHandlerClass; } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.upgrade(upgradeHandlerClass); } } private static class UpgradeConnection { private final Writer writer; private final BufferedReader reader; public UpgradeConnection(Writer writer, BufferedReader reader) { this.writer = writer; this.reader = reader; } public Writer getWriter() { return writer; } public BufferedReader getReader() { return reader; } } public static class EchoBlocking implements HttpUpgradeHandler { @Override public void init(WebConnection connection) { try (ServletInputStream sis = connection.getInputStream(); ServletOutputStream sos = connection.getOutputStream()){ IOTools.flow(sis, sos); } catch (IOException ioe) { throw new IllegalStateException(ioe); } } @Override public void destroy() { // NO-OP } } public static class EchoNonBlocking implements HttpUpgradeHandler { private ServletInputStream sis; private ServletOutputStream sos; @Override public void init(WebConnection connection) { try { sis = connection.getInputStream(); sos = connection.getOutputStream(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } sis.setReadListener(new EchoReadListener()); sos.setWriteListener(new NoOpWriteListener()); } @Override public void destroy() { // NO-OP } private class EchoReadListener extends NoOpReadListener { private byte[] buffer = new byte[8096]; @Override public void onDataAvailable() { try { while (sis.isReady()) { int read = sis.read(buffer); if (read > 0) { if (sos.isReady()) { sos.write(buffer, 0, read); } else { throw new IOException("Unable to echo data. " + "canWrite() returned false"); } } } } catch (IOException ioe) { throw new RuntimeException(ioe); } } } } public static class SetNullReadListener implements HttpUpgradeHandler { @Override public void init(WebConnection connection) { ServletInputStream sis; try { sis = connection.getInputStream(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } sis.setReadListener(null); } @Override public void destroy() { // NO-OP } } public static class SetNullWriteListener implements HttpUpgradeHandler { @Override public void init(WebConnection connection) { ServletOutputStream sos; try { sos = connection.getOutputStream(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } sos.setWriteListener(null); } @Override public void destroy() { // NO-OP } } public static class SetReadListenerTwice implements HttpUpgradeHandler { @Override public void init(WebConnection connection) { ServletInputStream sis; ServletOutputStream sos; try { sis = connection.getInputStream(); sos = connection.getOutputStream(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } sos.setWriteListener(new NoOpWriteListener()); ReadListener rl = new NoOpReadListener(); sis.setReadListener(rl); sis.setReadListener(rl); } @Override public void destroy() { // NO-OP } } public static class SetWriteListenerTwice implements HttpUpgradeHandler { @Override public void init(WebConnection connection) { ServletInputStream sis; ServletOutputStream sos; try { sis = connection.getInputStream(); sos = connection.getOutputStream(); } catch (IOException ioe) { throw new IllegalStateException(ioe); } sis.setReadListener(new NoOpReadListener()); WriteListener wl = new NoOpWriteListener(); sos.setWriteListener(wl); sos.setWriteListener(wl); } @Override public void destroy() { // NO-OP } } private static class NoOpReadListener implements ReadListener { @Override public void onDataAvailable() { // NO-OP } @Override public void onAllDataRead() { // Always NO-OP for HTTP Upgrade } @Override public void onError(Throwable throwable) { // NO-OP } } private static class NoOpWriteListener implements WriteListener { @Override public void onWritePossible() { // NO-OP } @Override public void onError(Throwable throwable) { // NO-OP } } }
55,893
Bug 55893 Split AccessLogValve and extract the formatting logic in an AbstractAccessLogValve
null
resolved fixed
92ce68a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T13:09:50Z
2013-12-17T03:13:20Z
java/org/apache/catalina/valves/AbstractAccessLogValve.java
55,893
Bug 55893 Split AccessLogValve and extract the formatting logic in an AbstractAccessLogValve
null
resolved fixed
92ce68a
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-10T13:09:50Z
2013-12-17T03:13:20Z
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.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import org.apache.catalina.AccessLog; import org.apache.catalina.Globals; import org.apache.catalina.LifecycleException; import org.apache.catalina.LifecycleState; import org.apache.catalina.Session; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.coyote.RequestInfo; import org.apache.juli.logging.Log; import org.apache.juli.logging.LogFactory; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.buf.B2CConverter; import org.apache.tomcat.util.collections.SynchronizedStack; /** * <p>Implementation of the <b>Valve</b> interface that generates a web server * access log with the detailed line contents matching a configurable pattern. * The syntax of the available patterns is similar to that supported by the * <a href="http://httpd.apache.org/">Apache HTTP Server</a> * <code>mod_log_config</code> module. As an additional feature, * automatic rollover of log files when the date changes is also supported.</p> * * <p>Patterns for the logged message may include constant text or any of the * following replacement strings, for which the corresponding information * from the specified Response is substituted:</p> * <ul> * <li><b>%a</b> - Remote IP address * <li><b>%A</b> - Local IP address * <li><b>%b</b> - Bytes sent, excluding HTTP headers, or '-' if no bytes * were sent * <li><b>%B</b> - Bytes sent, excluding HTTP headers * <li><b>%h</b> - Remote host name (or IP address if * <code>enableLookups</code> for the connector is false) * <li><b>%H</b> - Request protocol * <li><b>%l</b> - Remote logical username from identd (always returns '-') * <li><b>%m</b> - Request method * <li><b>%p</b> - Local port * <li><b>%q</b> - Query string (prepended with a '?' if it exists, otherwise * an empty string * <li><b>%r</b> - First line of the request * <li><b>%s</b> - HTTP status code of the response * <li><b>%S</b> - User session ID * <li><b>%t</b> - Date and time, in Common Log Format format * <li><b>%t{format}</b> - Date and time, in any format supported by SimpleDateFormat * <li><b>%u</b> - Remote user that was authenticated * <li><b>%U</b> - Requested URL path * <li><b>%v</b> - Local server name * <li><b>%D</b> - Time taken to process the request, in millis * <li><b>%T</b> - Time taken to process the request, in seconds * <li><b>%I</b> - current Request thread name (can compare later with stacktraces) * </ul> * <p>In addition, the caller can specify one of the following aliases for * commonly utilized patterns:</p> * <ul> * <li><b>common</b> - <code>%h %l %u %t "%r" %s %b</code> * <li><b>combined</b> - * <code>%h %l %u %t "%r" %s %b "%{Referer}i" "%{User-Agent}i"</code> * </ul> * * <p> * There is also support to write information from the cookie, incoming * header, the Session or something else in the ServletRequest.<br> * It is modeled after the * <a href="http://httpd.apache.org/">Apache HTTP Server</a> log configuration * syntax:</p> * <ul> * <li><code>%{xxx}i</code> for incoming headers * <li><code>%{xxx}o</code> for outgoing response headers * <li><code>%{xxx}c</code> for a specific cookie * <li><code>%{xxx}r</code> xxx is an attribute in the ServletRequest * <li><code>%{xxx}s</code> xxx is an attribute in the HttpSession * <li><code>%{xxx}t</code> xxx is an enhanced SimpleDateFormat pattern * (see Configuration Reference document for details on supported time patterns) * </ul> * * <p> * Log rotation can be on or off. This is dictated by the * <code>rotatable</code> property. * </p> * * <p> * For UNIX users, another field called <code>checkExists</code> is also * available. If set to true, the log file's existence will be checked before * each logging. This way an external log rotator can move the file * somewhere and Tomcat will start with a new file. * </p> * * <p> * For JMX junkies, a public method called <code>rotate</code> has * been made available to allow you to tell this instance to move * the existing log file to somewhere else and start writing a new log file. * </p> * * <p> * Conditional logging is also supported. This can be done with the * <code>conditionUnless</code> and <code>conditionIf</code> properties. * If the value returned from ServletRequest.getAttribute(conditionUnless) * yields a non-null value, the logging will be skipped. * If the value returned from ServletRequest.getAttribute(conditionIf) * yields the null value, the logging will be skipped. * The <code>condition</code> attribute is synonym for * <code>conditionUnless</code> and is provided for backwards compatibility. * </p> * * <p> * For extended attributes coming from a getAttribute() call, * it is you responsibility to ensure there are no newline or * control characters. * </p> * * @author Craig R. McClanahan * @author Jason Brittain * @author Remy Maucherat * @author Takayuki Kaneko * @author Peter Rossbach * * @version $Id$ */ public class AccessLogValve extends ValveBase implements AccessLog { private static final Log log = LogFactory.getLog(AccessLogValve.class); //------------------------------------------------------ Constructor public AccessLogValve() { super(true); } // ----------------------------------------------------- Instance Variables /** * The as-of date for the currently open log file, or a zero-length * string if there is no open log file. */ private volatile String dateStamp = ""; /** * The directory in which log files are created. */ private String directory = "logs"; /** * enabled this component */ protected boolean enabled = true; /** * The pattern used to format our access log lines. */ protected String pattern = null; /** * The prefix that is added to log file filenames. */ protected String prefix = "access_log"; /** * Should we rotate our log file? Default is true (like old behavior) */ protected boolean rotatable = true; /** * Should we defer inclusion of the date stamp in the file * name until rotate time? Default is false. */ protected boolean renameOnRotate = false; /** * Buffered logging. */ private boolean buffered = true; /** * The suffix that is added to log file filenames. */ protected String suffix = ""; /** * The PrintWriter to which we are currently logging, if any. */ protected PrintWriter writer = null; /** * A date formatter to format a Date using the format * given by <code>fileDateFormat</code>. */ protected SimpleDateFormat fileDateFormatter = null; /** * The size of our global date format cache */ private static final int globalCacheSize = 300; /** * The size of our thread local date format cache */ private static final int localCacheSize = 60; /** * The current log file we are writing to. Helpful when checkExists * is true. */ protected File currentLogFile = null; /** * <p>Cache structure for formatted timestamps based on seconds.</p> * * <p>The cache consists of entries for a consecutive range of * seconds. The length of the range is configurable. It is * implemented based on a cyclic buffer. New entries shift the range.</p> * * <p>There is one cache for the CLF format (the access log standard * format) and a HashMap of caches for additional formats used by * SimpleDateFormat.</p> * * <p>Although the cache supports specifying a locale when retrieving a * formatted timestamp, each format will always use the locale given * when the format was first used. New locales can only be used for new formats. * The CLF format will always be formatted using the locale * <code>en_US</code>.</p> * * <p>The cache is not threadsafe. It can be used without synchronization * via thread local instances, or with synchronization as a global cache.</p> * * <p>The cache can be created with a parent cache to build a cache hierarchy. * Access to the parent cache is threadsafe.</p> * * <p>This class uses a small thread local first level cache and a bigger * synchronized global second level cache.</p> */ protected static class DateFormatCache { protected class Cache { /* CLF log format */ private static final String cLFFormat = "dd/MMM/yyyy:HH:mm:ss Z"; /* Second used to retrieve CLF format in most recent invocation */ private long previousSeconds = Long.MIN_VALUE; /* Value of CLF format retrieved in most recent invocation */ private String previousFormat = ""; /* First second contained in cache */ private long first = Long.MIN_VALUE; /* Last second contained in cache */ private long last = Long.MIN_VALUE; /* Index of "first" in the cyclic cache */ private int offset = 0; /* Helper object to be able to call SimpleDateFormat.format(). */ private final Date currentDate = new Date(); protected final String cache[]; private SimpleDateFormat formatter; private boolean isCLF = false; private Cache parent = null; private Cache(Cache parent) { this(null, parent); } private Cache(String format, Cache parent) { this(format, null, parent); } private Cache(String format, Locale loc, Cache parent) { cache = new String[cacheSize]; for (int i = 0; i < cacheSize; i++) { cache[i] = null; } if (loc == null) { loc = cacheDefaultLocale; } if (format == null) { isCLF = true; format = cLFFormat; formatter = new SimpleDateFormat(format, Locale.US); } else { formatter = new SimpleDateFormat(format, loc); } formatter.setTimeZone(TimeZone.getDefault()); this.parent = parent; } private String getFormatInternal(long time) { long seconds = time / 1000; /* First step: if we have seen this timestamp during the previous call, and we need CLF, return the previous value. */ if (seconds == previousSeconds) { return previousFormat; } /* Second step: Try to locate in cache */ previousSeconds = seconds; int index = (offset + (int)(seconds - first)) % cacheSize; if (index < 0) { index += cacheSize; } if (seconds >= first && seconds <= last) { if (cache[index] != null) { /* Found, so remember for next call and return.*/ previousFormat = cache[index]; return previousFormat; } /* Third step: not found in cache, adjust cache and add item */ } else if (seconds >= last + cacheSize || seconds <= first - cacheSize) { first = seconds; last = first + cacheSize - 1; index = 0; offset = 0; for (int i = 1; i < cacheSize; i++) { cache[i] = null; } } else if (seconds > last) { for (int i = 1; i < seconds - last; i++) { cache[(index + cacheSize - i) % cacheSize] = null; } first = seconds - (cacheSize - 1); last = seconds; offset = (index + 1) % cacheSize; } else if (seconds < first) { for (int i = 1; i < first - seconds; i++) { cache[(index + i) % cacheSize] = null; } first = seconds; last = seconds + (cacheSize - 1); offset = index; } /* Last step: format new timestamp either using * parent cache or locally. */ if (parent != null) { synchronized(parent) { previousFormat = parent.getFormatInternal(time); } } else { currentDate.setTime(time); previousFormat = formatter.format(currentDate); if (isCLF) { StringBuilder current = new StringBuilder(32); current.append('['); current.append(previousFormat); current.append(']'); previousFormat = current.toString(); } } cache[index] = previousFormat; return previousFormat; } } /* Number of cached entries */ private int cacheSize = 0; private final Locale cacheDefaultLocale; private final DateFormatCache parent; protected final Cache cLFCache; private final HashMap<String, Cache> formatCache = new HashMap<>(); protected DateFormatCache(int size, Locale loc, DateFormatCache parent) { cacheSize = size; cacheDefaultLocale = loc; this.parent = parent; Cache parentCache = null; if (parent != null) { synchronized(parent) { parentCache = parent.getCache(null, null); } } cLFCache = new Cache(parentCache); } private Cache getCache(String format, Locale loc) { Cache cache; if (format == null) { cache = cLFCache; } else { cache = formatCache.get(format); if (cache == null) { Cache parentCache = null; if (parent != null) { synchronized(parent) { parentCache = parent.getCache(format, loc); } } cache = new Cache(format, loc, parentCache); formatCache.put(format, cache); } } return cache; } public String getFormat(long time) { return cLFCache.getFormatInternal(time); } public String getFormat(String format, Locale loc, long time) { return getCache(format, loc).getFormatInternal(time); } } /** * Global date format cache. */ private static final DateFormatCache globalDateCache = new DateFormatCache(globalCacheSize, Locale.getDefault(), null); /** * Thread local date format cache. */ private static final ThreadLocal<DateFormatCache> localDateCache = new ThreadLocal<DateFormatCache>() { @Override protected DateFormatCache initialValue() { return new DateFormatCache(localCacheSize, Locale.getDefault(), globalDateCache); } }; /** * The system time when we last updated the Date that this valve * uses for log lines. */ private static final ThreadLocal<Date> localDate = new ThreadLocal<Date>() { @Override protected Date initialValue() { return new Date(); } }; /** * The list of our format types. */ private static enum FormatType { CLF, SEC, MSEC, MSEC_FRAC, SDF } /** * Instant when the log daily rotation was last checked. */ private volatile long rotationLastChecked = 0L; /** * Do we check for log file existence? Helpful if an external * agent renames the log file so we can automagically recreate it. */ private boolean checkExists = false; /** * Are we doing conditional logging. default null. * It is the value of <code>conditionUnless</code> property. */ protected String condition = null; /** * Are we doing conditional logging. default null. * It is the value of <code>conditionIf</code> property. */ protected String conditionIf = null; /** * Date format to place in log file name. */ protected String fileDateFormat = ".yyyy-MM-dd"; /** * Name of locale used to format timestamps in log entries and in * log file name suffix. */ protected String localeName = Locale.getDefault().toString(); /** * Locale used to format timestamps in log entries and in * log file name suffix. */ protected Locale locale = Locale.getDefault(); /** * Character set used by the log file. If it is <code>null</code>, the * system default character set will be used. An empty string will be * treated as <code>null</code> when this property is assigned. */ protected String encoding = null; /** * Array of AccessLogElement, they will be used to make log message. */ protected AccessLogElement[] logElements = null; /** * @see #setRequestAttributesEnabled(boolean) */ protected boolean requestAttributesEnabled = false; /** * Buffer pool used for log message generation. Pool used to reduce garbage * generation. */ private SynchronizedStack<CharArrayWriter> charArrayWriters = new SynchronizedStack<>(); /** * Log message buffers are usually recycled and re-used. To prevent * excessive memory usage, if a buffer grows beyond this size it will be * discarded. The default is 256 characters. This should be set to larger * than the typical access log message size. */ private int maxLogMessageBufferSize = 256; // ------------------------------------------------------------- Properties public int getMaxLogMessageBufferSize() { return maxLogMessageBufferSize; } public void setMaxLogMessageBufferSize(int maxLogMessageBufferSize) { this.maxLogMessageBufferSize = maxLogMessageBufferSize; } /** * {@inheritDoc} */ @Override public void setRequestAttributesEnabled(boolean requestAttributesEnabled) { this.requestAttributesEnabled = requestAttributesEnabled; } /** * {@inheritDoc} */ @Override public boolean getRequestAttributesEnabled() { return requestAttributesEnabled; } /** * @return Returns the enabled. */ public boolean getEnabled() { return enabled; } /** * @param enabled * The enabled to set. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Return the directory in which we create log files. */ public String getDirectory() { return (directory); } /** * Set the directory in which we create log files. * * @param directory The new log file directory */ public void setDirectory(String directory) { this.directory = directory; } /** * Return the format pattern. */ public String getPattern() { return (this.pattern); } /** * Set the format pattern, first translating any recognized alias. * * @param pattern The new pattern */ public void setPattern(String pattern) { if (pattern == null) { this.pattern = ""; } else if (pattern.equals(Constants.AccessLog.COMMON_ALIAS)) { this.pattern = Constants.AccessLog.COMMON_PATTERN; } else if (pattern.equals(Constants.AccessLog.COMBINED_ALIAS)) { this.pattern = Constants.AccessLog.COMBINED_PATTERN; } else { this.pattern = pattern; } logElements = createLogElements(); } /** * Check for file existence before logging. */ public boolean isCheckExists() { return checkExists; } /** * Set whether to check for log file existence before logging. * * @param checkExists true meaning to check for file existence. */ public void setCheckExists(boolean checkExists) { this.checkExists = checkExists; } /** * Return the log file prefix. */ public String getPrefix() { return (prefix); } /** * Set the log file prefix. * * @param prefix The new log file prefix */ public void setPrefix(String prefix) { this.prefix = prefix; } /** * Should we rotate the logs */ public boolean isRotatable() { return rotatable; } /** * Set the value is we should we rotate the logs * * @param rotatable true is we should rotate. */ public void setRotatable(boolean rotatable) { this.rotatable = rotatable; } /** * Should we defer inclusion of the date stamp in the file * name until rotate time */ public boolean isRenameOnRotate() { return renameOnRotate; } /** * Set the value if we should defer inclusion of the date * stamp in the file name until rotate time * * @param renameOnRotate true if defer inclusion of date stamp */ public void setRenameOnRotate(boolean renameOnRotate) { this.renameOnRotate = renameOnRotate; } /** * Is the logging buffered */ public boolean isBuffered() { return buffered; } /** * Set the value if the logging should be buffered * * @param buffered true if buffered. */ public void setBuffered(boolean buffered) { this.buffered = buffered; } /** * Return the log file suffix. */ public String getSuffix() { return (suffix); } /** * Set the log file suffix. * * @param suffix The new log file suffix */ public void setSuffix(String suffix) { this.suffix = suffix; } /** * Return whether the attribute name to look for when * performing conditional logging. If null, every * request is logged. */ public String getCondition() { return condition; } /** * Set the ServletRequest.attribute to look for to perform * conditional logging. Set to null to log everything. * * @param condition Set to null to log everything */ public void setCondition(String condition) { this.condition = condition; } /** * Return whether the attribute name to look for when * performing conditional logging. If null, every * request is logged. */ public String getConditionUnless() { return getCondition(); } /** * Set the ServletRequest.attribute to look for to perform * conditional logging. Set to null to log everything. * * @param condition Set to null to log everything */ public void setConditionUnless(String condition) { setCondition(condition); } /** * Return whether the attribute name to look for when * performing conditional logging. If null, every * request is logged. */ public String getConditionIf() { return conditionIf; } /** * Set the ServletRequest.attribute to look for to perform * conditional logging. Set to null to log everything. * * @param condition Set to null to log everything */ public void setConditionIf(String condition) { this.conditionIf = condition; } /** * Return the date format date based log rotation. */ public String getFileDateFormat() { return fileDateFormat; } /** * Set the date format date based log rotation. */ public void setFileDateFormat(String fileDateFormat) { String newFormat; if (fileDateFormat == null) { newFormat = ""; } else { newFormat = fileDateFormat; } this.fileDateFormat = newFormat; synchronized (this) { fileDateFormatter = new SimpleDateFormat(newFormat, Locale.US); fileDateFormatter.setTimeZone(TimeZone.getDefault()); } } /** * Return the locale used to format timestamps in log entries and in * log file name suffix. */ public String getLocale() { return localeName; } /** * Set the locale used to format timestamps in log entries and in * log file name suffix. Changing the locale is only supported * as long as the AccessLogValve has not logged anything. Changing * the locale later can lead to inconsistent formatting. * * @param localeName The locale to use. */ public void setLocale(String localeName) { this.localeName = localeName; locale = findLocale(localeName, locale); } /** * Return the character set name that is used to write the log file. * * @return Character set name, or <code>null</code> if the system default * character set is used. */ public String getEncoding() { return encoding; } /** * Set the character set that is used to write the log file. * * @param encoding The name of the character set. */ public void setEncoding(String encoding) { if (encoding != null && encoding.length() > 0) { this.encoding = encoding; } else { this.encoding = null; } } // --------------------------------------------------------- Public Methods /** * Execute a periodic task, such as reloading, etc. This method will be * invoked inside the classloading context of this container. Unexpected * throwables will be caught and logged. */ @Override public synchronized void backgroundProcess() { if (getState().isAvailable() && getEnabled() && writer != null && buffered) { writer.flush(); } } /** * Log a message summarizing the specified request and response, according * to the format specified by the <code>pattern</code> property. * * @param request Request being processed * @param response Response being processed * * @exception IOException if an input/output error has occurred * @exception ServletException if a servlet error has occurred */ @Override public void invoke(Request request, Response response) throws IOException, ServletException { getNext().invoke(request, response); } @Override public void log(Request request, Response response, long time) { if (!getState().isAvailable() || !getEnabled() || logElements == null || condition != null && null != request.getRequest().getAttribute(condition) || conditionIf != null && null == request.getRequest().getAttribute(conditionIf)) { return; } /** * XXX This is a bit silly, but we want to have start and stop time and * duration consistent. It would be better to keep start and stop * simply in the request and/or response object and remove time * (duration) from the interface. */ long start = request.getCoyoteRequest().getStartTime(); Date date = getDate(start + time); CharArrayWriter result = charArrayWriters.pop(); if (result == null) { result = new CharArrayWriter(128); } for (int i = 0; i < logElements.length; i++) { logElements[i].addElement(result, date, request, response, time); } log(result); if (result.size() <= maxLogMessageBufferSize) { result.reset(); charArrayWriters.push(result); } } /** * Rotate the log file if necessary. */ public void rotate() { if (rotatable) { // Only do a logfile switch check once a second, max. long systime = System.currentTimeMillis(); if ((systime - rotationLastChecked) > 1000) { synchronized(this) { if ((systime - rotationLastChecked) > 1000) { rotationLastChecked = systime; String tsDate; // Check for a change of date tsDate = fileDateFormatter.format(new Date(systime)); // If the date has changed, switch log files if (!dateStamp.equals(tsDate)) { close(true); dateStamp = tsDate; open(); } } } } } } /** * Rename the existing log file to something else. Then open the * old log file name up once again. Intended to be called by a JMX * agent. * * * @param newFileName The file name to move the log file entry to * @return true if a file was rotated with no error */ public synchronized boolean rotate(String newFileName) { if (currentLogFile != null) { File holder = currentLogFile; close(false); try { holder.renameTo(new File(newFileName)); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.rotateFail"), e); } /* Make sure date is correct */ dateStamp = fileDateFormatter.format( new Date(System.currentTimeMillis())); open(); return true; } else { return false; } } // -------------------------------------------------------- Private Methods /** * Create a File object based on the current log file name. * Directories are created as needed but the underlying file * is not created or opened. * * @param useDateStamp include the timestamp in the file name. * @return the log file object */ private File getLogFile(boolean useDateStamp) { // Create the directory if necessary File dir = new File(directory); if (!dir.isAbsolute()) { dir = new File(getContainer().getCatalinaBase(), directory); } if (!dir.mkdirs() && !dir.isDirectory()) { log.error(sm.getString("accessLogValve.openDirFail", dir)); } // Calculate the current log file name File pathname; if (useDateStamp) { pathname = new File(dir.getAbsoluteFile(), prefix + dateStamp + suffix); } else { pathname = new File(dir.getAbsoluteFile(), prefix + suffix); } File parent = pathname.getParentFile(); if (!parent.mkdirs() && !parent.isDirectory()) { log.error(sm.getString("accessLogValve.openDirFail", parent)); } return pathname; } /** * Move a current but rotated log file back to the unrotated * one. Needed if date stamp inclusion is deferred to rotation * time. */ private void restore() { File newLogFile = getLogFile(false); File rotatedLogFile = getLogFile(true); if (rotatedLogFile.exists() && !newLogFile.exists() && !rotatedLogFile.equals(newLogFile)) { try { if (!rotatedLogFile.renameTo(newLogFile)) { log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile)); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.renameFail", rotatedLogFile, newLogFile), e); } } } /** * Close the currently open log file (if any) * * @param rename Rename file to final name after closing */ private synchronized void close(boolean rename) { if (writer == null) { return; } writer.flush(); writer.close(); if (rename && renameOnRotate) { File newLogFile = getLogFile(true); if (!newLogFile.exists()) { try { if (!currentLogFile.renameTo(newLogFile)) { log.error(sm.getString("accessLogValve.renameFail", currentLogFile, newLogFile)); } } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.error(sm.getString("accessLogValve.renameFail", currentLogFile, newLogFile), e); } } else { log.error(sm.getString("accessLogValve.alreadyExists", currentLogFile, newLogFile)); } } writer = null; dateStamp = ""; currentLogFile = null; } /** * Log the specified message to the log file, switching files if the date * has changed since the previous log call. * * @param message Message to be logged */ public void log(CharArrayWriter message) { rotate(); /* In case something external rotated the file instead */ if (checkExists) { synchronized (this) { if (currentLogFile != null && !currentLogFile.exists()) { try { close(false); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); log.info(sm.getString("accessLogValve.closeFail"), e); } /* Make sure date is correct */ dateStamp = fileDateFormatter.format( new Date(System.currentTimeMillis())); open(); } } } // Log this message try { synchronized(this) { if (writer != null) { message.writeTo(writer); writer.println(""); if (!buffered) { writer.flush(); } } } } catch (IOException ioe) { log.warn(sm.getString( "accessLogValve.writeFail", message.toString()), ioe); } } /** * Open the new log file for the date specified by <code>dateStamp</code>. */ protected synchronized void open() { // Open the current log file // If no rotate - no need for dateStamp in fileName File pathname = getLogFile(rotatable && !renameOnRotate); Charset charset = null; if (encoding != null) { try { charset = B2CConverter.getCharset(encoding); } catch (UnsupportedEncodingException ex) { log.error(sm.getString( "accessLogValve.unsupportedEncoding", encoding), ex); } } if (charset == null) { charset = StandardCharsets.ISO_8859_1; } try { writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter( new FileOutputStream(pathname, true), charset), 128000), false); currentLogFile = pathname; } catch (IOException e) { writer = null; currentLogFile = null; log.error(sm.getString("accessLogValve.openFail", pathname), e); } } /** * This method returns a Date object that is accurate to within one second. * If a thread calls this method to get a Date and it's been less than 1 * second since a new Date was created, this method simply gives out the * same Date again so that the system doesn't spend time creating Date * objects unnecessarily. * * @return Date */ private static Date getDate(long systime) { Date date = localDate.get(); date.setTime(systime); return date; } /** * Find a locale by name */ protected static Locale findLocale(String name, Locale fallback) { if (name == null || name.isEmpty()) { return Locale.getDefault(); } else { for (Locale l: Locale.getAvailableLocales()) { if (name.equals(l.toString())) { return(l); } } } log.error(sm.getString("accessLogValve.invalidLocale", name)); return fallback; } /** * Start this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void startInternal() throws LifecycleException { // Initialize the Date formatters String format = getFileDateFormat(); fileDateFormatter = new SimpleDateFormat(format, Locale.US); fileDateFormatter.setTimeZone(TimeZone.getDefault()); dateStamp = fileDateFormatter.format(new Date(System.currentTimeMillis())); if (rotatable && renameOnRotate) { restore(); } open(); setState(LifecycleState.STARTING); } /** * Stop this component and implement the requirements * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}. * * @exception LifecycleException if this component detects a fatal error * that prevents this component from being used */ @Override protected synchronized void stopInternal() throws LifecycleException { setState(LifecycleState.STOPPING); close(false); } /** * AccessLogElement writes the partial message into the buffer. */ protected interface AccessLogElement { public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time); } /** * write thread name - %I */ protected static class ThreadNameElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { RequestInfo info = request.getCoyoteRequest().getRequestProcessor(); if(info != null) { buf.append(info.getWorkerThreadName()); } else { buf.append("-"); } } } /** * write local IP address - %A */ protected static class LocalAddrElement implements AccessLogElement { private static final String LOCAL_ADDR_VALUE; static { String init; try { init = InetAddress.getLocalHost().getHostAddress(); } catch (Throwable e) { ExceptionUtils.handleThrowable(e); init = "127.0.0.1"; } LOCAL_ADDR_VALUE = init; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { buf.append(LOCAL_ADDR_VALUE); } } /** * write remote IP address - %a */ protected class RemoteAddrElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (requestAttributesEnabled) { Object addr = request.getAttribute(REMOTE_ADDR_ATTRIBUTE); if (addr == null) { buf.append(request.getRemoteAddr()); } else { buf.append(addr.toString()); } } else { buf.append(request.getRemoteAddr()); } } } /** * write remote host name - %h */ protected class HostElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { String value = null; if (requestAttributesEnabled) { Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE); if (host != null) { value = host.toString(); } } if (value == null || value.length() == 0) { value = request.getRemoteHost(); } if (value == null || value.length() == 0) { value = "-"; } buf.append(value); } } /** * write remote logical username from identd (always returns '-') - %l */ protected static class LogicalUserNameElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { buf.append('-'); } } /** * write request protocol - %H */ protected class ProtocolElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (requestAttributesEnabled) { Object proto = request.getAttribute(PROTOCOL_ATTRIBUTE); if (proto == null) { buf.append(request.getProtocol()); } else { buf.append(proto.toString()); } } else { buf.append(request.getProtocol()); } } } /** * write remote user that was authenticated (if any), else '-' - %u */ protected static class UserElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { String value = request.getRemoteUser(); if (value != null) { buf.append(value); } else { buf.append('-'); } } else { buf.append('-'); } } } /** * write date and time, in configurable format (default CLF) - %t or %t{format} */ protected class DateAndTimeElement implements AccessLogElement { /** * Format prefix specifying request start time */ private static final String requestStartPrefix = "begin"; /** * Format prefix specifying response end time */ private static final String responseEndPrefix = "end"; /** * Separator between optional prefix and rest of format */ private static final String prefixSeparator = ":"; /** * Special format for seconds since epoch */ private static final String secFormat = "sec"; /** * Special format for milliseconds since epoch */ private static final String msecFormat = "msec"; /** * Special format for millisecond part of timestamp */ private static final String msecFractionFormat = "msec_frac"; /** * The patterns we use to replace "S" and "SSS" millisecond * formatting of SimpleDateFormat by our own handling */ private static final String msecPattern = "{#}"; private static final String trippleMsecPattern = msecPattern + msecPattern + msecPattern; /* Our format description string, null if CLF */ private final String format; /* Whether to use begin of request or end of response as the timestamp */ private final boolean usesBegin; /* The format type */ private final FormatType type; /* Whether we need to postprocess by adding milliseconds */ private boolean usesMsecs = false; protected DateAndTimeElement() { this(null); } /** * Replace the millisecond formatting character 'S' by * some dummy characters in order to make the resulting * formatted time stamps cacheable. We replace the dummy * chars later with the actual milliseconds because that's * relatively cheap. */ private String tidyFormat(String format) { boolean escape = false; StringBuilder result = new StringBuilder(); int len = format.length(); char x; for (int i = 0; i < len; i++) { x = format.charAt(i); if (escape || x != 'S') { result.append(x); } else { result.append(msecPattern); usesMsecs = true; } if (x == '\'') { escape = !escape; } } return result.toString(); } protected DateAndTimeElement(String header) { String format = header; boolean usesBegin = false; FormatType type = FormatType.CLF; if (format != null) { if (format.equals(requestStartPrefix)) { usesBegin = true; format = ""; } else if (format.startsWith(requestStartPrefix + prefixSeparator)) { usesBegin = true; format = format.substring(6); } else if (format.equals(responseEndPrefix)) { usesBegin = false; format = ""; } else if (format.startsWith(responseEndPrefix + prefixSeparator)) { usesBegin = false; format = format.substring(4); } if (format.length() == 0) { type = FormatType.CLF; } else if (format.equals(secFormat)) { type = FormatType.SEC; } else if (format.equals(msecFormat)) { type = FormatType.MSEC; } else if (format.equals(msecFractionFormat)) { type = FormatType.MSEC_FRAC; } else { type = FormatType.SDF; format = tidyFormat(format); } } this.format = format; this.usesBegin = usesBegin; this.type = type; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { long timestamp = date.getTime(); long frac; if (usesBegin) { timestamp -= time; } switch (type) { case CLF: buf.append(localDateCache.get().getFormat(timestamp)); break; case SEC: buf.append(Long.toString(timestamp / 1000)); break; case MSEC: buf.append(Long.toString(timestamp)); break; case MSEC_FRAC: frac = timestamp % 1000; if (frac < 100) { if (frac < 10) { buf.append('0'); buf.append('0'); } else { buf.append('0'); } } buf.append(Long.toString(frac)); break; case SDF: String temp = localDateCache.get().getFormat(format, locale, timestamp); if (usesMsecs) { frac = timestamp % 1000; StringBuilder trippleMsec = new StringBuilder(4); if (frac < 100) { if (frac < 10) { trippleMsec.append('0'); trippleMsec.append('0'); } else { trippleMsec.append('0'); } } trippleMsec.append(frac); temp = temp.replace(trippleMsecPattern, trippleMsec); temp = temp.replace(msecPattern, Long.toString(frac)); } buf.append(temp); break; } } } /** * write first line of the request (method and request URI) - %r */ protected static class RequestElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { String method = request.getMethod(); if (method == null) { // No method means no request line buf.append('-'); } else { buf.append(request.getMethod()); buf.append(' '); buf.append(request.getRequestURI()); if (request.getQueryString() != null) { buf.append('?'); buf.append(request.getQueryString()); } buf.append(' '); buf.append(request.getProtocol()); } } else { buf.append('-'); } } } /** * write HTTP status code of the response - %s */ protected static class HttpStatusCodeElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (response != null) { // This approach is used to reduce GC from toString conversion int status = response.getStatus(); if (100 <= status && status < 1000) { buf.append((char) ('0' + (status / 100))) .append((char) ('0' + ((status / 10) % 10))) .append((char) ('0' + (status % 10))); } else { buf.append(Integer.toString(status)); } } else { buf.append('-'); } } } /** * write local port on which this request was received - %p */ protected class LocalPortElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (requestAttributesEnabled) { Object port = request.getAttribute(SERVER_PORT_ATTRIBUTE); if (port == null) { buf.append(Integer.toString(request.getServerPort())); } else { buf.append(port.toString()); } } else { buf.append(Integer.toString(request.getServerPort())); } } } /** * write bytes sent, excluding HTTP headers - %b, %B */ protected static class ByteSentElement implements AccessLogElement { private final boolean conversion; /** * if conversion is true, write '-' instead of 0 - %b */ public ByteSentElement(boolean conversion) { this.conversion = conversion; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { // Don't need to flush since trigger for log message is after the // response has been committed long length = response.getBytesWritten(false); if (length <= 0) { // Protect against nulls and unexpected types as these values // may be set by untrusted applications Object start = request.getAttribute( Globals.SENDFILE_FILE_START_ATTR); if (start instanceof Long) { Object end = request.getAttribute( Globals.SENDFILE_FILE_END_ATTR); if (end instanceof Long) { length = ((Long) end).longValue() - ((Long) start).longValue(); } } } if (length <= 0 && conversion) { buf.append('-'); } else { buf.append(Long.toString(length)); } } } /** * write request method (GET, POST, etc.) - %m */ protected static class MethodElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (request != null) { buf.append(request.getMethod()); } } } /** * write time taken to process the request - %D, %T */ protected static class ElapsedTimeElement implements AccessLogElement { private final boolean millis; /** * if millis is true, write time in millis - %D * if millis is false, write time in seconds - %T */ public ElapsedTimeElement(boolean millis) { this.millis = millis; } @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (millis) { buf.append(Long.toString(time)); } else { // second buf.append(Long.toString(time / 1000)); buf.append('.'); int remains = (int) (time % 1000); buf.append(Long.toString(remains / 100)); remains = remains % 100; buf.append(Long.toString(remains / 10)); buf.append(Long.toString(remains % 10)); } } } /** * write time until first byte is written (commit time) in millis - %F */ protected static class FirstByteTimeElement implements AccessLogElement { @Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { long commitTime = response.getCoyoteResponse().getCommitTime(); if (commitTime == -1) { buf.append('-'); } else { long delta = commitTime - request.getCoyoteRequest().getStartTime(); buf.append(Long.toString(delta)); } } } /** * 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 'F': return new FirstByteTimeElement(); case 'h': return new HostElement(); case 'H': return new ProtocolElement(); case 'l': return new LogicalUserNameElement(); case 'm': return new MethodElement(); case 'p': return new LocalPortElement(); case 'q': return new QueryElement(); case 'r': return new RequestElement(); case 's': return new HttpStatusCodeElement(); case 'S': return new SessionIdElement(); case 't': return new DateAndTimeElement(); case 'T': return new ElapsedTimeElement(false); case 'u': return new UserElement(); case 'U': return new RequestURIElement(); case 'v': return new LocalServerNameElement(); case 'I': return new ThreadNameElement(); default: return new StringElement("???" + pattern + "???"); } } }
55,995
Bug 55995 java.lang.NullPointerException at org.apache.jasper.servlet.JspCServletContext.getResource(JspCServletContext.java:344)
Null pointer exception when running JSPC from a Shell Script. JspCServletContext.java:344 /** * Return a URL object of a resource that is mapped to the * specified context-relative path. * * @param path Context-relative path of the desired resource * * @exception MalformedURLException if the resource path is * not properly formed */ @Override public URL getResource(String path) throws MalformedURLException { if (!path.startsWith("/")) throw new MalformedURLException("Path '" + path + "' does not start with '/'"); TldCache.java:124 private long[] getLastModified(TldResourcePath tldResourcePath) { long[] result = new long[2]; result[0] = -1; result[1] = -1; try { URL url = servletContext.getResource(tldResourcePath.getWebappPath()); /usr/java/jdk1.7.0_45/bin/java -classpath :/home/tomcat/apache-tomcat-8.0.0-RC10/lib/catalina-storeconfig.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-websocket.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-i18n-es.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/catalina-tribes.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/catalina-ha.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-i18n-ja.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/jsp-api.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-util.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-jni.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/jasper.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/websocket-api.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/ecj-4.3.1.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-i18n-fr.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-api.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-coyote.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/servlet-api.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/jasper-el.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/catalina.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-dbcp.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-jdbc.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/annotations-api.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-util-scan.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/catalina-ant.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/el-api.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/lib/tomcat-spdy.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/bin/tomcat-juli.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/bin/bootstrap.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/bin/commons-daemon.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/webapps/examples/WEB-INF/lib/jstl.jar:/home/tomcat/apache-tomcat-8.0.0-RC10/webapps/examples/WEB-INF/lib/standard.jar:/home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/lib/ant-1.6.5.jar org.apache.jasper.JspC -d /home/java/source/HEAD/work/tomcat80 -v -l -uriroot /home/java/source/HEAD/work/jsp_compile_shared /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/dialog/qbAxesDlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/dialog/qbManualGecodingDlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/fmtdlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/index.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/joindlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/producer.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/simplefilter.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/selectvaluedlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/binddowsTestView.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/variableeditordlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/filterprompteditor.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/ajax_response.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/fontdlg.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/join_fields.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/tree_component.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/waiting_banner.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/folderblock/BID_FolderBlockInit.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/folderblock/BID_FolderBlockBoot.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/BID_EmptyContent.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/xml/BID_UrlProperties.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/xml/BID_IBFSpathToHrefs.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/xml/BID_xmlresponse.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/xml/BID_statusResponse.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/favorites/BID_favorites_tree.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/favorites/BID_FavoritesBlockBoot.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/favorites/BID_FavoritesBlockInit.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/favorites/BID_favorites_tree_boot.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/favorites/BID_listToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/index.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_InternalPage.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_SearchTree_Boot.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_SATree_Boot.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_BiFrame.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_initView.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_ShowToolbar.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_ExternalPage.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_SATreeBiFrame.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_initBindows.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/views/BID_SearchTreeBiFrame.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/recents/BID_recents_tree_boot.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/recents/BID_recents_tree.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/recents/BID_listToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/error.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/groups/BID_listToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/search/BID_searchListToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/search/BID_listToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/tree/BID_MrPropertiesToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/tree/BID_flatListToXML.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/tree/BID_PlainText.jsp /home/java/source/HEAD/work/jsp_compile_shared/WEB-INF/jsp/bid/tree/BID_listToXML.jsp 2>&1 Exception in thread "main" java.lang.NullPointerException at org.apache.jasper.servlet.JspCServletContext.getResource(JspCServletContext.java:344) at org.apache.jasper.compiler.TldCache.getLastModified(TldCache.java:124) at org.apache.jasper.compiler.TldCache.<init>(TldCache.java:70) at org.apache.jasper.JspC.initServletContext(JspC.java:1468) at org.apache.jasper.JspC.execute(JspC.java:1321) at org.apache.jasper.JspC.main(JspC.java:269)
resolved fixed
5e6b884
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-14T12:04:41Z
2014-01-13T10:46:40Z
java/org/apache/jasper/compiler/TldCache.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletContext; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; import org.apache.tomcat.util.descriptor.tld.TaglibXml; import org.apache.tomcat.util.descriptor.tld.TldParser; import org.apache.tomcat.util.descriptor.tld.TldResourcePath; import org.apache.tomcat.util.scan.Jar; import org.xml.sax.SAXException; /** * This class caches parsed instances of TLD files to remove the need for the * same TLD to be parsed for each JSP that references it. It does not protect * against multiple threads processing the same, new TLD but it does ensure that * each all threads will use the same TLD object after parsing. */ public class TldCache { public static final String SERVLET_CONTEXT_ATTRIBUTE_NAME = TldCache.class.getName(); private final ServletContext servletContext; private final Map<String,TldResourcePath> uriTldResourcePathMap = new HashMap<>(); private final Map<TldResourcePath,TaglibXmlCacheEntry> tldResourcePathTaglibXmlMap = new HashMap<>(); private final TldParser tldParser; public static TldCache getInstance(ServletContext servletContext) { if (servletContext == null) { throw new IllegalArgumentException(Localizer.getMessage( "org.apache.jasper.compiler.TldCache.servletContextNull")); } return (TldCache) servletContext.getAttribute(SERVLET_CONTEXT_ATTRIBUTE_NAME); } public TldCache(ServletContext servletContext, Map<String, TldResourcePath> uriTldResourcePathMap, Map<TldResourcePath, TaglibXml> tldResourcePathTaglibXmlMap) { this.servletContext = servletContext; this.uriTldResourcePathMap.putAll(uriTldResourcePathMap); for (Entry<TldResourcePath, TaglibXml> entry : tldResourcePathTaglibXmlMap.entrySet()) { TldResourcePath tldResourcePath = entry.getKey(); long lastModified[] = getLastModified(tldResourcePath); TaglibXmlCacheEntry cacheEntry = new TaglibXmlCacheEntry( entry.getValue(), lastModified[0], lastModified[1]); this.tldResourcePathTaglibXmlMap.put(tldResourcePath, cacheEntry); } boolean validate = Boolean.parseBoolean( servletContext.getInitParameter(Constants.XML_VALIDATION_TLD_INIT_PARAM)); String blockExternalString = servletContext.getInitParameter( Constants.XML_BLOCK_EXTERNAL_INIT_PARAM); boolean blockExternal; if (blockExternalString == null) { blockExternal = Constants.IS_SECURITY_ENABLED; } else { blockExternal = Boolean.parseBoolean(blockExternalString); } tldParser = new TldParser(true, validate, blockExternal); } public TldResourcePath getTldResourcePath(String uri) { return uriTldResourcePathMap.get(uri); } public TaglibXml getTaglibXml(TldResourcePath tldResourcePath) throws JasperException { TaglibXmlCacheEntry cacheEntry = tldResourcePathTaglibXmlMap.get(tldResourcePath); long lastModified[] = getLastModified(tldResourcePath); if (lastModified[0] != cacheEntry.getWebAppPathLastModified() || lastModified[1] != cacheEntry.getEntryLastModified()) { synchronized (cacheEntry) { if (lastModified[0] != cacheEntry.getWebAppPathLastModified() || lastModified[1] != cacheEntry.getEntryLastModified()) { // Re-parse TLD TaglibXml updatedTaglibXml; try { updatedTaglibXml = tldParser.parse(tldResourcePath); } catch (IOException | SAXException e) { throw new JasperException(e); } cacheEntry.setTaglibXml(updatedTaglibXml); cacheEntry.setWebAppPathLastModified(lastModified[0]); cacheEntry.setEntryLastModified(lastModified[1]); } } } return cacheEntry.getTaglibXml(); } private long[] getLastModified(TldResourcePath tldResourcePath) { long[] result = new long[2]; result[0] = -1; result[1] = -1; try { URL url = servletContext.getResource(tldResourcePath.getWebappPath()); URLConnection conn = url.openConnection(); result[0] = conn.getLastModified(); if ("file".equals(url.getProtocol())) { // Reading the last modified time opens an input stream so we // need to make sure it is closed again otherwise the TLD file // will be locked until GC runs. conn.getInputStream().close(); } Jar jar = tldResourcePath.getJar(); if (jar != null) { result[1] = jar.getLastModified(tldResourcePath.getEntryName()); } } catch (IOException e) { // Ignore (shouldn't happen) } return result; } private static class TaglibXmlCacheEntry { private volatile TaglibXml taglibXml; private volatile long webAppPathLastModified; private volatile long entryLastModified; public TaglibXmlCacheEntry(TaglibXml taglibXml, long webAppPathLastModified, long entryLastModified) { this.taglibXml = taglibXml; this.webAppPathLastModified = webAppPathLastModified; this.entryLastModified = entryLastModified; } public TaglibXml getTaglibXml() { return taglibXml; } public void setTaglibXml(TaglibXml taglibXml) { this.taglibXml = taglibXml; } public long getWebAppPathLastModified() { return webAppPathLastModified; } public void setWebAppPathLastModified(long webAppPathLastModified) { this.webAppPathLastModified = webAppPathLastModified; } public long getEntryLastModified() { return entryLastModified; } public void setEntryLastModified(long entryLastModified) { this.entryLastModified = entryLastModified; } } }
55,996
Bug 55996 Async context does not timeout with HTTP NIO connector
null
resolved fixed
553ad39
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-14T17:58:45Z
2014-01-13T10:46:40Z
java/org/apache/tomcat/util/net/SocketWrapper.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.util.Iterator; import java.util.Set; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock; public class SocketWrapper<E> { private volatile E socket; private volatile long lastAccess = -1; private long timeout = -1; private boolean error = false; private volatile int keepAliveLeft = 100; private volatile boolean comet = false; private volatile boolean async = false; private boolean keptAlive = false; private volatile boolean upgraded = false; private boolean secure = false; /* * Following cached for speed / reduced GC */ private String localAddr = null; private String localName = null; private int localPort = -1; private String remoteAddr = null; private String remoteHost = null; private int remotePort = -1; /* * Used if block/non-blocking is set at the socket level. The client is * responsible for the thread-safe use of this field via the locks provided. */ private volatile boolean blockingStatus = true; private final Lock blockingStatusReadLock; private final WriteLock blockingStatusWriteLock; /* * In normal servlet processing only one thread is allowed to access the * socket at a time. That is controlled by a lock on the socket for both * read and writes). When HTTP upgrade is used, one read thread and one * write thread are allowed to access the socket concurrently. In this case * the lock on the socket is used for reads and the lock below is used for * writes. */ private final Object writeThreadLock = new Object(); private Set<DispatchType> dispatches = new CopyOnWriteArraySet<>(); public SocketWrapper(E socket) { this.socket = socket; ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); this.blockingStatusReadLock = lock.readLock(); this.blockingStatusWriteLock = lock.writeLock(); } public E getSocket() { return socket; } public boolean isComet() { return comet; } public void setComet(boolean comet) { this.comet = comet; } public boolean isAsync() { return async; } public void setAsync(boolean async) { this.async = async; } public boolean isUpgraded() { return upgraded; } public void setUpgraded(boolean upgraded) { this.upgraded = upgraded; } public boolean isSecure() { return secure; } public void setSecure(boolean secure) { this.secure = secure; } public long getLastAccess() { return lastAccess; } public void access() { access(System.currentTimeMillis()); } public void access(long access) { lastAccess = access; } public void setTimeout(long timeout) {this.timeout = timeout;} public long getTimeout() {return this.timeout;} public boolean getError() { return error; } public void setError(boolean error) { this.error = error; } public void setKeepAliveLeft(int keepAliveLeft) { this.keepAliveLeft = keepAliveLeft;} public int decrementKeepAlive() { return (--keepAliveLeft);} public boolean isKeptAlive() {return keptAlive;} public void setKeptAlive(boolean keptAlive) {this.keptAlive = keptAlive;} public int getLocalPort() { return localPort; } public void setLocalPort(int localPort) {this.localPort = localPort; } public String getLocalName() { return localName; } public void setLocalName(String localName) {this.localName = localName; } public String getLocalAddr() { return localAddr; } public void setLocalAddr(String localAddr) {this.localAddr = localAddr; } public int getRemotePort() { return remotePort; } public void setRemotePort(int remotePort) {this.remotePort = remotePort; } public String getRemoteHost() { return remoteHost; } public void setRemoteHost(String remoteHost) {this.remoteHost = remoteHost; } public String getRemoteAddr() { return remoteAddr; } public void setRemoteAddr(String remoteAddr) {this.remoteAddr = remoteAddr; } public boolean getBlockingStatus() { return blockingStatus; } public void setBlockingStatus(boolean blockingStatus) { this.blockingStatus = blockingStatus; } public Lock getBlockingStatusReadLock() { return blockingStatusReadLock; } public WriteLock getBlockingStatusWriteLock() { return blockingStatusWriteLock; } public Object getWriteThreadLock() { return writeThreadLock; } public void addDispatch(DispatchType dispatchType) { synchronized (dispatches) { dispatches.add(dispatchType); } } public Iterator<DispatchType> getIteratorAndClearDispatches() { // Note: Logic in AbstractProtocol depends on this method only returning // a non-null value if the iterator is non-empty. i.e. it should never // return an empty iterator. Iterator<DispatchType> result; synchronized (dispatches) { // Synchronized as the generation of the iterator and the clearing // of dispatches needs to be an atomic operation. result = dispatches.iterator(); if (result.hasNext()) { dispatches.clear(); } else { result = null; } } return result; } public void clearDispatches() { synchronized (dispatches) { dispatches.clear(); } } public void reset(E socket, long timeout) { async = false; blockingStatus = true; comet = false; dispatches.clear(); error = false; keepAliveLeft = 100; lastAccess = System.currentTimeMillis(); localAddr = null; localName = null; localPort = -1; remoteAddr = null; remoteHost = null; remotePort = -1; this.socket = socket; this.timeout = timeout; upgraded = false; } /** * Overridden for debug purposes. No guarantees are made about the format of * this message which may vary significantly between point releases. * <p> * {@inheritDoc} */ @Override public String toString() { return super.toString() + ":" + String.valueOf(socket); } }
56,010
Bug 56010 JspFactory.getPageContext with JspWriter.DEFAULT_BUFFER throws IllegalArgumentException
null
resolved fixed
48650dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-16T14:21:17Z
2014-01-15T07:13:20Z
java/org/apache/jasper/runtime/PageContextImpl.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.security.AccessController; import java.security.PrivilegedAction; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.Collections; import java.util.Enumeration; import java.util.HashMap; import javax.el.ELContext; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.ValueExpression; import javax.servlet.RequestDispatcher; 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.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.PageContext; import javax.servlet.jsp.tagext.BodyContent; import org.apache.jasper.compiler.Localizer; import org.apache.jasper.el.ELContextImpl; import org.apache.jasper.security.SecurityUtil; /** * Implementation of the PageContext class from the JSP spec. Also doubles as a * VariableResolver for the EL. * * @author Anil K. Vijendran * @author Larry Cable * @author Hans Bergsten * @author Pierre Delisle * @author Mark Roth * @author Jan Luehe * @author Jacob Hookom */ public class PageContextImpl extends PageContext { private static final JspFactory jspf = JspFactory.getDefaultFactory(); private BodyContentImpl[] outs; private int depth; // per-servlet state private Servlet servlet; private ServletConfig config; private ServletContext context; private JspApplicationContextImpl applicationContext; private String errorPageURL; // page-scope attributes private final transient HashMap<String, Object> attributes; // per-request state private transient ServletRequest request; private transient ServletResponse response; private transient HttpSession session; private transient ELContextImpl elContext; private boolean isIncluded; // initial output stream private transient JspWriter out; private transient JspWriterImpl baseOut; /* * Constructor. */ PageContextImpl() { this.outs = new BodyContentImpl[0]; this.attributes = new HashMap<>(16); this.depth = -1; } @Override public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) throws IOException { // initialize state this.servlet = servlet; this.config = servlet.getServletConfig(); this.context = config.getServletContext(); this.errorPageURL = errorPageURL; this.request = request; this.response = response; // initialize application context this.applicationContext = JspApplicationContextImpl.getInstance(context); // Setup session (if required) if (request instanceof HttpServletRequest && needsSession) this.session = ((HttpServletRequest) request).getSession(); if (needsSession && session == null) throw new IllegalStateException( "Page needs a session and none is available"); // initialize the initial out ... depth = -1; if (this.baseOut == null) { this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush); } else { this.baseOut.init(response, bufferSize, autoFlush); } this.out = baseOut; // register names/values as per spec setAttribute(OUT, this.out); setAttribute(REQUEST, request); setAttribute(RESPONSE, response); if (session != null) setAttribute(SESSION, session); setAttribute(PAGE, servlet); setAttribute(CONFIG, config); setAttribute(PAGECONTEXT, this); setAttribute(APPLICATION, context); isIncluded = request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH) != null; } @Override public void release() { out = baseOut; try { if (isIncluded) { ((JspWriterImpl) out).flushBuffer(); // push it into the including jspWriter } else { // Old code: // out.flush(); // Do not flush the buffer even if we're not included (i.e. // we are the main page. The servlet will flush it and close // the stream. ((JspWriterImpl) out).flushBuffer(); } } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer.getMessage("jsp.error.flush"), ex); throw ise; } finally { servlet = null; config = null; context = null; applicationContext = null; elContext = null; errorPageURL = null; request = null; response = null; depth = -1; baseOut.recycle(); session = null; attributes.clear(); for (BodyContentImpl body: outs) { body.recycle(); } } } @Override public Object getAttribute(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name); } }); } else { return doGetAttribute(name); } } private Object doGetAttribute(String name) { return attributes.get(name); } @Override public Object getAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { return doGetAttribute(name, scope); } }); } else { return doGetAttribute(name, scope); } } private Object doGetAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: return attributes.get(name); case REQUEST_SCOPE: return request.getAttribute(name); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttribute(name); case APPLICATION_SCOPE: return context.getAttribute(name); default: throw new IllegalArgumentException("Invalid scope"); } } @Override public void setAttribute(final String name, final Object attribute) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doSetAttribute(name, attribute); return null; } }); } else { doSetAttribute(name, attribute); } } private void doSetAttribute(String name, Object attribute) { if (attribute != null) { attributes.put(name, attribute); } else { removeAttribute(name, PAGE_SCOPE); } } @Override public void setAttribute(final String name, final Object o, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doSetAttribute(name, o, scope); return null; } }); } else { doSetAttribute(name, o, scope); } } private void doSetAttribute(String name, Object o, int scope) { if (o != null) { switch (scope) { case PAGE_SCOPE: attributes.put(name, o); break; case REQUEST_SCOPE: request.setAttribute(name, o); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.setAttribute(name, o); break; case APPLICATION_SCOPE: context.setAttribute(name, o); break; default: throw new IllegalArgumentException("Invalid scope"); } } else { removeAttribute(name, scope); } } @Override public void removeAttribute(final String name, final int scope) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name, scope); return null; } }); } else { doRemoveAttribute(name, scope); } } private void doRemoveAttribute(String name, int scope) { switch (scope) { case PAGE_SCOPE: attributes.remove(name); break; case REQUEST_SCOPE: request.removeAttribute(name); break; case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } session.removeAttribute(name); break; case APPLICATION_SCOPE: context.removeAttribute(name); break; default: throw new IllegalArgumentException("Invalid scope"); } } @Override public int getAttributesScope(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { return (AccessController .doPrivileged(new PrivilegedAction<Integer>() { @Override public Integer run() { return Integer.valueOf(doGetAttributeScope(name)); } })).intValue(); } else { return doGetAttributeScope(name); } } private int doGetAttributeScope(String name) { if (attributes.get(name) != null) return PAGE_SCOPE; if (request.getAttribute(name) != null) return REQUEST_SCOPE; if (session != null) { try { if (session.getAttribute(name) != null) return SESSION_SCOPE; } catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall through to application scope. } } if (context.getAttribute(name) != null) return APPLICATION_SCOPE; return 0; } @Override public Object findAttribute(final String name) { if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Object>() { @Override public Object run() { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return doFindAttribute(name); } }); } else { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } return doFindAttribute(name); } } private Object doFindAttribute(String name) { Object o = attributes.get(name); if (o != null) return o; o = request.getAttribute(name); if (o != null) return o; if (session != null) { try { o = session.getAttribute(name); } catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall through to application scope. } if (o != null) return o; } return context.getAttribute(name); } @Override public Enumeration<String> getAttributeNamesInScope(final int scope) { if (SecurityUtil.isPackageProtectionEnabled()) { return AccessController.doPrivileged( new PrivilegedAction<Enumeration<String>>() { @Override public Enumeration<String> run() { return doGetAttributeNamesInScope(scope); } }); } else { return doGetAttributeNamesInScope(scope); } } private Enumeration<String> doGetAttributeNamesInScope(int scope) { switch (scope) { case PAGE_SCOPE: return Collections.enumeration(attributes.keySet()); case REQUEST_SCOPE: return request.getAttributeNames(); case SESSION_SCOPE: if (session == null) { throw new IllegalStateException(Localizer .getMessage("jsp.error.page.noSession")); } return session.getAttributeNames(); case APPLICATION_SCOPE: return context.getAttributeNames(); default: throw new IllegalArgumentException("Invalid scope"); } } @Override public void removeAttribute(final String name) { if (name == null) { throw new NullPointerException(Localizer .getMessage("jsp.error.attribute.null_name")); } if (SecurityUtil.isPackageProtectionEnabled()) { AccessController.doPrivileged(new PrivilegedAction<Void>() { @Override public Void run() { doRemoveAttribute(name); return null; } }); } else { doRemoveAttribute(name); } } private void doRemoveAttribute(String name) { removeAttribute(name, PAGE_SCOPE); removeAttribute(name, REQUEST_SCOPE); if( session != null ) { try { removeAttribute(name, SESSION_SCOPE); } catch(IllegalStateException ise) { // Session has been invalidated. // Ignore and fall throw to application scope. } } removeAttribute(name, APPLICATION_SCOPE); } @Override public JspWriter getOut() { return out; } @Override public HttpSession getSession() { return session; } @Override public ServletConfig getServletConfig() { return config; } @Override public ServletContext getServletContext() { return config.getServletContext(); } @Override public ServletRequest getRequest() { return request; } @Override public ServletResponse getResponse() { return response; } /** * Returns the exception associated with this page context, if any. <p/> * Added wrapping for Throwables to avoid ClassCastException: see Bugzilla * 31171 for details. * * @return The Exception associated with this page context, if any. */ @Override public Exception getException() { Throwable t = JspRuntimeLibrary.getThrowable(request); // Only wrap if needed if ((t != null) && (!(t instanceof Exception))) { t = new JspException(t); } return (Exception) t; } @Override public Object getPage() { return servlet; } private final String getAbsolutePathRelativeToContext(String relativeUrlPath) { String path = relativeUrlPath; if (!path.startsWith("/")) { String uri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (uri == null) uri = ((HttpServletRequest) request).getServletPath(); String baseURI = uri.substring(0, uri.lastIndexOf('/')); path = baseURI + '/' + path; } return path; } @Override public void include(String relativeUrlPath) throws ServletException, IOException { JspRuntimeLibrary .include(request, response, relativeUrlPath, out, true); } @Override public void include(final String relativeUrlPath, final boolean flush) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doInclude(relativeUrlPath, flush); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } } else { doInclude(relativeUrlPath, flush); } } private void doInclude(String relativeUrlPath, boolean flush) throws ServletException, IOException { JspRuntimeLibrary.include(request, response, relativeUrlPath, out, flush); } @Override @Deprecated public javax.servlet.jsp.el.VariableResolver getVariableResolver() { return new org.apache.jasper.el.VariableResolverImpl( this.getELContext()); } @Override public void forward(final String relativeUrlPath) throws ServletException, IOException { if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doForward(relativeUrlPath); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } } else { doForward(relativeUrlPath); } } private void doForward(String relativeUrlPath) throws ServletException, IOException { // JSP.4.5 If the buffer was flushed, throw IllegalStateException try { out.clear(); baseOut.clear(); } catch (IOException ex) { IllegalStateException ise = new IllegalStateException(Localizer .getMessage("jsp.error.attempt_to_clear_flushed_buffer")); ise.initCause(ex); throw ise; } // Make sure that the response object is not the wrapper for include while (response instanceof ServletResponseWrapperInclude) { response = ((ServletResponseWrapperInclude) response).getResponse(); } final String path = getAbsolutePathRelativeToContext(relativeUrlPath); String includeUri = (String) request.getAttribute( RequestDispatcher.INCLUDE_SERVLET_PATH); if (includeUri != null) request.removeAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH); try { context.getRequestDispatcher(path).forward(request, response); } finally { if (includeUri != null) request.setAttribute(RequestDispatcher.INCLUDE_SERVLET_PATH, includeUri); } } @Override public BodyContent pushBody() { return (BodyContent) pushBody(null); } @Override public JspWriter pushBody(Writer writer) { depth++; if (depth >= outs.length) { BodyContentImpl[] newOuts = new BodyContentImpl[depth + 1]; for (int i = 0; i < outs.length; i++) { newOuts[i] = outs[i]; } newOuts[depth] = new BodyContentImpl(out); outs = newOuts; } outs[depth].setWriter(writer); out = outs[depth]; // Update the value of the "out" attribute in the page scope // attribute namespace of this PageContext setAttribute(OUT, out); return outs[depth]; } @Override public JspWriter popBody() { depth--; if (depth >= 0) { out = outs[depth]; } else { out = baseOut; } // Update the value of the "out" attribute in the page scope // attribute namespace of this PageContext setAttribute(OUT, out); return out; } /** * Provides programmatic access to the ExpressionEvaluator. The JSP * Container must return a valid instance of an ExpressionEvaluator that can * parse EL expressions. */ @Override @Deprecated public javax.servlet.jsp.el.ExpressionEvaluator getExpressionEvaluator() { return new org.apache.jasper.el.ExpressionEvaluatorImpl( this.applicationContext.getExpressionFactory()); } @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(final Throwable t) throws IOException, ServletException { if (t == null) throw new NullPointerException("null Throwable"); if (SecurityUtil.isPackageProtectionEnabled()) { try { AccessController.doPrivileged( new PrivilegedExceptionAction<Void>() { @Override public Void run() throws Exception { doHandlePageException(t); return null; } }); } catch (PrivilegedActionException e) { Exception ex = e.getException(); if (ex instanceof IOException) { throw (IOException) ex; } else { throw (ServletException) ex; } } } else { doHandlePageException(t); } } @SuppressWarnings("deprecation") // Still jave to support old JSP EL private void doHandlePageException(Throwable t) throws IOException, ServletException { if (errorPageURL != null && !errorPageURL.equals("")) { /* * Set request attributes. Do not set the * javax.servlet.error.exception attribute here (instead, set in the * generated servlet code for the error page) in order to prevent * the ErrorReportValve, which is invoked as part of forwarding the * request to the error page, from throwing it if the response has * not been committed (the response will have been committed if the * error page is a JSP page). */ request.setAttribute(PageContext.EXCEPTION, t); request.setAttribute(RequestDispatcher.ERROR_STATUS_CODE, new Integer(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); request.setAttribute(RequestDispatcher.ERROR_REQUEST_URI, ((HttpServletRequest) request).getRequestURI()); request.setAttribute(RequestDispatcher.ERROR_SERVLET_NAME, config.getServletName()); try { forward(errorPageURL); } catch (IllegalStateException ise) { include(errorPageURL); } // The error page could be inside an include. Object newException = request.getAttribute(RequestDispatcher.ERROR_EXCEPTION); // t==null means the attribute was not set. if ((newException != null) && (newException == t)) { request.removeAttribute(RequestDispatcher.ERROR_EXCEPTION); } // now clear the error code - to prevent double handling. request.removeAttribute(RequestDispatcher.ERROR_STATUS_CODE); request.removeAttribute(RequestDispatcher.ERROR_REQUEST_URI); request.removeAttribute(RequestDispatcher.ERROR_SERVLET_NAME); request.removeAttribute(PageContext.EXCEPTION); } else { // Otherwise throw the exception wrapped inside a ServletException. // Set the exception as the root cause in the ServletException // to get a stack trace for the real problem if (t instanceof IOException) throw (IOException) t; if (t instanceof ServletException) throw (ServletException) t; if (t instanceof RuntimeException) throw (RuntimeException) t; Throwable rootCause = null; if (t instanceof JspException || t instanceof ELException || t instanceof javax.servlet.jsp.el.ELException) { rootCause =t.getCause(); } if (rootCause != null) { throw new ServletException(t.getClass().getName() + ": " + t.getMessage(), rootCause); } throw new ServletException(t); } } /** * Proprietary method to evaluate EL expressions. XXX - This method should * go away once the EL interpreter moves out of JSTL and into its own * project. For now, this is necessary because the standard machinery is too * slow. * * @param expression * The expression to be evaluated * @param expectedType * The expected resulting type * @param pageContext * The page context * @param functionMap * Maps prefix and name to Method * @return The result of the evaluation */ public static Object proprietaryEvaluate(final String expression, final Class<?> expectedType, final PageContext pageContext, final ProtectedFunctionMapper functionMap) throws ELException { Object retValue; final ExpressionFactory exprFactory = jspf.getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory(); if (SecurityUtil.isPackageProtectionEnabled()) { try { retValue = AccessController .doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() throws Exception { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(functionMap); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); return ve.getValue(ctx); } }); } catch (PrivilegedActionException ex) { Exception realEx = ex.getException(); if (realEx instanceof ELException) { throw (ELException) realEx; } else { throw new ELException(realEx); } } } else { ELContextImpl ctx = (ELContextImpl) pageContext.getELContext(); ctx.setFunctionMapper(functionMap); ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType); retValue = ve.getValue(ctx); } return retValue; } @Override public ELContext getELContext() { if (this.elContext == null) { this.elContext = this.applicationContext.createELContext(this); } return this.elContext; } }
56,010
Bug 56010 JspFactory.getPageContext with JspWriter.DEFAULT_BUFFER throws IllegalArgumentException
null
resolved fixed
48650dd
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-16T14:21:17Z
2014-01-15T07:13:20Z
test/org/apache/jasper/runtime/TestPageContextImpl.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.File; import javax.servlet.http.HttpServletResponse; import org.junit.Assert; import org.junit.Test; import org.apache.catalina.startup.Tomcat; import org.apache.catalina.startup.TomcatBaseTest; import org.apache.tomcat.util.buf.ByteChunk; public class TestPageContextImpl extends TomcatBaseTest { @Test public void testDoForward() throws Exception { Tomcat tomcat = getTomcatInstance(); File appDir = new File("test/webapp"); tomcat.addWebapp(null, "/test", appDir.getAbsolutePath()); tomcat.start(); ByteChunk res = new ByteChunk(); int rc = getUrl("http://localhost:" + getPort() + "/test/bug5nnnn/bug53545.jsp", res, null); Assert.assertEquals(HttpServletResponse.SC_OK, rc); String body = res.toString(); Assert.assertTrue(body.contains("OK")); Assert.assertFalse(body.contains("FAIL")); } }
56,025
Bug 56025 Order of invocation of method of ServerEndpointConfig.Configurator
null
resolved fixed
11b1e83
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-17T11:50:11Z
2014-01-17T14:46:40Z
java/org/apache/tomcat/websocket/server/UpgradeUtil.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.StandardCharsets; 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.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; public class UpgradeUtil { private static final byte[] WS_ACCEPT = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11".getBytes( StandardCharsets.ISO_8859_1); private static final Queue<MessageDigest> sha1Helpers = new ConcurrentLinkedQueue<>(); private UpgradeUtil() { // Utility class. Hide default constructor. } /** * Checks to see if this is an HTTP request that includes a valid upgrade * request to web socket. * <p> * Note: RFC 2616 does not limit HTTP upgrade to GET requests but the Java * WebSocket spec 1.0, section 8.2 implies such a limitation and RFC * 6455 section 4.1 requires that a WebSocket Upgrade uses GET. */ public static boolean isWebSocketUpgradeRequest(ServletRequest request, ServletResponse response) { return ((request instanceof HttpServletRequest) && (response instanceof HttpServletResponse) && headerContainsToken((HttpServletRequest) request, Constants.UPGRADE_HEADER_NAME, Constants.UPGRADE_HEADER_VALUE) && "GET".equals(((HttpServletRequest) request).getMethod())); } public static void doUpgrade(WsServerContainer sc, HttpServletRequest req, HttpServletResponse resp, ServerEndpointConfig sec, Map<String,String> pathParams) throws ServletException, IOException { // Validate the rest of the headers and reject the request if that // validation fails 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; } // 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(); WsPerSessionServerEndpointConfig perSessionServerEndpointConfig = new WsPerSessionServerEndpointConfig(sec); sec.getConfigurator().modifyHandshake(perSessionServerEndpointConfig, 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, perSessionServerEndpointConfig, sc, wsRequest, subProtocol, pathParams, req.isSecure()); } /* * This only works for tokens. Quoted strings need more sophisticated * parsing. */ private static 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 static 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 static 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(StandardCharsets.ISO_8859_1)); String result = Base64.encodeBase64String(sha1Helper.digest(WS_ACCEPT)); sha1Helpers.add(sha1Helper); return result; } }
55,943
Bug 55943 Provide a way prevent looking at the System classloader before the webapp classloaders
null
resolved fixed
f28800c
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-17T15:16:35Z
2014-01-01T15:26:40Z
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.FilePermission; import java.io.IOException; import java.io.InputStream; import java.lang.instrument.ClassFileTransformer; import java.lang.instrument.IllegalClassFormatException; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.net.URLClassLoader; import java.nio.charset.StandardCharsets; 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.Collections; import java.util.ConcurrentModificationException; import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.ThreadPoolExecutor; import java.util.jar.Attributes; import java.util.jar.Attributes.Name; import java.util.jar.Manifest; import java.util.regex.Matcher; import java.util.regex.Pattern; 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.catalina.webresources.TomcatURLStreamHandlerFactory; import org.apache.tomcat.InstrumentableClassLoader; 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> * <strong>IMPLEMENTATION NOTE</strong> - As of 8.0, this class * loader implements {@link InstrumentableClassLoader}, permitting web * application classes to instrument other classes in the same web * application. It does not permit instrumentation of system or container * classes or classes in other web apps. * * @author Remy Maucherat * @author Craig R. McClanahan * @version $Id$ */ public class WebappClassLoader extends URLClassLoader implements Lifecycle, InstrumentableClassLoader { private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog( WebappClassLoader.class ); /** * 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"; private static final String CLASS_FILE_SUFFIX = ".class"; 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 /** * Regular expression of package names which are not allowed to be loaded * from a webapp class loader without delegating first. */ protected final Matcher packageTriggersDeny = Pattern.compile( "^javax\\.el\\.|" + "^javax\\.servlet\\.|" + "^org\\.apache\\.(catalina|coyote|el|jasper|juli|naming|tomcat)\\." ).matcher(""); /** * Regular expression of package names which are allowed to be loaded from a * webapp class loader without delegating first and override any set by * {@link #packageTriggersDeny}. */ protected final Matcher packageTriggersPermit = Pattern.compile("^javax\\.servlet\\.jsp\\.jstl\\.").matcher(""); /** * The string manager for this package. */ protected static final StringManager sm = StringManager.getManager(Constants.Package); // ----------------------------------------------------------- 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 web resources for this webapp. * TODO Review the use of resources in this class to see if further * simplifications can be made. */ protected WebResourceRoot resources = null; /** * The cache of ResourceEntry for classes and resources we have loaded, * keyed by resource path, not binary name. Path is used as the key since * resources may be requested by binary name (classes) or path (other * resources such as property files) and the mapping from binary name to * path is unambiguous but the reverse mapping is ambiguous. */ protected final Map<String, ResourceEntry> resourceEntries = new ConcurrentHashMap<>(); /** * 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; private final HashMap<String,Long> jarModificationTimes = new HashMap<>(); /** * 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<>(); /** * 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; /** * Holds the class file transformers decorating this class loader. The * CopyOnWriteArrayList is thread safe. It is expensive on writes, but * those should be rare. It is very fast on reads, since synchronization * is not actually used. Importantly, the ClassLoader will never block * iterating over the transformers while loading a class. */ private final List<ClassFileTransformer> transformers = new CopyOnWriteArrayList<>(); // ------------------------------------------------------------- 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; } /** * If there is a Java SecurityManager create a read permission for the * target of the given URL as appropriate. * * @param url URL for a file or directory on local system */ void addPermission(URL url) { if (url == null) { return; } if (securityManager != null) { String protocol = url.getProtocol(); if ("file".equalsIgnoreCase(protocol)) { URI uri; File f; String path; try { uri = url.toURI(); f = new File(uri); path = f.getCanonicalPath(); } catch (IOException | URISyntaxException e) { log.warn(sm.getString( "webappClassLoader.addPermisionNoCanonicalFile", url.toExternalForm())); return; } if (f.isFile()) { // Allow the file to be read addPermission(new FilePermission(path, "read")); } else if (f.isDirectory()) { addPermission(new FilePermission(path, "read")); addPermission(new FilePermission( path + File.separator + "-", "read")); } else { // File does not exist - ignore (shouldn't happen) } } else { // Unsupported URL protocol log.warn(sm.getString( "webappClassLoader.addPermisionNoProtocol", protocol, url.toExternalForm())); } } } /** * If there is a Java SecurityManager create a Permission. * * @param permission The permission */ void addPermission(Permission permission) { if ((securityManager != null) && (permission != null)) { permissionList.add(permission); } } /** * 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 /** * Adds the specified class file transformer to this class loader. The * transformer will then be able to modify the bytecode of any classes * loaded by this class loader after the invocation of this method. * * @param transformer The transformer to add to the class loader */ @Override public void addTransformer(ClassFileTransformer transformer) { if (transformer == null) { throw new IllegalArgumentException(sm.getString( "webappClassLoader.addTransformer.illegalArgument", getContextName())); } if (this.transformers.contains(transformer)) { // if the same instance of this transformer was already added, bail out log.warn(sm.getString("webappClassLoader.addTransformer.duplicate", transformer, getContextName())); return; } this.transformers.add(transformer); log.info(sm.getString("webappClassLoader.addTransformer", transformer, getContextName())); } /** * Removes the specified class file transformer from this class loader. * It will no longer be able to modify the byte code of any classes * loaded by the class loader after the invocation of this method. * However, any classes already modified by this transformer will * remain transformed. * * @param transformer The transformer to remove */ @Override public void removeTransformer(ClassFileTransformer transformer) { if (transformer == null) { return; } if (this.transformers.remove(transformer)) { log.info(sm.getString("webappClassLoader.removeTransformer", transformer, getContextName())); return; } } /** * Returns a copy of this class loader without any class file * transformers. This is a tool often used by Java Persistence API * providers to inspect entity classes in the absence of any * instrumentation, something that can't be guaranteed within the * context of a {@link ClassFileTransformer}'s * {@link ClassFileTransformer#transform(ClassLoader, String, Class, * ProtectionDomain, byte[]) transform} method. * <p> * The returned class loader's resource cache will have been cleared * so that classes already instrumented will not be retained or * returned. * * @return the transformer-free copy of this class loader. */ @Override public WebappClassLoader copyWithoutTransformers() { WebappClassLoader result = new WebappClassLoader(this.parent); result.resources = this.resources; result.delegate = this.delegate; result.started = this.started; result.needConvert = this.needConvert; result.clearReferencesStatic = this.clearReferencesStatic; result.clearReferencesStopThreads = this.clearReferencesStopThreads; result.clearReferencesStopTimerThreads = this.clearReferencesStopTimerThreads; result.clearReferencesLogFactoryRelease = this.clearReferencesLogFactoryRelease; result.clearReferencesHttpClientKeepAliveThread = this.clearReferencesHttpClientKeepAliveThread; result.jarModificationTimes.putAll(this.jarModificationTimes); result.permissionList.addAll(this.permissionList); result.loaderPC.putAll(this.loaderPC); try { result.start(); } catch (LifecycleException e) { throw new IllegalStateException(e); } return result; } /** * Have one or more classes or resources been modified so that a reload * is appropriate? */ public boolean modified() { if (log.isDebugEnabled()) log.debug("modified()"); for (Entry<String,ResourceEntry> entry : resourceEntries.entrySet()) { long cachedLastModified = entry.getValue().lastModified; long lastModified = resources.getClassLoaderResource( entry.getKey()).getLastModified(); if (lastModified != cachedLastModified) { if( log.isDebugEnabled() ) log.debug(sm.getString("webappClassLoader.resourceModified", entry.getKey(), new Date(cachedLastModified), new Date(lastModified))); return true; } } // Check if JARs have been added or removed WebResource[] jars = resources.listResources("/WEB-INF/lib"); // Filter out non-JAR resources int jarCount = 0; for (WebResource jar : jars) { if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) { jarCount++; Long recordedLastModified = jarModificationTimes.get(jar.getName()); if (recordedLastModified == null) { // Jar has been added log.info(sm.getString("webappClassLoader.jarsAdded", resources.getContext().getName())); return true; } if (recordedLastModified.longValue() != jar.getLastModified()) { // Jar has been changed log.info(sm.getString("webappClassLoader.jarsModified", resources.getContext().getName())); return true; } } } if (jarCount < jarModificationTimes.size()){ log.info(sm.getString("webappClassLoader.jarsRemoved", resources.getContext().getName())); 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"); if (this.parent != null) { sb.append("----------> Parent Classloader:\r\n"); sb.append(this.parent.toString()); sb.append("\r\n"); } if (this.transformers.size() > 0) { sb.append("----------> Class file transformers:\r\n"); for (ClassFileTransformer transformer : this.transformers) { sb.append(transformer).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 The binary 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; String path = nameToPath(name); ResourceEntry entry = resourceEntries.get(path); if (entry == null) { if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, path); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, path); } } 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<>(); String path = nameToPath(name); WebResource[] webResources = resources.getClassLoaderResources(path); for (WebResource webResource : webResources) { if (webResource.exists()) { result.add(webResource.getURL()); } } return Collections.enumeration(result); } /** * 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) { 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 The binary 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 The binary 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 String resourceName = binaryNameToPath(name, false); if (system.getResource(resourceName) != null) { 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); } /** * {@inheritDoc} * <p> * Note that list of URLs returned by this method may not be complete. The * web application class loader accesses class loader resources via the * {@link WebResourceRoot} which supports the arbitrary mapping of * additional files, directories and contents of JAR files under * WEB-INF/classes. Any such resources will not be included in the URLs * returned here. */ @Override public URL[] getURLs() { return super.getURLs(); } // ------------------------------------------------------ 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 { WebResource classes = resources.getResource("/WEB-INF/classes"); if (classes.isDirectory() && classes.canRead()) { addURL(classes.getURL()); } WebResource[] jars = resources.listResources("/WEB-INF/lib"); for (WebResource jar : jars) { if (jar.getName().endsWith(".jar") && jar.isFile() && jar.canRead()) { addURL(jar.getURL()); jarModificationTimes.put( jar.getName(), Long.valueOf(jar.getLastModified())); } } 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; resourceEntries.clear(); jarModificationTimes.clear(); resources = null; parent = null; permissionList.clear(); loaderPC.clear(); } @Override public void destroy() { // NOOP } // ------------------------------------------------------ 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(); // Clear any custom URLStreamHandlers TomcatURLStreamHandlerFactory.release(this); } /** * 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(); @SuppressWarnings("unchecked") 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 = resourceEntries.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(); List<Thread> executorThreadsToStop = new ArrayList<>(); // 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 boolean usingExecutor = false; 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(); usingExecutor = true; } } } 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); } if (usingExecutor) { // Executor may take a short time to stop all the // threads. Make a note of threads that should be // stopped and check them at the end of the method. executorThreadsToStop.add(thread); } else { // 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(); } } } } // If thread stopping is enabled, executor threads should have been // stopped above when the executor was shut down but that depends on the // thread correctly handling the interrupt. Give all the executor // threads a few seconds shutdown and if they are still running // Give threads up to 2 seconds to shutdown int count = 0; for (Thread t : executorThreadsToStop) { while (t.isAlive() && count < 100) { try { Thread.sleep(20); } catch (InterruptedException e) { // Quit the while loop break; } count++; } if (t.isAlive()) { // 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. t.stop(); } } } /* * Look at a threads stack trace to see if it is a request thread or not. It * isn't perfect, but it should be good-enough for most cases. */ private boolean isRequestThread(Thread thread) { StackTraceElement[] elements = thread.getStackTrace(); if (elements == null || elements.length == 0) { // Must have stopped already. Too late to ignore it. Assume not a // request processing thread. return false; } // Step through the methods in reverse order looking for calls to any // CoyoteAdapter method. All request threads will have this unless // Tomcat has been heavily modified - in which case there isn't much we // can do. for (int i = 0; i < elements.length; i++) { StackTraceElement element = elements[elements.length - (i+1)]; if ("org.apache.catalina.connector.CoyoteAdapter".equals( element.getClassName())) { return true; } } return false; } private void clearReferencesStopTimerThread(Thread thread) { // Need to get references to: // in Sun/Oracle JDK: // - newTasksMayBeScheduled field (in java.util.TimerThread) // - queue field // - queue.clear() // in IBM JDK, Apache Harmony: // - cancel() method (in java.util.Timer$TimerImpl) try { try { Field newTasksMayBeScheduledField = thread.getClass().getDeclaredField("newTasksMayBeScheduled"); newTasksMayBeScheduledField.setAccessible(true); Field queueField = thread.getClass().getDeclaredField("queue"); queueField.setAccessible(true); Object queue = queueField.get(thread); Method clearMethod = queue.getClass().getDeclaredMethod("clear"); clearMethod.setAccessible(true); synchronized(queue) { newTasksMayBeScheduledField.setBoolean(thread, false); clearMethod.invoke(queue); queue.notify(); // In case queue was already empty. } }catch (NoSuchFieldException nfe){ Method cancelMethod = thread.getClass().getDeclaredMethod("cancel"); synchronized(thread) { cancelMethod.setAccessible(true); cancelMethod.invoke(thread); } } log.error(sm.getString("webappClassLoader.warnTimerThread", getContextName(), thread.getName())); } catch (Exception e) { // So many things to go wrong above... Throwable t = ExceptionUtils.unwrapInvocationTargetException(e); ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.stopTimerThreadFail", thread.getName(), getContextName()), t); } } private void checkThreadLocalsForLeaks() { Thread[] threads = getThreads(); try { // Make the fields in the Thread class that store ThreadLocals // accessible Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Field inheritableThreadLocalsField = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocalsField.setAccessible(true); // Make the underlying array of ThreadLoad.ThreadLocalMap.Entry objects // accessible Class<?> tlmClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = tlmClass.getDeclaredField("table"); tableField.setAccessible(true); Method expungeStaleEntriesMethod = tlmClass.getDeclaredMethod("expungeStaleEntries"); expungeStaleEntriesMethod.setAccessible(true); for (int i = 0; i < threads.length; i++) { Object threadLocalMap; if (threads[i] != null) { // Clear the first map threadLocalMap = threadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } // Clear the second map threadLocalMap =inheritableThreadLocalsField.get(threads[i]); if (null != threadLocalMap){ expungeStaleEntriesMethod.invoke(threadLocalMap); checkThreadLocalMapForLeaks(threadLocalMap, tableField); } } } } catch (Throwable t) { ExceptionUtils.handleThrowable(t); log.warn(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksFail", getContextName()), t); } } /** * Analyzes the given thread local map object. Also pass in the field that * points to the internal table to save re-calculating it on every * call to this method. */ private void checkThreadLocalMapForLeaks(Object map, Field internalTableField) throws IllegalAccessException, NoSuchFieldException { if (map != null) { Object[] table = (Object[]) internalTableField.get(map); if (table != null) { for (int j =0; j < table.length; j++) { Object obj = table[j]; if (obj != null) { boolean potentialLeak = false; // Check the key Object key = ((Reference<?>) obj).get(); if (this.equals(key) || loadedByThisOrChild(key)) { potentialLeak = true; } // Check the value Field valueField = obj.getClass().getDeclaredField("value"); valueField.setAccessible(true); Object value = valueField.get(obj); if (this.equals(value) || loadedByThisOrChild(value)) { potentialLeak = true; } if (potentialLeak) { Object[] args = new Object[5]; args[0] = getContextName(); if (key != null) { args[1] = getPrettyClassName(key.getClass()); try { args[2] = key.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badKey", args[1]), e); args[2] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value != null) { args[3] = getPrettyClassName(value.getClass()); try { args[4] = value.toString(); } catch (Exception e) { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.badValue", args[3]), e); args[4] = sm.getString( "webappClassLoader.checkThreadLocalsForLeaks.unknown"); } } if (value == null) { if (log.isDebugEnabled()) { log.debug(sm.getString( "webappClassLoader.checkThreadLocalsForLeaksDebug", args)); } } else { log.error(sm.getString( "webappClassLoader.checkThreadLocalsForLeaks", args)); } } } } } } } private String getPrettyClassName(Class<?> clazz) { String name = clazz.getCanonicalName(); if (name==null){ name = clazz.getName(); } return name; } /** * @param o object to test, may be null * @return <code>true</code> if o has been loaded by the current classloader * or one of its descendants. */ private boolean loadedByThisOrChild(Object o) { if (o == null) { return false; } Class<?> clazz; if (o instanceof Class) { clazz = (Class<?>) o; } else { clazz = o.getClass(); } ClassLoader cl = clazz.getClassLoader(); while (cl != null) { if (cl == this) { return true; } cl = cl.getParent(); } if (o instanceof Collection<?>) { Iterator<?> iter = ((Collection<?>) o).iterator(); try { while (iter.hasNext()) { Object entry = iter.next(); if (loadedByThisOrChild(entry)) { return true; } } } catch (ConcurrentModificationException e) { log.warn(sm.getString( "webappClassLoader", clazz.getName(), getContextName()), e); } } 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 try { while (tg.getParent() != null) { tg = tg.getParent(); } } catch (SecurityException se) { String msg = sm.getString( "webappClassLoader.getThreadGroupError", tg.getName()); if (log.isDebugEnabled()) { log.debug(msg, se); } else { log.warn(msg); } } 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); } } /** * Find specified class in local repositories. * * @param name The binary name of the class to be loaded * * @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 path = binaryNameToPath(name, true); ResourceEntry entry = null; if (securityManager != null) { PrivilegedAction<ResourceEntry> dp = new PrivilegedFindResourceByName(name, path); entry = AccessController.doPrivileged(dp); } else { entry = findResourceInternal(name, path); } 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)); } // Now the class has been defined, clear the elements of the local // resource cache that are no longer required. entry.loadedClass = clazz; entry.binaryContent = null; entry.codeBase = null; entry.manifest = null; entry.certificates = null; // Retain entry.source in case of a getResourceAsStream() call on // the class file after the class has been defined. } return clazz; } private String binaryNameToPath(String binaryName, boolean withLeadingSlash) { StringBuilder path = new StringBuilder( 1 + binaryName.length() + CLASS_FILE_SUFFIX.length()); if (withLeadingSlash) { path.append('/'); } path.append(binaryName.replace('.', '/')); path.append(CLASS_FILE_SUFFIX); return path.toString(); } private String nameToPath(String name) { if (name.startsWith("/")) { return name; } StringBuilder path = new StringBuilder( 1 + name.length()); path.append('/'); path.append(name); return path.toString(); } /** * Find specified resource in local repositories. * * @return the loaded resource, or null if the resource isn't found */ protected ResourceEntry findResourceInternal(final String name, final String path) { if (!started) { log.info(sm.getString("webappClassLoader.stopped", name)); return null; } if ((name == null) || (path == null)) return null; ResourceEntry entry = resourceEntries.get(path); if (entry != null) return entry; boolean isClassResource = path.endsWith(CLASS_FILE_SUFFIX); WebResource resource = null; boolean fileNeedConvert = false; resource = resources.getClassLoaderResource(path); if (!resource.exists()) { return null; } entry = new ResourceEntry(); entry.source = resource.getURL(); entry.codeBase = entry.source; entry.lastModified = resource.getLastModified(); if (needConvert) { if (path.endsWith(".properties")) { fileNeedConvert = true; } } /* 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 (isClassResource || fileNeedConvert) { byte[] binaryContent = resource.getContent(); if (binaryContent != 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); try { binaryContent = str.getBytes(StandardCharsets.UTF_8); } catch (Exception e) { return null; } } entry.binaryContent = binaryContent; // The certificates and manifest are made available as a side // effect of reading the binary content entry.certificates = resource.getCertificates(); } } entry.manifest = resource.getManifest(); if (isClassResource && entry.binaryContent != null && this.transformers.size() > 0) { // If the resource is a class just being loaded, decorate it // with any attached transformers String className = name.endsWith(CLASS_FILE_SUFFIX) ? name.substring(0, name.length() - CLASS_FILE_SUFFIX.length()) : name; String internalName = className.replace(".", "/"); for (ClassFileTransformer transformer : this.transformers) { try { byte[] transformed = transformer.transform( this, internalName, null, null, entry.binaryContent ); if (transformed != null) { entry.binaryContent = transformed; } } catch (IllegalClassFormatException e) { log.error(sm.getString("webappClassLoader.transformError", name), e); return null; } } } // 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(path); if (entry2 == null) { resourceEntries.put(path, 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) { String path = nameToPath(name); ResourceEntry entry = resourceEntries.get(path); 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 The binary name of the resource to return */ protected Class<?> findLoadedClass0(String name) { String path = binaryNameToPath(name, true); ResourceEntry entry = resourceEntries.get(path); if (entry != null) { return entry.loadedClass; } return null; } /** * 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 synchronized 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; packageTriggersPermit.reset(packageName); if (packageTriggersPermit.lookingAt()) { return false; } packageTriggersDeny.reset(packageName); if (packageTriggersDeny.lookingAt()) { 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; } }
56,029
Bug 56029 Ternary operator doesn't work as expected inside attributes in jspx pages
null
resolved fixed
b430e29
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-18T19:33:19Z
2014-01-18T18:33:20Z
java/org/apache/jasper/compiler/ELParser.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.JasperException; import org.apache.jasper.compiler.ELNode.ELText; import org.apache.jasper.compiler.ELNode.Function; import org.apache.jasper.compiler.ELNode.Root; import org.apache.jasper.compiler.ELNode.Text; /** * This class implements a parser for EL expressions. * * It takes strings of the form xxx${..}yyy${..}zzz etc, and turn it into a * ELNode.Nodes. * * Currently, it only handles text outside ${..} and functions in ${ ..}. * * @author Kin-man Chung */ public class ELParser { private Token curToken; // current token private Token prevToken; // previous token private final ELNode.Nodes expr; private ELNode.Nodes ELexpr; private int index; // Current index of the expression private final String expression; // The EL expression private char type; private final boolean isDeferredSyntaxAllowedAsLiteral; private static final String reservedWords[] = { "and", "div", "empty", "eq", "false", "ge", "gt", "instanceof", "le", "lt", "mod", "ne", "not", "null", "or", "true" }; public ELParser(String expression, boolean isDeferredSyntaxAllowedAsLiteral) { index = 0; this.expression = expression; this.isDeferredSyntaxAllowedAsLiteral = isDeferredSyntaxAllowedAsLiteral; expr = new ELNode.Nodes(); } /** * Parse an EL expression * * @param expression * The input expression string of the form Char* ('${' Char* * '}')* Char* * @param isDeferredSyntaxAllowedAsLiteral * Are deferred expressions treated as literals? * @return Parsed EL expression in ELNode.Nodes */ public static ELNode.Nodes parse(String expression, boolean isDeferredSyntaxAllowedAsLiteral) { ELParser parser = new ELParser(expression, isDeferredSyntaxAllowedAsLiteral); while (parser.hasNextChar()) { String text = parser.skipUntilEL(); if (text.length() > 0) { parser.expr.add(new ELNode.Text(text)); } ELNode.Nodes elexpr = parser.parseEL(); if (!elexpr.isEmpty()) { parser.expr.add(new ELNode.Root(elexpr, parser.type)); } } return parser.expr; } /** * Parse an EL expression string '${...}'. Currently only separates the EL * into functions and everything else. * * @return An ELNode.Nodes representing the EL expression * * TODO: Can this be refactored to use the standard EL implementation? */ private ELNode.Nodes parseEL() { StringBuilder buf = new StringBuilder(); ELexpr = new ELNode.Nodes(); while (hasNext()) { curToken = nextToken(); if (curToken instanceof Char) { if (curToken.toChar() == '}') { break; } buf.append(curToken.toChar()); } else { // Output whatever is in buffer if (buf.length() > 0) { ELexpr.add(new ELNode.ELText(buf.toString())); buf = new StringBuilder(); } if (!parseFunction()) { ELexpr.add(new ELNode.ELText(curToken.toString())); } } } if (buf.length() > 0) { ELexpr.add(new ELNode.ELText(buf.toString())); } return ELexpr; } /** * Parse for a function FunctionInvokation ::= (identifier ':')? identifier * '(' (Expression (,Expression)*)? ')' Note: currently we don't parse * arguments */ private boolean parseFunction() { if (!(curToken instanceof Id) || isELReserved(curToken.toString()) || prevToken instanceof Char && prevToken.toChar() == '.') { return false; } String s1 = null; // Function prefix String s2 = curToken.toString(); // Function name if (hasNext()) { int mark = getIndex(); curToken = nextToken(); if (curToken.toChar() == ':') { if (hasNext()) { Token t2 = nextToken(); if (t2 instanceof Id) { s1 = s2; s2 = t2.toString(); if (hasNext()) { curToken = nextToken(); } } } } if (curToken.toChar() == '(') { ELexpr.add(new ELNode.Function(s1, s2)); return true; } curToken = prevToken; setIndex(mark); } return false; } /** * Test if an id is a reserved word in EL */ private boolean isELReserved(String id) { int i = 0; int j = reservedWords.length; while (i < j) { int k = (i + j) / 2; int result = reservedWords[k].compareTo(id); if (result == 0) { return true; } if (result < 0) { i = k + 1; } else { j = k; } } return false; } /** * Skip until an EL expression ('${' || '#{') is reached, allowing escape * sequences '\\' and '\$' and '\#'. * * @return The text string up to the EL expression */ private String skipUntilEL() { char prev = 0; StringBuilder buf = new StringBuilder(); while (hasNextChar()) { char ch = nextChar(); if (prev == '\\') { prev = 0; if (ch == '\\') { buf.append('\\'); prev = '\\'; } else if (ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')) { buf.append(ch); } // else error! } else if (prev == '$' || (!isDeferredSyntaxAllowedAsLiteral && prev == '#')) { if (ch == '{') { this.type = prev; prev = 0; break; } buf.append(prev); prev = 0; } if (ch == '\\' || ch == '$' || (!isDeferredSyntaxAllowedAsLiteral && ch == '#')) { prev = ch; } else { buf.append(ch); } } if (prev != 0) { buf.append(prev); } return buf.toString(); } /* * @return true if there is something left in EL expression buffer other * than white spaces. */ private boolean hasNext() { skipSpaces(); return hasNextChar(); } /* * @return The next token in the EL expression buffer. */ private Token nextToken() { prevToken = curToken; skipSpaces(); if (hasNextChar()) { char ch = nextChar(); if (Character.isJavaIdentifierStart(ch)) { StringBuilder buf = new StringBuilder(); buf.append(ch); while (index < expression.length() && Character.isJavaIdentifierPart( ch = expression.charAt(index))) { buf.append(ch); nextChar(); } return new Id(buf.toString()); } if (ch == '\'' || ch == '"') { return parseQuotedChars(ch); } else { // For now... return new Char(ch); } } return null; } /* * Parse a string in single or double quotes, allowing for escape sequences * '\\', and ('\"', or "\'") */ private Token parseQuotedChars(char quote) { StringBuilder buf = new StringBuilder(); buf.append(quote); while (hasNextChar()) { char ch = nextChar(); if (ch == '\\') { ch = nextChar(); if (ch == '\\' || ch == quote) { buf.append(ch); } // else error! } else if (ch == quote) { buf.append(ch); break; } else { buf.append(ch); } } return new QuotedString(buf.toString()); } /* * A collection of low level parse methods dealing with character in the EL * expression buffer. */ private void skipSpaces() { while (hasNextChar()) { if (expression.charAt(index) > ' ') break; index++; } } private boolean hasNextChar() { return index < expression.length(); } private char nextChar() { if (index >= expression.length()) { return (char) -1; } return expression.charAt(index++); } private int getIndex() { return index; } private void setIndex(int i) { index = i; } /* * Represents a token in EL expression string */ private static class Token { char toChar() { return 0; } @Override public String toString() { return ""; } } /* * Represents an ID token in EL */ private static class Id extends Token { String id; Id(String id) { this.id = id; } @Override public String toString() { return id; } } /* * Represents a character token in EL */ private static class Char extends Token { private char ch; Char(char ch) { this.ch = ch; } @Override char toChar() { return ch; } @Override public String toString() { return (new Character(ch)).toString(); } } /* * Represents a quoted (single or double) string token in EL */ private static class QuotedString extends Token { private String value; QuotedString(String v) { this.value = v; } @Override public String toString() { return value; } } public char getType() { return type; } protected static class TextBuilder extends ELNode.Visitor { protected StringBuilder output = new StringBuilder(); public String getText() { return output.toString(); } @Override public void visit(Root n) throws JasperException { output.append(n.getType()); output.append('{'); n.getExpression().visit(this); output.append('}'); } @Override public void visit(Function n) throws JasperException { if (n.getPrefix() != null) { output.append(n.getPrefix()); output.append(':'); } output.append(n.getName()); output.append('('); } @Override public void visit(Text n) throws JasperException { output.append(n.getText()); } @Override public void visit(ELText n) throws JasperException { output.append(n.getText()); } } }
56,029
Bug 56029 Ternary operator doesn't work as expected inside attributes in jspx pages
null
resolved fixed
b430e29
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-18T19:33:19Z
2014-01-18T18:33:20Z
test/org/apache/jasper/compiler/TestELParser.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.junit.Assert; import org.junit.Test; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.ELNode.Nodes; import org.apache.jasper.compiler.ELParser.TextBuilder; public class TestELParser { @Test public void testText() throws JasperException { doTestParser("foo"); } @Test public void testLiteral() throws JasperException { doTestParser("${'foo'}"); } @Test public void testVariable() throws JasperException { doTestParser("${test}"); } @Test public void testFunction01() throws JasperException { doTestParser("${do(x)}"); } @Test public void testFunction02() throws JasperException { doTestParser("${do:it(x)}"); } @Test public void testFunction03() throws JasperException { doTestParser("${do:it(x,y)}"); } @Test public void testFunction04() throws JasperException { doTestParser("${do:it(x,y,z)}"); } @Test public void testCompound01() throws JasperException { doTestParser("1${'foo'}1"); } @Test public void testCompound02() throws JasperException { doTestParser("1${test}1"); } @Test public void testCompound03() throws JasperException { doTestParser("${foo}${bar}"); } private void doTestParser(String input) throws JasperException { Nodes nodes = ELParser.parse(input, false); TextBuilder textBuilder = new TextBuilder(); nodes.visit(textBuilder); Assert.assertEquals(input, textBuilder.getText()); } }
56,012
Bug 56012 wrong import statement generation while using the extends attribute of the page directive
null
resolved fixed
42056be
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-18T21:24:37Z
2014-01-15T12:46:40Z
java/org/apache/jasper/compiler/PageInfo.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import javax.el.ExpressionFactory; import javax.servlet.jsp.tagext.TagLibraryInfo; import org.apache.jasper.Constants; import org.apache.jasper.JasperException; /** * A repository for various info about the translation unit under compilation. * * @author Kin-man Chung */ class PageInfo { private final Vector<String> imports; private final Map<String,Long> dependants; private final BeanRepository beanRepository; private final Set<String> varInfoNames; private final HashMap<String,TagLibraryInfo> taglibsMap; private final HashMap<String, String> jspPrefixMapper; private final HashMap<String, LinkedList<String>> xmlPrefixMapper; private final HashMap<String, Mark> nonCustomTagPrefixMap; private final String jspFile; private final String defaultLanguage = "java"; private String language; private final String defaultExtends = Constants.JSP_SERVLET_BASE; private String xtends; private String contentType = null; private String session; private boolean isSession = true; private String bufferValue; private int buffer = 8*1024; // XXX confirm private String autoFlush; private boolean isAutoFlush = true; private String isThreadSafeValue; private boolean isThreadSafe = true; private String isErrorPageValue; private boolean isErrorPage = false; private String errorPage = null; private String info; private boolean scriptless = false; private boolean scriptingInvalid = false; private String isELIgnoredValue; private boolean isELIgnored = false; // JSP 2.1 private String deferredSyntaxAllowedAsLiteralValue; private boolean deferredSyntaxAllowedAsLiteral = false; private final ExpressionFactory expressionFactory = ExpressionFactory.newInstance(); private String trimDirectiveWhitespacesValue; private boolean trimDirectiveWhitespaces = false; private String omitXmlDecl = null; private String doctypeName = null; private String doctypePublic = null; private String doctypeSystem = null; private boolean isJspPrefixHijacked; // Set of all element and attribute prefixes used in this translation unit private final HashSet<String> prefixes; private boolean hasJspRoot = false; private Collection<String> includePrelude; private Collection<String> includeCoda; private final Vector<String> pluginDcls; // Id's for tagplugin declarations // JSP 2.2 private boolean errorOnUndeclaredNamepsace = false; private final boolean isTagFile; PageInfo(BeanRepository beanRepository, String jspFile, boolean isTagFile) { this.isTagFile = isTagFile; this.jspFile = jspFile; this.beanRepository = beanRepository; this.varInfoNames = new HashSet<>(); this.taglibsMap = new HashMap<>(); this.jspPrefixMapper = new HashMap<>(); this.xmlPrefixMapper = new HashMap<>(); this.nonCustomTagPrefixMap = new HashMap<>(); this.imports = new Vector<>(); this.dependants = new HashMap<>(); this.includePrelude = new Vector<>(); this.includeCoda = new Vector<>(); this.pluginDcls = new Vector<>(); this.prefixes = new HashSet<>(); // Enter standard imports imports.addAll(Constants.STANDARD_IMPORTS); } public boolean isTagFile() { return isTagFile; } /** * Check if the plugin ID has been previously declared. Make a not * that this Id is now declared. * @return true if Id has been declared. */ public boolean isPluginDeclared(String id) { if (pluginDcls.contains(id)) return true; pluginDcls.add(id); return false; } public void addImports(List<String> imports) { this.imports.addAll(imports); } public void addImport(String imp) { this.imports.add(imp); } public List<String> getImports() { return imports; } public String getJspFile() { return jspFile; } public void addDependant(String d, Long lastModified) { if (!dependants.containsKey(d) && !jspFile.equals(d)) dependants.put(d, lastModified); } public Map<String,Long> getDependants() { return dependants; } public BeanRepository getBeanRepository() { return beanRepository; } public void setScriptless(boolean s) { scriptless = s; } public boolean isScriptless() { return scriptless; } public void setScriptingInvalid(boolean s) { scriptingInvalid = s; } public boolean isScriptingInvalid() { return scriptingInvalid; } public Collection<String> getIncludePrelude() { return includePrelude; } public void setIncludePrelude(Collection<String> prelude) { includePrelude = prelude; } public Collection<String> getIncludeCoda() { return includeCoda; } public void setIncludeCoda(Collection<String> coda) { includeCoda = coda; } public void setHasJspRoot(boolean s) { hasJspRoot = s; } public boolean hasJspRoot() { return hasJspRoot; } public String getOmitXmlDecl() { return omitXmlDecl; } public void setOmitXmlDecl(String omit) { omitXmlDecl = omit; } public String getDoctypeName() { return doctypeName; } public void setDoctypeName(String doctypeName) { this.doctypeName = doctypeName; } public String getDoctypeSystem() { return doctypeSystem; } public void setDoctypeSystem(String doctypeSystem) { this.doctypeSystem = doctypeSystem; } public String getDoctypePublic() { return doctypePublic; } public void setDoctypePublic(String doctypePublic) { this.doctypePublic = doctypePublic; } /* Tag library and XML namespace management methods */ public void setIsJspPrefixHijacked(boolean isHijacked) { isJspPrefixHijacked = isHijacked; } public boolean isJspPrefixHijacked() { return isJspPrefixHijacked; } /* * Adds the given prefix to the set of prefixes of this translation unit. * * @param prefix The prefix to add */ public void addPrefix(String prefix) { prefixes.add(prefix); } /* * Checks to see if this translation unit contains the given prefix. * * @param prefix The prefix to check * * @return true if this translation unit contains the given prefix, false * otherwise */ public boolean containsPrefix(String prefix) { return prefixes.contains(prefix); } /* * Maps the given URI to the given tag library. * * @param uri The URI to map * @param info The tag library to be associated with the given URI */ public void addTaglib(String uri, TagLibraryInfo info) { taglibsMap.put(uri, info); } /* * Gets the tag library corresponding to the given URI. * * @return Tag library corresponding to the given URI */ public TagLibraryInfo getTaglib(String uri) { return taglibsMap.get(uri); } /* * Gets the collection of tag libraries that are associated with a URI * * @return Collection of tag libraries that are associated with a URI */ public Collection<TagLibraryInfo> getTaglibs() { return taglibsMap.values(); } /* * Checks to see if the given URI is mapped to a tag library. * * @param uri The URI to map * * @return true if the given URI is mapped to a tag library, false * otherwise */ public boolean hasTaglib(String uri) { return taglibsMap.containsKey(uri); } /* * Maps the given prefix to the given URI. * * @param prefix The prefix to map * @param uri The URI to be associated with the given prefix */ public void addPrefixMapping(String prefix, String uri) { jspPrefixMapper.put(prefix, uri); } /* * Pushes the given URI onto the stack of URIs to which the given prefix * is mapped. * * @param prefix The prefix whose stack of URIs is to be pushed * @param uri The URI to be pushed onto the stack */ public void pushPrefixMapping(String prefix, String uri) { LinkedList<String> stack = xmlPrefixMapper.get(prefix); if (stack == null) { stack = new LinkedList<>(); xmlPrefixMapper.put(prefix, stack); } stack.addFirst(uri); } /* * Removes the URI at the top of the stack of URIs to which the given * prefix is mapped. * * @param prefix The prefix whose stack of URIs is to be popped */ public void popPrefixMapping(String prefix) { LinkedList<String> stack = xmlPrefixMapper.get(prefix); stack.removeFirst(); } /* * Returns the URI to which the given prefix maps. * * @param prefix The prefix whose URI is sought * * @return The URI to which the given prefix maps */ public String getURI(String prefix) { String uri = null; LinkedList<String> stack = xmlPrefixMapper.get(prefix); if (stack == null || stack.size() == 0) { uri = jspPrefixMapper.get(prefix); } else { uri = stack.getFirst(); } return uri; } /* Page/Tag directive attributes */ /* * language */ public void setLanguage(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if (!"java".equalsIgnoreCase(value)) { if (pagedir) err.jspError(n, "jsp.error.page.language.nonjava"); else err.jspError(n, "jsp.error.tag.language.nonjava"); } language = value; } public String getLanguage(boolean useDefault) { return (language == null && useDefault ? defaultLanguage : language); } /* * extends */ public void setExtends(String value, Node.PageDirective n) { xtends = value; /* * If page superclass is top level class (i.e. not in a package) * explicitly import it. If this is not done, the compiler will assume * the extended class is in the same pkg as the generated servlet. */ if (value.indexOf('.') < 0) n.addImport(value); } /** * Gets the value of the 'extends' page directive attribute. * * @param useDefault TRUE if the default * (org.apache.jasper.runtime.HttpJspBase) should be returned if this * attribute has not been set, FALSE otherwise * * @return The value of the 'extends' page directive attribute, or the * default (org.apache.jasper.runtime.HttpJspBase) if this attribute has * not been set and useDefault is TRUE */ public String getExtends(boolean useDefault) { return (xtends == null && useDefault ? defaultExtends : xtends); } /** * Gets the value of the 'extends' page directive attribute. * * @return The value of the 'extends' page directive attribute, or the * default (org.apache.jasper.runtime.HttpJspBase) if this attribute has * not been set */ public String getExtends() { return getExtends(true); } /* * contentType */ public void setContentType(String value) { contentType = value; } public String getContentType() { return contentType; } /* * buffer */ public void setBufferValue(String value, Node n, ErrorDispatcher err) throws JasperException { if ("none".equalsIgnoreCase(value)) buffer = 0; else { if (value == null || !value.endsWith("kb")) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } try { @SuppressWarnings("null") // value can't be null here Integer k = new Integer(value.substring(0, value.length()-2)); buffer = k.intValue() * 1024; } catch (NumberFormatException e) { if (n == null) { err.jspError("jsp.error.page.invalid.buffer"); } else { err.jspError(n, "jsp.error.page.invalid.buffer"); } } } bufferValue = value; } public String getBufferValue() { return bufferValue; } public int getBuffer() { return buffer; } /* * session */ public void setSession(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isSession = true; else if ("false".equalsIgnoreCase(value)) isSession = false; else err.jspError(n, "jsp.error.page.invalid.session"); session = value; } public String getSession() { return session; } public boolean isSession() { return isSession; } /* * autoFlush */ public void setAutoFlush(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isAutoFlush = true; else if ("false".equalsIgnoreCase(value)) isAutoFlush = false; else err.jspError(n, "jsp.error.autoFlush.invalid"); autoFlush = value; } public String getAutoFlush() { return autoFlush; } public boolean isAutoFlush() { return isAutoFlush; } /* * isThreadSafe */ public void setIsThreadSafe(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isThreadSafe = true; else if ("false".equalsIgnoreCase(value)) isThreadSafe = false; else err.jspError(n, "jsp.error.page.invalid.isthreadsafe"); isThreadSafeValue = value; } public String getIsThreadSafe() { return isThreadSafeValue; } public boolean isThreadSafe() { return isThreadSafe; } /* * info */ public void setInfo(String value) { info = value; } public String getInfo() { return info; } /* * errorPage */ public void setErrorPage(String value) { errorPage = value; } public String getErrorPage() { return errorPage; } /* * isErrorPage */ public void setIsErrorPage(String value, Node n, ErrorDispatcher err) throws JasperException { if ("true".equalsIgnoreCase(value)) isErrorPage = true; else if ("false".equalsIgnoreCase(value)) isErrorPage = false; else err.jspError(n, "jsp.error.page.invalid.iserrorpage"); isErrorPageValue = value; } public String getIsErrorPage() { return isErrorPageValue; } public boolean isErrorPage() { return isErrorPage; } /* * isELIgnored */ public void setIsELIgnored(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) isELIgnored = true; else if ("false".equalsIgnoreCase(value)) isELIgnored = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.iselignored"); else err.jspError(n, "jsp.error.tag.invalid.iselignored"); } isELIgnoredValue = value; } /* * deferredSyntaxAllowedAsLiteral */ public void setDeferredSyntaxAllowedAsLiteral(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) deferredSyntaxAllowedAsLiteral = true; else if ("false".equalsIgnoreCase(value)) deferredSyntaxAllowedAsLiteral = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.deferredsyntaxallowedasliteral"); else err.jspError(n, "jsp.error.tag.invalid.deferredsyntaxallowedasliteral"); } deferredSyntaxAllowedAsLiteralValue = value; } /* * trimDirectiveWhitespaces */ public void setTrimDirectiveWhitespaces(String value, Node n, ErrorDispatcher err, boolean pagedir) throws JasperException { if ("true".equalsIgnoreCase(value)) trimDirectiveWhitespaces = true; else if ("false".equalsIgnoreCase(value)) trimDirectiveWhitespaces = false; else { if (pagedir) err.jspError(n, "jsp.error.page.invalid.trimdirectivewhitespaces"); else err.jspError(n, "jsp.error.tag.invalid.trimdirectivewhitespaces"); } trimDirectiveWhitespacesValue = value; } public void setELIgnored(boolean s) { isELIgnored = s; } public String getIsELIgnored() { return isELIgnoredValue; } public boolean isELIgnored() { return isELIgnored; } public void putNonCustomTagPrefix(String prefix, Mark where) { nonCustomTagPrefixMap.put(prefix, where); } public Mark getNonCustomTagPrefix(String prefix) { return nonCustomTagPrefixMap.get(prefix); } public String getDeferredSyntaxAllowedAsLiteral() { return deferredSyntaxAllowedAsLiteralValue; } public boolean isDeferredSyntaxAllowedAsLiteral() { return deferredSyntaxAllowedAsLiteral; } public void setDeferredSyntaxAllowedAsLiteral(boolean isELDeferred) { this.deferredSyntaxAllowedAsLiteral = isELDeferred; } public ExpressionFactory getExpressionFactory() { return expressionFactory; } public String getTrimDirectiveWhitespaces() { return trimDirectiveWhitespacesValue; } public boolean isTrimDirectiveWhitespaces() { return trimDirectiveWhitespaces; } public void setTrimDirectiveWhitespaces(boolean trimDirectiveWhitespaces) { this.trimDirectiveWhitespaces = trimDirectiveWhitespaces; } public Set<String> getVarInfoNames() { return varInfoNames; } public boolean isErrorOnUndeclaredNamespace() { return errorOnUndeclaredNamepsace; } public void setErrorOnUndeclaredNamespace( boolean errorOnUndeclaredNamespace) { this.errorOnUndeclaredNamepsace = errorOnUndeclaredNamespace; } }
56,012
Bug 56012 wrong import statement generation while using the extends attribute of the page directive
null
resolved fixed
42056be
Tomcat
https://github.com/apache/tomcat
apache/tomcat
java
null
null
null
2014-01-18T21:24:37Z
2014-01-15T12:46:40Z
java/org/apache/jasper/compiler/Validator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.compiler; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Locale; import javax.el.ELException; import javax.el.ExpressionFactory; import javax.el.FunctionMapper; import javax.servlet.jsp.JspFactory; import javax.servlet.jsp.tagext.FunctionInfo; import javax.servlet.jsp.tagext.PageData; import javax.servlet.jsp.tagext.TagAttributeInfo; import javax.servlet.jsp.tagext.TagData; import javax.servlet.jsp.tagext.TagExtraInfo; import javax.servlet.jsp.tagext.TagInfo; import javax.servlet.jsp.tagext.TagLibraryInfo; import javax.servlet.jsp.tagext.ValidationMessage; import org.apache.jasper.JasperException; import org.apache.jasper.compiler.ELNode.Text; import org.apache.jasper.el.ELContextImpl; import org.xml.sax.Attributes; /** * Performs validation on the page elements. Attributes are checked for * mandatory presence, entry value validity, and consistency. As a side effect, * some page global value (such as those from page directives) are stored, for * later use. * * @author Kin-man Chung * @author Jan Luehe * @author Shawn Bayern * @author Mark Roth */ class Validator { /** * A visitor to validate and extract page directive info */ private static class DirectiveVisitor extends Node.Visitor { private final PageInfo pageInfo; private final ErrorDispatcher err; private static final JspUtil.ValidAttribute[] pageDirectiveAttrs = { new JspUtil.ValidAttribute("language"), new JspUtil.ValidAttribute("extends"), new JspUtil.ValidAttribute("import"), new JspUtil.ValidAttribute("session"), new JspUtil.ValidAttribute("buffer"), new JspUtil.ValidAttribute("autoFlush"), new JspUtil.ValidAttribute("isThreadSafe"), new JspUtil.ValidAttribute("info"), new JspUtil.ValidAttribute("errorPage"), new JspUtil.ValidAttribute("isErrorPage"), new JspUtil.ValidAttribute("contentType"), new JspUtil.ValidAttribute("pageEncoding"), new JspUtil.ValidAttribute("isELIgnored"), new JspUtil.ValidAttribute("deferredSyntaxAllowedAsLiteral"), new JspUtil.ValidAttribute("trimDirectiveWhitespaces") }; private boolean pageEncodingSeen = false; /* * Constructor */ DirectiveVisitor(Compiler compiler) { this.pageInfo = compiler.getPageInfo(); this.err = compiler.getErrorDispatcher(); } @Override public void visit(Node.IncludeDirective n) throws JasperException { // Since pageDirectiveSeen flag only applies to the Current page // save it here and restore it after the file is included. boolean pageEncodingSeenSave = pageEncodingSeen; pageEncodingSeen = false; visitBody(n); pageEncodingSeen = pageEncodingSeenSave; } @Override public void visit(Node.PageDirective n) throws JasperException { JspUtil.checkAttributes("Page directive", n, pageDirectiveAttrs, err); // JSP.2.10.1 Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, true); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.language", pageInfo.getLanguage(false), value); } } else if ("extends".equals(attr)) { if (pageInfo.getExtends(false) == null) { pageInfo.setExtends(value, n); } else if (!pageInfo.getExtends(false).equals(value)) { err.jspError(n, "jsp.error.page.conflict.extends", pageInfo.getExtends(false), value); } } else if ("contentType".equals(attr)) { if (pageInfo.getContentType() == null) { pageInfo.setContentType(value); } else if (!pageInfo.getContentType().equals(value)) { err.jspError(n, "jsp.error.page.conflict.contenttype", pageInfo.getContentType(), value); } } else if ("session".equals(attr)) { if (pageInfo.getSession() == null) { pageInfo.setSession(value, n, err); } else if (!pageInfo.getSession().equals(value)) { err.jspError(n, "jsp.error.page.conflict.session", pageInfo.getSession(), value); } } else if ("buffer".equals(attr)) { if (pageInfo.getBufferValue() == null) { pageInfo.setBufferValue(value, n, err); } else if (!pageInfo.getBufferValue().equals(value)) { err.jspError(n, "jsp.error.page.conflict.buffer", pageInfo.getBufferValue(), value); } } else if ("autoFlush".equals(attr)) { if (pageInfo.getAutoFlush() == null) { pageInfo.setAutoFlush(value, n, err); } else if (!pageInfo.getAutoFlush().equals(value)) { err.jspError(n, "jsp.error.page.conflict.autoflush", pageInfo.getAutoFlush(), value); } } else if ("isThreadSafe".equals(attr)) { if (pageInfo.getIsThreadSafe() == null) { pageInfo.setIsThreadSafe(value, n, err); } else if (!pageInfo.getIsThreadSafe().equals(value)) { err.jspError(n, "jsp.error.page.conflict.isthreadsafe", pageInfo.getIsThreadSafe(), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, true); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("isErrorPage".equals(attr)) { if (pageInfo.getIsErrorPage() == null) { pageInfo.setIsErrorPage(value, n, err); } else if (!pageInfo.getIsErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.iserrorpage", pageInfo.getIsErrorPage(), value); } } else if ("errorPage".equals(attr)) { if (pageInfo.getErrorPage() == null) { pageInfo.setErrorPage(value); } else if (!pageInfo.getErrorPage().equals(value)) { err.jspError(n, "jsp.error.page.conflict.errorpage", pageInfo.getErrorPage(), value); } } else if ("info".equals(attr)) { if (pageInfo.getInfo() == null) { pageInfo.setInfo(value); } else if (!pageInfo.getInfo().equals(value)) { err.jspError(n, "jsp.error.page.conflict.info", pageInfo.getInfo(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.page.multi.pageencoding"); // 'pageEncoding' can occur at most once per file pageEncodingSeen = true; String actual = comparePageEncodings(value, n); n.getRoot().setPageEncoding(actual); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, true); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.page.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, true); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.page.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Check for bad combinations if (pageInfo.getBuffer() == 0 && !pageInfo.isAutoFlush()) err.jspError(n, "jsp.error.page.badCombo"); // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); } @Override public void visit(Node.TagDirective n) throws JasperException { // Note: Most of the validation is done in TagFileProcessor // when it created a TagInfo object from the // tag file in which the directive appeared. // This method does additional processing to collect page info Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { String attr = attrs.getQName(i); String value = attrs.getValue(i); if ("language".equals(attr)) { if (pageInfo.getLanguage(false) == null) { pageInfo.setLanguage(value, n, err, false); } else if (!pageInfo.getLanguage(false).equals(value)) { err.jspError(n, "jsp.error.tag.conflict.language", pageInfo.getLanguage(false), value); } } else if ("isELIgnored".equals(attr)) { if (pageInfo.getIsELIgnored() == null) { pageInfo.setIsELIgnored(value, n, err, false); } else if (!pageInfo.getIsELIgnored().equals(value)) { err.jspError(n, "jsp.error.tag.conflict.iselignored", pageInfo.getIsELIgnored(), value); } } else if ("pageEncoding".equals(attr)) { if (pageEncodingSeen) err.jspError(n, "jsp.error.tag.multi.pageencoding"); pageEncodingSeen = true; compareTagEncodings(value, n); n.getRoot().setPageEncoding(value); } else if ("deferredSyntaxAllowedAsLiteral".equals(attr)) { if (pageInfo.getDeferredSyntaxAllowedAsLiteral() == null) { pageInfo.setDeferredSyntaxAllowedAsLiteral(value, n, err, false); } else if (!pageInfo.getDeferredSyntaxAllowedAsLiteral() .equals(value)) { err .jspError( n, "jsp.error.tag.conflict.deferredsyntaxallowedasliteral", pageInfo .getDeferredSyntaxAllowedAsLiteral(), value); } } else if ("trimDirectiveWhitespaces".equals(attr)) { if (pageInfo.getTrimDirectiveWhitespaces() == null) { pageInfo.setTrimDirectiveWhitespaces(value, n, err, false); } else if (!pageInfo.getTrimDirectiveWhitespaces().equals( value)) { err .jspError( n, "jsp.error.tag.conflict.trimdirectivewhitespaces", pageInfo.getTrimDirectiveWhitespaces(), value); } } } // Attributes for imports for this node have been processed by // the parsers, just add them to pageInfo. pageInfo.addImports(n.getImports()); } @Override public void visit(Node.AttributeDirective n) throws JasperException { // Do nothing, since this attribute directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared } @Override public void visit(Node.VariableDirective n) throws JasperException { // Do nothing, since this variable directive has already been // validated by TagFileProcessor when it created a TagInfo object // from the tag file in which the directive appeared } /* * Compares page encodings specified in various places, and throws * exception in case of page encoding mismatch. * * @param pageDirEnc The value of the pageEncoding attribute of the page * directive @param pageDir The page directive node * * @throws JasperException in case of page encoding mismatch */ private String comparePageEncodings(String thePageDirEnc, Node.PageDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String configEnc = root.getJspConfigPageEncoding(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the JSP config element whose URL * pattern matches this page. Treat "UTF-16", "UTF-16BE", and * "UTF-16LE" as identical. */ if (configEnc != null) { configEnc = configEnc.toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(configEnc) && (!pageDirEnc.startsWith("UTF-16") || !configEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.config_pagedir_encoding_mismatch", configEnc, pageDirEnc); } else { return configEnc; } } /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } else { return pageEnc; } } return pageDirEnc; } /* * Compares page encodings specified in various places, and throws * exception in case of page encoding mismatch. * * @param thePageDirEnc The value of the pageEncoding attribute of the page * directive @param pageDir The page directive node * * @throws JasperException in case of page encoding mismatch */ private void compareTagEncodings(String thePageDirEnc, Node.TagDirective pageDir) throws JasperException { Node.Root root = pageDir.getRoot(); String pageDirEnc = thePageDirEnc.toUpperCase(Locale.ENGLISH); /* * Compare the 'pageEncoding' attribute of the page directive with * the encoding specified in the XML prolog (only for XML syntax, * and only if JSP document contains XML prolog with encoding * declaration). Treat "UTF-16", "UTF-16BE", and "UTF-16LE" as * identical. */ if ((root.isXmlSyntax() && root.isEncodingSpecifiedInProlog()) || root.isBomPresent()) { String pageEnc = root.getPageEncoding().toUpperCase(Locale.ENGLISH); if (!pageDirEnc.equals(pageEnc) && (!pageDirEnc.startsWith("UTF-16") || !pageEnc .startsWith("UTF-16"))) { err.jspError(pageDir, "jsp.error.prolog_pagedir_encoding_mismatch", pageEnc, pageDirEnc); } } } } /** * A visitor for validating nodes other than page directives */ private static class ValidateVisitor extends Node.Visitor { private final PageInfo pageInfo; private final ErrorDispatcher err; private final ClassLoader loader; private final StringBuilder buf = new StringBuilder(32); private static final JspUtil.ValidAttribute[] jspRootAttrs = { new JspUtil.ValidAttribute("xsi:schemaLocation"), new JspUtil.ValidAttribute("version", true) }; private static final JspUtil.ValidAttribute[] includeDirectiveAttrs = { new JspUtil.ValidAttribute( "file", true) }; private static final JspUtil.ValidAttribute[] taglibDirectiveAttrs = { new JspUtil.ValidAttribute("uri"), new JspUtil.ValidAttribute("tagdir"), new JspUtil.ValidAttribute("prefix", true) }; private static final JspUtil.ValidAttribute[] includeActionAttrs = { new JspUtil.ValidAttribute("page", true), new JspUtil.ValidAttribute("flush") }; private static final JspUtil.ValidAttribute[] paramActionAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("value", true) }; private static final JspUtil.ValidAttribute[] forwardActionAttrs = { new JspUtil.ValidAttribute("page", true) }; private static final JspUtil.ValidAttribute[] getPropertyAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("property", true) }; private static final JspUtil.ValidAttribute[] setPropertyAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("property", true), new JspUtil.ValidAttribute("value", false), new JspUtil.ValidAttribute("param") }; private static final JspUtil.ValidAttribute[] useBeanAttrs = { new JspUtil.ValidAttribute("id", true), new JspUtil.ValidAttribute("scope"), new JspUtil.ValidAttribute("class"), new JspUtil.ValidAttribute("type"), new JspUtil.ValidAttribute("beanName", false) }; private static final JspUtil.ValidAttribute[] plugInAttrs = { new JspUtil.ValidAttribute("type", true), new JspUtil.ValidAttribute("code", true), new JspUtil.ValidAttribute("codebase"), new JspUtil.ValidAttribute("align"), new JspUtil.ValidAttribute("archive"), new JspUtil.ValidAttribute("height", false), new JspUtil.ValidAttribute("hspace"), new JspUtil.ValidAttribute("jreversion"), new JspUtil.ValidAttribute("name"), new JspUtil.ValidAttribute("vspace"), new JspUtil.ValidAttribute("width", false), new JspUtil.ValidAttribute("nspluginurl"), new JspUtil.ValidAttribute("iepluginurl") }; private static final JspUtil.ValidAttribute[] attributeAttrs = { new JspUtil.ValidAttribute("name", true), new JspUtil.ValidAttribute("trim"), new JspUtil.ValidAttribute("omit")}; private static final JspUtil.ValidAttribute[] invokeAttrs = { new JspUtil.ValidAttribute("fragment", true), new JspUtil.ValidAttribute("var"), new JspUtil.ValidAttribute("varReader"), new JspUtil.ValidAttribute("scope") }; private static final JspUtil.ValidAttribute[] doBodyAttrs = { new JspUtil.ValidAttribute("var"), new JspUtil.ValidAttribute("varReader"), new JspUtil.ValidAttribute("scope") }; private static final JspUtil.ValidAttribute[] jspOutputAttrs = { new JspUtil.ValidAttribute("omit-xml-declaration"), new JspUtil.ValidAttribute("doctype-root-element"), new JspUtil.ValidAttribute("doctype-public"), new JspUtil.ValidAttribute("doctype-system") }; private final ExpressionFactory expressionFactory; /* * Constructor */ ValidateVisitor(Compiler compiler) { this.pageInfo = compiler.getPageInfo(); this.err = compiler.getErrorDispatcher(); this.loader = compiler.getCompilationContext().getClassLoader(); // Get the cached EL expression factory for this context expressionFactory = JspFactory.getDefaultFactory().getJspApplicationContext( compiler.getCompilationContext().getServletContext()). getExpressionFactory(); } @Override public void visit(Node.JspRoot n) throws JasperException { JspUtil.checkAttributes("Jsp:root", n, jspRootAttrs, err); String version = n.getTextAttribute("version"); if (!version.equals("1.2") && !version.equals("2.0") && !version.equals("2.1") && !version.equals("2.2") && !version.equals("2.3")) { err.jspError(n, "jsp.error.jsproot.version.invalid", version); } visitBody(n); } @Override public void visit(Node.IncludeDirective n) throws JasperException { JspUtil.checkAttributes("Include directive", n, includeDirectiveAttrs, err); visitBody(n); } @Override public void visit(Node.TaglibDirective n) throws JasperException { JspUtil.checkAttributes("Taglib directive", n, taglibDirectiveAttrs, err); // Either 'uri' or 'tagdir' attribute must be specified String uri = n.getAttributeValue("uri"); String tagdir = n.getAttributeValue("tagdir"); if (uri == null && tagdir == null) { err.jspError(n, "jsp.error.taglibDirective.missing.location"); } if (uri != null && tagdir != null) { err .jspError(n, "jsp.error.taglibDirective.both_uri_and_tagdir"); } } @Override public void visit(Node.ParamAction n) throws JasperException { JspUtil.checkAttributes("Param action", n, paramActionAttrs, err); // make sure the value of the 'name' attribute is not a // request-time expression throwErrorIfExpression(n, "name", "jsp:param"); n.setValue(getJspAttribute(null, "value", null, null, n .getAttributeValue("value"), n, false)); visitBody(n); } @Override public void visit(Node.ParamsAction n) throws JasperException { // Make sure we've got at least one nested jsp:param Node.Nodes subElems = n.getBody(); if (subElems == null) { err.jspError(n, "jsp.error.params.emptyBody"); } visitBody(n); } @Override public void visit(Node.IncludeAction n) throws JasperException { JspUtil.checkAttributes("Include action", n, includeActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); } @Override public void visit(Node.ForwardAction n) throws JasperException { JspUtil.checkAttributes("Forward", n, forwardActionAttrs, err); n.setPage(getJspAttribute(null, "page", null, null, n .getAttributeValue("page"), n, false)); visitBody(n); } @Override public void visit(Node.GetProperty n) throws JasperException { JspUtil.checkAttributes("GetProperty", n, getPropertyAttrs, err); } @Override public void visit(Node.SetProperty n) throws JasperException { JspUtil.checkAttributes("SetProperty", n, setPropertyAttrs, err); String property = n.getTextAttribute("property"); String param = n.getTextAttribute("param"); String value = n.getAttributeValue("value"); n.setValue(getJspAttribute(null, "value", null, null, value, n, false)); boolean valueSpecified = n.getValue() != null; if ("*".equals(property)) { if (param != null || valueSpecified) err.jspError(n, "jsp.error.setProperty.invalid"); } else if (param != null && valueSpecified) { err.jspError(n, "jsp.error.setProperty.invalid"); } visitBody(n); } @Override public void visit(Node.UseBean n) throws JasperException { JspUtil.checkAttributes("UseBean", n, useBeanAttrs, err); String name = n.getTextAttribute("id"); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String className = n.getTextAttribute("class"); String type = n.getTextAttribute("type"); BeanRepository beanInfo = pageInfo.getBeanRepository(); if (className == null && type == null) err.jspError(n, "jsp.error.usebean.missingType"); if (beanInfo.checkVariable(name)) err.jspError(n, "jsp.error.usebean.duplicate"); if ("session".equals(scope) && !pageInfo.isSession()) err.jspError(n, "jsp.error.usebean.noSession"); Node.JspAttribute jattr = getJspAttribute(null, "beanName", null, null, n.getAttributeValue("beanName"), n, false); n.setBeanName(jattr); if (className != null && jattr != null) err.jspError(n, "jsp.error.usebean.notBoth"); if (className == null) className = type; beanInfo.addBean(n, name, className, scope); visitBody(n); } @SuppressWarnings("null") // type can't be null after initial test @Override public void visit(Node.PlugIn n) throws JasperException { JspUtil.checkAttributes("Plugin", n, plugInAttrs, err); throwErrorIfExpression(n, "type", "jsp:plugin"); throwErrorIfExpression(n, "code", "jsp:plugin"); throwErrorIfExpression(n, "codebase", "jsp:plugin"); throwErrorIfExpression(n, "align", "jsp:plugin"); throwErrorIfExpression(n, "archive", "jsp:plugin"); throwErrorIfExpression(n, "hspace", "jsp:plugin"); throwErrorIfExpression(n, "jreversion", "jsp:plugin"); throwErrorIfExpression(n, "name", "jsp:plugin"); throwErrorIfExpression(n, "vspace", "jsp:plugin"); throwErrorIfExpression(n, "nspluginurl", "jsp:plugin"); throwErrorIfExpression(n, "iepluginurl", "jsp:plugin"); String type = n.getTextAttribute("type"); if (type == null) err.jspError(n, "jsp.error.plugin.notype"); if (!type.equals("bean") && !type.equals("applet")) err.jspError(n, "jsp.error.plugin.badtype"); if (n.getTextAttribute("code") == null) err.jspError(n, "jsp.error.plugin.nocode"); Node.JspAttribute width = getJspAttribute(null, "width", null, null, n.getAttributeValue("width"), n, false); n.setWidth(width); Node.JspAttribute height = getJspAttribute(null, "height", null, null, n.getAttributeValue("height"), n, false); n.setHeight(height); visitBody(n); } @Override public void visit(Node.NamedAttribute n) throws JasperException { JspUtil.checkAttributes("Attribute", n, attributeAttrs, err); n.setOmit(getJspAttribute(null, "omit", null, null, n .getAttributeValue("omit"), n, true)); visitBody(n); } @Override public void visit(Node.JspBody n) throws JasperException { visitBody(n); } @Override public void visit(Node.Declaration n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } } @Override public void visit(Node.Expression n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } } @Override public void visit(Node.Scriptlet n) throws JasperException { if (pageInfo.isScriptingInvalid()) { err.jspError(n.getStart(), "jsp.error.no.scriptlets"); } } @Override public void visit(Node.ELExpression n) throws JasperException { // exit if we are ignoring EL all together if (pageInfo.isELIgnored()) return; // JSP.2.2 - '#{' not allowed in template text if (n.getType() == '#') { if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { err.jspError(n, "jsp.error.el.template.deferred"); } else { return; } } // build expression StringBuilder expr = this.getBuffer(); expr.append(n.getType()).append('{').append(n.getText()) .append('}'); ELNode.Nodes el = ELParser.parse(expr.toString(), pageInfo .isDeferredSyntaxAllowedAsLiteral()); // validate/prepare expression prepareExpression(el, n, expr.toString()); // store it n.setEL(el); } @Override public void visit(Node.UninterpretedTag n) throws JasperException { if (n.getNamedAttributeNodes().size() != 0) { err.jspError(n, "jsp.error.namedAttribute.invalidUse"); } Attributes attrs = n.getAttributes(); if (attrs != null) { int attrSize = attrs.getLength(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[attrSize]; for (int i = 0; i < attrSize; i++) { // JSP.2.2 - '#{' not allowed in template text String value = attrs.getValue(i); if (!pageInfo.isDeferredSyntaxAllowedAsLiteral()) { if (containsDeferredSyntax(value)) { err.jspError(n, "jsp.error.el.template.deferred"); } } jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), value, n, false); } n.setJspAttributes(jspAttrs); } visitBody(n); } /* * Look for a #{ sequence that isn't preceded by \. */ private boolean containsDeferredSyntax(String value) { if (value == null) { return false; } int i = 0; int len = value.length(); boolean prevCharIsEscape = false; while (i < value.length()) { char c = value.charAt(i); if (c == '#' && (i+1) < len && value.charAt(i+1) == '{' && !prevCharIsEscape) { return true; } else if (c == '\\') { prevCharIsEscape = true; } else { prevCharIsEscape = false; } i++; } return false; } @SuppressWarnings("null") // tagInfo can't be null after initial test @Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } /* * The bodycontent of a SimpleTag cannot be JSP. */ if (n.implementsSimpleTag() && tagInfo.getBodyContent().equalsIgnoreCase( TagInfo.BODY_CONTENT_JSP)) { err.jspError(n, "jsp.error.simpletag.badbodycontent", tagInfo .getTagClassName()); } /* * If the tag handler declares in the TLD that it supports dynamic * attributes, it also must implement the DynamicAttributes * interface. */ if (tagInfo.hasDynamicAttributes() && !n.implementsDynamicAttributes()) { err.jspError(n, "jsp.error.dynamic.attributes.not.implemented", n.getQName()); } /* * Make sure all required attributes are present, either as * attributes or named attributes (<jsp:attribute>). Also make sure * that the same attribute is not specified in both attributes or * named attributes. */ TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); String customActionUri = n.getURI(); Attributes attrs = n.getAttributes(); int attrsSize = (attrs == null) ? 0 : attrs.getLength(); for (int i = 0; i < tldAttrs.length; i++) { String attr = null; if (attrs != null) { attr = attrs.getValue(tldAttrs[i].getName()); if (attr == null) { attr = attrs.getValue(customActionUri, tldAttrs[i] .getName()); } } Node.NamedAttribute na = n.getNamedAttributeNode(tldAttrs[i] .getName()); if (tldAttrs[i].isRequired() && attr == null && na == null) { err.jspError(n, "jsp.error.missing_attribute", tldAttrs[i] .getName(), n.getLocalName()); } if (attr != null && na != null) { err.jspError(n, "jsp.error.duplicate.name.jspattribute", tldAttrs[i].getName()); } } Node.Nodes naNodes = n.getNamedAttributeNodes(); int jspAttrsSize = naNodes.size() + attrsSize; Node.JspAttribute[] jspAttrs = null; if (jspAttrsSize > 0) { jspAttrs = new Node.JspAttribute[jspAttrsSize]; } Hashtable<String, Object> tagDataAttrs = new Hashtable<>(attrsSize); checkXmlAttributes(n, jspAttrs, tagDataAttrs); checkNamedAttributes(n, jspAttrs, attrsSize, tagDataAttrs); TagData tagData = new TagData(tagDataAttrs); // JSP.C1: It is a (translation time) error for an action that // has one or more variable subelements to have a TagExtraInfo // class that returns a non-null object. TagExtraInfo tei = tagInfo.getTagExtraInfo(); if (tei != null && tei.getVariableInfo(tagData) != null && tei.getVariableInfo(tagData).length > 0 && tagInfo.getTagVariableInfos().length > 0) { err.jspError("jsp.error.non_null_tei_and_var_subelems", n .getQName()); } n.setTagData(tagData); n.setJspAttributes(jspAttrs); visitBody(n); } @Override public void visit(Node.JspElement n) throws JasperException { Attributes attrs = n.getAttributes(); if (attrs == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } @SuppressWarnings("null") // Exception will have been thrown above int xmlAttrLen = attrs.getLength(); Node.Nodes namedAttrs = n.getNamedAttributeNodes(); // XML-style 'name' attribute, which is mandatory, must not be // included in JspAttribute array int jspAttrSize = xmlAttrLen - 1 + namedAttrs.size(); Node.JspAttribute[] jspAttrs = new Node.JspAttribute[jspAttrSize]; int jspAttrIndex = 0; // Process XML-style attributes for (int i = 0; i < xmlAttrLen; i++) { if ("name".equals(attrs.getLocalName(i))) { n.setNameAttribute(getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false)); } else { if (jspAttrIndex < jspAttrSize) { jspAttrs[jspAttrIndex++] = getJspAttribute(null, attrs .getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), n, false); } } } if (n.getNameAttribute() == null) { err.jspError(n, "jsp.error.jspelement.missing.name"); } // Process named attributes for (int i = 0; i < namedAttrs.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) namedAttrs .getNode(i); jspAttrs[jspAttrIndex++] = new Node.JspAttribute(na, null, false); } n.setJspAttributes(jspAttrs); visitBody(n); } @Override public void visit(Node.JspOutput n) throws JasperException { JspUtil.checkAttributes("jsp:output", n, jspOutputAttrs, err); if (n.getBody() != null) { err.jspError(n, "jsp.error.jspoutput.nonemptybody"); } String omitXmlDecl = n.getAttributeValue("omit-xml-declaration"); String doctypeName = n.getAttributeValue("doctype-root-element"); String doctypePublic = n.getAttributeValue("doctype-public"); String doctypeSystem = n.getAttributeValue("doctype-system"); String omitXmlDeclOld = pageInfo.getOmitXmlDecl(); String doctypeNameOld = pageInfo.getDoctypeName(); String doctypePublicOld = pageInfo.getDoctypePublic(); String doctypeSystemOld = pageInfo.getDoctypeSystem(); if (omitXmlDecl != null && omitXmlDeclOld != null && !omitXmlDecl.equals(omitXmlDeclOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "omit-xml-declaration", omitXmlDeclOld, omitXmlDecl); } if (doctypeName != null && doctypeNameOld != null && !doctypeName.equals(doctypeNameOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-root-element", doctypeNameOld, doctypeName); } if (doctypePublic != null && doctypePublicOld != null && !doctypePublic.equals(doctypePublicOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-public", doctypePublicOld, doctypePublic); } if (doctypeSystem != null && doctypeSystemOld != null && !doctypeSystem.equals(doctypeSystemOld)) { err.jspError(n, "jsp.error.jspoutput.conflict", "doctype-system", doctypeSystemOld, doctypeSystem); } if (doctypeName == null && doctypeSystem != null || doctypeName != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypenamesystem"); } if (doctypePublic != null && doctypeSystem == null) { err.jspError(n, "jsp.error.jspoutput.doctypepulicsystem"); } if (omitXmlDecl != null) { pageInfo.setOmitXmlDecl(omitXmlDecl); } if (doctypeName != null) { pageInfo.setDoctypeName(doctypeName); } if (doctypeSystem != null) { pageInfo.setDoctypeSystem(doctypeSystem); } if (doctypePublic != null) { pageInfo.setDoctypePublic(doctypePublic); } } @Override public void visit(Node.InvokeAction n) throws JasperException { JspUtil.checkAttributes("Invoke", n, invokeAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } } @Override public void visit(Node.DoBodyAction n) throws JasperException { JspUtil.checkAttributes("DoBody", n, doBodyAttrs, err); String scope = n.getTextAttribute("scope"); JspUtil.checkScope(scope, n, err); String var = n.getTextAttribute("var"); String varReader = n.getTextAttribute("varReader"); if (scope != null && var == null && varReader == null) { err.jspError(n, "jsp.error.missing_var_or_varReader"); } if (var != null && varReader != null) { err.jspError(n, "jsp.error.var_and_varReader"); } } /* * Make sure the given custom action does not have any invalid * attributes. * * A custom action and its declared attributes always belong to the same * namespace, which is identified by the prefix name of the custom tag * invocation. For example, in this invocation: * * <my:test a="1" b="2" c="3"/>, the action * * "test" and its attributes "a", "b", and "c" all belong to the * namespace identified by the prefix "my". The above invocation would * be equivalent to: * * <my:test my:a="1" my:b="2" my:c="3"/> * * An action attribute may have a prefix different from that of the * action invocation only if the underlying tag handler supports dynamic * attributes, in which case the attribute with the different prefix is * considered a dynamic attribute. */ private void checkXmlAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Attributes attrs = n.getAttributes(); for (int i = 0; attrs != null && i < attrs.getLength(); i++) { boolean found = false; boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("%=")) || (!n.getRoot().isXmlSyntax() && attrs.getValue(i).startsWith("<%="))); boolean elExpression = false; boolean deferred = false; double libraryVersion = Double.parseDouble( tagInfo.getTagLibrary().getRequiredVersion()); boolean deferredSyntaxAllowedAsLiteral = pageInfo.isDeferredSyntaxAllowedAsLiteral() || libraryVersion < 2.1; ELNode.Nodes el = null; if (!runtimeExpression && !pageInfo.isELIgnored()) { el = ELParser.parse(attrs.getValue(i), deferredSyntaxAllowedAsLiteral); Iterator<ELNode> nodes = el.iterator(); while (nodes.hasNext()) { ELNode node = nodes.next(); if (node instanceof ELNode.Root) { if (((ELNode.Root) node).getType() == '$') { if (elExpression && deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; } else if (((ELNode.Root) node).getType() == '#') { if (elExpression && !deferred) { err.jspError(n, "jsp.error.attribute.deferredmix"); } elExpression = true; deferred = true; } } } } boolean expression = runtimeExpression || elExpression; for (int j = 0; tldAttrs != null && j < tldAttrs.length; j++) { if (attrs.getLocalName(i).equals(tldAttrs[j].getName()) && (attrs.getURI(i) == null || attrs.getURI(i).length() == 0 || attrs .getURI(i).equals(n.getURI()))) { TagAttributeInfo tldAttr = tldAttrs[j]; if (tldAttr.canBeRequestTime() || tldAttr.isDeferredMethod() || tldAttr.isDeferredValue()) { // JSP 2.1 if (!expression) { String expectedType = null; if (tldAttr.isDeferredMethod()) { // The String literal must be castable to what is declared as type // for the attribute String m = tldAttr.getMethodSignature(); if (m != null) { m = m.trim(); int rti = m.indexOf(' '); if (rti > 0) { expectedType = m.substring(0, rti).trim(); } } else { expectedType = "java.lang.Object"; } if ("void".equals(expectedType)) { // Can't specify a literal for a // deferred method with an expected type // of void - JSP.2.3.4 err.jspError(n, "jsp.error.literal_with_void", tldAttr.getName()); } } if (tldAttr.isDeferredValue()) { // The String literal must be castable to what is declared as type // for the attribute expectedType = tldAttr.getExpectedTypeName(); } if (expectedType != null) { Class<?> expectedClass = String.class; try { expectedClass = JspUtil.toClass(expectedType, loader); } catch (ClassNotFoundException e) { err.jspError (n, "jsp.error.unknown_attribute_type", tldAttr.getName(), expectedType); } // Check casting - not possible for all types if (String.class.equals(expectedClass) || expectedClass == Long.TYPE || expectedClass == Double.TYPE || expectedClass == Byte.TYPE || expectedClass == Short.TYPE || expectedClass == Integer.TYPE || expectedClass == Float.TYPE || Number.class.isAssignableFrom(expectedClass) || Character.class.equals(expectedClass) || Character.TYPE == expectedClass || Boolean.class.equals(expectedClass) || Boolean.TYPE == expectedClass || expectedClass.isEnum()) { try { expressionFactory.coerceToType(attrs.getValue(i), expectedClass); } catch (Exception e) { err.jspError (n, "jsp.error.coerce_to_type", tldAttr.getName(), expectedType, attrs.getValue(i)); } } } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } else { if (deferred && !tldAttr.isDeferredMethod() && !tldAttr.isDeferredValue()) { // No deferred expressions allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (!deferred && !tldAttr.canBeRequestTime()) { // Only deferred expressions are allowed for this attribute err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } if (elExpression) { // El expression validateFunctions(el, n); jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs.getValue(i), false, el, false); ELContextImpl ctx = new ELContextImpl( expressionFactory); ctx.setFunctionMapper(getFunctionMapper(el)); try { jspAttrs[i].validateEL(this.pageInfo.getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", attrs.getValue(i), e.toString()); } } else { // Runtime expression jspAttrs[i] = getJspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, false); } } } else { // Attribute does not accept any expressions. // Make sure its value does not contain any. if (expression) { err.jspError(n, "jsp.error.attribute.custom.non_rt_with_expr", tldAttr.getName()); } jspAttrs[i] = new Node.JspAttribute(tldAttr, attrs.getQName(i), attrs.getURI(i), attrs .getLocalName(i), attrs.getValue(i), false, null, false); } if (expression) { tagDataAttrs.put(attrs.getQName(i), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(attrs.getQName(i), attrs .getValue(i)); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[i] = getJspAttribute(null, attrs.getQName(i), attrs.getURI(i), attrs.getLocalName(i), attrs .getValue(i), n, true); } else { err.jspError(n, "jsp.error.bad_attribute", attrs .getQName(i), n.getLocalName()); } } } } /* * Make sure the given custom action does not have any invalid named * attributes */ private void checkNamedAttributes(Node.CustomTag n, Node.JspAttribute[] jspAttrs, int start, Hashtable<String, Object> tagDataAttrs) throws JasperException { TagInfo tagInfo = n.getTagInfo(); TagAttributeInfo[] tldAttrs = tagInfo.getAttributes(); Node.Nodes naNodes = n.getNamedAttributeNodes(); for (int i = 0; i < naNodes.size(); i++) { Node.NamedAttribute na = (Node.NamedAttribute) naNodes .getNode(i); boolean found = false; for (int j = 0; j < tldAttrs.length; j++) { /* * See above comment about namespace matches. For named * attributes, we use the prefix instead of URI as the match * criterion, because in the case of a JSP document, we'd * have to keep track of which namespaces are in scope when * parsing a named attribute, in order to determine the URI * that the prefix of the named attribute's name matches to. */ String attrPrefix = na.getPrefix(); if (na.getLocalName().equals(tldAttrs[j].getName()) && (attrPrefix == null || attrPrefix.length() == 0 || attrPrefix .equals(n.getPrefix()))) { jspAttrs[start + i] = new Node.JspAttribute(na, tldAttrs[j], false); NamedAttributeVisitor nav = null; if (na.getBody() != null) { nav = new NamedAttributeVisitor(); na.getBody().visit(nav); } if (nav != null && nav.hasDynamicContent()) { tagDataAttrs.put(na.getName(), TagData.REQUEST_TIME_VALUE); } else { tagDataAttrs.put(na.getName(), na.getText()); } found = true; break; } } if (!found) { if (tagInfo.hasDynamicAttributes()) { jspAttrs[start + i] = new Node.JspAttribute(na, null, true); } else { err.jspError(n, "jsp.error.bad_attribute", na.getName(), n.getLocalName()); } } } } /** * Preprocess attributes that can be expressions. Expression delimiters * are stripped. * <p> * If value is null, checks if there are any NamedAttribute subelements * in the tree node, and if so, constructs a JspAttribute out of a child * NamedAttribute node. */ private Node.JspAttribute getJspAttribute(TagAttributeInfo tai, String qName, String uri, String localName, String value, Node n, boolean dynamic) throws JasperException { Node.JspAttribute result = null; // XXX Is it an error to see "%=foo%" in non-Xml page? // (We won't see "<%=foo%> in xml page because '<' is not a // valid attribute value in xml). if (value != null) { if (n.getRoot().isXmlSyntax() && value.startsWith("%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(2, value.length() - 1), true, null, dynamic); } else if (!n.getRoot().isXmlSyntax() && value.startsWith("<%=")) { result = new Node.JspAttribute(tai, qName, uri, localName, value.substring(3, value.length() - 2), true, null, dynamic); } else if (pageInfo.isELIgnored()) { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } else { // The attribute can contain expressions but is not a // scriptlet expression; thus, we want to run it through // the expression interpreter // validate expression syntax if string contains // expression(s) ELNode.Nodes el = ELParser.parse(value, pageInfo .isDeferredSyntaxAllowedAsLiteral()); if (el.containsEL()) { validateFunctions(el, n); if (n.getRoot().isXmlSyntax()) { // The non-EL elements need to be XML escaped XmlEscapeNonELVisitor v = new XmlEscapeNonELVisitor(); el.visit(v); result = new Node.JspAttribute(tai, qName, uri, localName, v.getText(), false, el, dynamic); } else { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, el, dynamic); } ELContextImpl ctx = new ELContextImpl(expressionFactory); ctx.setFunctionMapper(getFunctionMapper(el)); try { result.validateEL(this.pageInfo .getExpressionFactory(), ctx); } catch (ELException e) { this.err.jspError(n.getStart(), "jsp.error.invalid.expression", value, e .toString()); } } else { result = new Node.JspAttribute(tai, qName, uri, localName, value, false, null, dynamic); } } } else { // Value is null. Check for any NamedAttribute subnodes // that might contain the value for this attribute. // Otherwise, the attribute wasn't found so we return null. Node.NamedAttribute namedAttributeNode = n .getNamedAttributeNode(qName); if (namedAttributeNode != null) { result = new Node.JspAttribute(namedAttributeNode, tai, dynamic); } } return result; } private static class XmlEscapeNonELVisitor extends ELParser.TextBuilder { @Override public void visit(Text n) throws JasperException { output.append(xmlEscape(n.getText())); } } /* * Return an empty StringBuilder [not thread-safe] */ private StringBuilder getBuffer() { this.buf.setLength(0); return this.buf; } /* * Checks to see if the given attribute value represents a runtime or EL * expression. */ private boolean isExpression(Node n, String value, boolean checkDeferred) { boolean runtimeExpression = ((n.getRoot().isXmlSyntax() && value.startsWith("%=")) || (!n.getRoot().isXmlSyntax() && value.startsWith("<%="))); boolean elExpression = false; if (!runtimeExpression && !pageInfo.isELIgnored()) { Iterator<ELNode> nodes = ELParser.parse(value, pageInfo.isDeferredSyntaxAllowedAsLiteral()).iterator(); while (nodes.hasNext()) { ELNode node = nodes.next(); if (node instanceof ELNode.Root) { if (((ELNode.Root) node).getType() == '$') { elExpression = true; break; } else if (checkDeferred && !pageInfo.isDeferredSyntaxAllowedAsLiteral() && ((ELNode.Root) node).getType() == '#') { elExpression = true; break; } } } } return runtimeExpression || elExpression; } /* * Throws exception if the value of the attribute with the given name in * the given node is given as an RT or EL expression, but the spec * requires a static value. */ private void throwErrorIfExpression(Node n, String attrName, String actionName) throws JasperException { if (n.getAttributes() != null && n.getAttributes().getValue(attrName) != null && isExpression(n, n.getAttributes().getValue(attrName), true)) { err.jspError(n, "jsp.error.attribute.standard.non_rt_with_expr", attrName, actionName); } } private static class NamedAttributeVisitor extends Node.Visitor { private boolean hasDynamicContent; @Override public void doVisit(Node n) throws JasperException { if (!(n instanceof Node.JspText) && !(n instanceof Node.TemplateText)) { hasDynamicContent = true; } visitBody(n); } public boolean hasDynamicContent() { return hasDynamicContent; } } private String findUri(String prefix, Node n) { for (Node p = n; p != null; p = p.getParent()) { Attributes attrs = p.getTaglibAttributes(); if (attrs == null) { continue; } for (int i = 0; i < attrs.getLength(); i++) { String name = attrs.getQName(i); int k = name.indexOf(':'); if (prefix == null && k < 0) { // prefix not specified and a default ns found return attrs.getValue(i); } if (prefix != null && k >= 0 && prefix.equals(name.substring(k + 1))) { return attrs.getValue(i); } } } return null; } /** * Validate functions in EL expressions */ private void validateFunctions(ELNode.Nodes el, Node n) throws JasperException { class FVVisitor extends ELNode.Visitor { private Node n; FVVisitor(Node n) { this.n = n; } @Override public void visit(ELNode.Function func) throws JasperException { String prefix = func.getPrefix(); String function = func.getName(); String uri = null; if (n.getRoot().isXmlSyntax()) { uri = findUri(prefix, n); } else if (prefix != null) { uri = pageInfo.getURI(prefix); } if (uri == null) { if (prefix == null) { err.jspError(n, "jsp.error.noFunctionPrefix", function); } else { err.jspError(n, "jsp.error.attribute.invalidPrefix", prefix); } } TagLibraryInfo taglib = pageInfo.getTaglib(uri); FunctionInfo funcInfo = null; if (taglib != null) { funcInfo = taglib.getFunction(function); } if (funcInfo == null) { err.jspError(n, "jsp.error.noFunction", function); } // Skip TLD function uniqueness check. Done by Schema ? func.setUri(uri); func.setFunctionInfo(funcInfo); processSignature(func); } } el.visit(new FVVisitor(n)); } private void prepareExpression(ELNode.Nodes el, Node n, String expr) throws JasperException { validateFunctions(el, n); // test it out ELContextImpl ctx = new ELContextImpl(expressionFactory); ctx.setFunctionMapper(this.getFunctionMapper(el)); ExpressionFactory ef = this.pageInfo.getExpressionFactory(); try { ef.createValueExpression(ctx, expr, Object.class); } catch (ELException e) { } } private void processSignature(ELNode.Function func) throws JasperException { func.setMethodName(getMethod(func)); func.setParameters(getParameters(func)); } /** * Get the method name from the signature. */ private String getMethod(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); int start = signature.indexOf(' '); if (start < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } int end = signature.indexOf('('); if (end < 0) { err.jspError( "jsp.error.tld.fn.invalid.signature.parenexpected", func.getPrefix(), func.getName()); } return signature.substring(start + 1, end).trim(); } /** * Get the parameters types from the function signature. * * @return An array of parameter class names */ private String[] getParameters(ELNode.Function func) throws JasperException { FunctionInfo funcInfo = func.getFunctionInfo(); String signature = funcInfo.getFunctionSignature(); ArrayList<String> params = new ArrayList<>(); // Signature is of the form // <return-type> S <method-name S? '(' // < <arg-type> ( ',' <arg-type> )* )? ')' int start = signature.indexOf('(') + 1; boolean lastArg = false; while (true) { int p = signature.indexOf(',', start); if (p < 0) { p = signature.indexOf(')', start); if (p < 0) { err.jspError("jsp.error.tld.fn.invalid.signature", func .getPrefix(), func.getName()); } lastArg = true; } String arg = signature.substring(start, p).trim(); if (!"".equals(arg)) { params.add(arg); } if (lastArg) { break; } start = p + 1; } return params.toArray(new String[params.size()]); } private FunctionMapper getFunctionMapper(ELNode.Nodes el) throws JasperException { class ValidateFunctionMapper extends FunctionMapper { private HashMap<String, Method> fnmap = new HashMap<>(); @Override public void mapFunction(String prefix, String localName, Method method) { fnmap.put(prefix + ":" + localName, method); } @Override public Method resolveFunction(String prefix, String localName) { return this.fnmap.get(prefix + ":" + localName); } } class MapperELVisitor extends ELNode.Visitor { private ValidateFunctionMapper fmapper; MapperELVisitor(ValidateFunctionMapper fmapper) { this.fmapper = fmapper; } @SuppressWarnings("null") // c can't be null after catch block @Override public void visit(ELNode.Function n) throws JasperException { Class<?> c = null; Method method = null; try { c = loader.loadClass(n.getFunctionInfo() .getFunctionClass()); } catch (ClassNotFoundException e) { err.jspError("jsp.error.function.classnotfound", n .getFunctionInfo().getFunctionClass(), n .getPrefix() + ':' + n.getName(), e.getMessage()); } String paramTypes[] = n.getParameters(); int size = paramTypes.length; Class<?> params[] = new Class[size]; int i = 0; try { for (i = 0; i < size; i++) { params[i] = JspUtil.toClass(paramTypes[i], loader); } method = c.getDeclaredMethod(n.getMethodName(), params); } catch (ClassNotFoundException e) { err.jspError("jsp.error.signature.classnotfound", paramTypes[i], n.getPrefix() + ':' + n.getName(), e.getMessage()); } catch (NoSuchMethodException e) { err.jspError("jsp.error.noFunctionMethod", n .getMethodName(), n.getName(), c.getName()); } fmapper.mapFunction(n.getPrefix(), n.getName(), method); } } ValidateFunctionMapper fmapper = new ValidateFunctionMapper(); el.visit(new MapperELVisitor(fmapper)); return fmapper; } } // End of ValidateVisitor /** * A visitor for validating TagExtraInfo classes of all tags */ private static class TagExtraInfoVisitor extends Node.Visitor { private final ErrorDispatcher err; /* * Constructor */ TagExtraInfoVisitor(Compiler compiler) { this.err = compiler.getErrorDispatcher(); } @Override public void visit(Node.CustomTag n) throws JasperException { TagInfo tagInfo = n.getTagInfo(); if (tagInfo == null) { err.jspError(n, "jsp.error.missing.tagInfo", n.getQName()); } @SuppressWarnings("null") // tagInfo can't be null here ValidationMessage[] errors = tagInfo.validate(n.getTagData()); if (errors != null && errors.length != 0) { StringBuilder errMsg = new StringBuilder(); errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tei.invalid.attributes", n.getQName())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { errMsg.append("<p>"); if (errors[i].getId() != null) { errMsg.append(errors[i].getId()); errMsg.append(": "); } errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } err.jspError(n, errMsg.toString()); } visitBody(n); } } public static void validateDirectives(Compiler compiler, Node.Nodes page) throws JasperException { page.visit(new DirectiveVisitor(compiler)); } public static void validateExDirectives(Compiler compiler, Node.Nodes page) throws JasperException { // Determine the default output content type PageInfo pageInfo = compiler.getPageInfo(); String contentType = pageInfo.getContentType(); if (contentType == null || contentType.indexOf("charset=") < 0) { boolean isXml = page.getRoot().isXmlSyntax(); String defaultType; if (contentType == null) { defaultType = isXml ? "text/xml" : "text/html"; } else { defaultType = contentType; } String charset = null; if (isXml) { charset = "UTF-8"; } else { if (!page.getRoot().isDefaultPageEncoding()) { charset = page.getRoot().getPageEncoding(); } } if (charset != null) { pageInfo.setContentType(defaultType + ";charset=" + charset); } else { pageInfo.setContentType(defaultType); } } /* * Validate all other nodes. This validation step includes checking a * custom tag's mandatory and optional attributes against information in * the TLD (first validation step for custom tags according to * JSP.10.5). */ page.visit(new ValidateVisitor(compiler)); /* * Invoke TagLibraryValidator classes of all imported tags (second * validation step for custom tags according to JSP.10.5). */ validateXmlView(new PageDataImpl(page, compiler), compiler); /* * Invoke TagExtraInfo method isValid() for all imported tags (third * validation step for custom tags according to JSP.10.5). */ page.visit(new TagExtraInfoVisitor(compiler)); } // ********************************************************************* // Private (utility) methods /** * Validate XML view against the TagLibraryValidator classes of all imported * tag libraries. */ private static void validateXmlView(PageData xmlView, Compiler compiler) throws JasperException { StringBuilder errMsg = null; ErrorDispatcher errDisp = compiler.getErrorDispatcher(); for (Iterator<TagLibraryInfo> iter = compiler.getPageInfo().getTaglibs().iterator(); iter.hasNext();) { Object o = iter.next(); if (!(o instanceof TagLibraryInfoImpl)) continue; TagLibraryInfoImpl tli = (TagLibraryInfoImpl) o; ValidationMessage[] errors = tli.validate(xmlView); if ((errors != null) && (errors.length != 0)) { if (errMsg == null) { errMsg = new StringBuilder(); } errMsg.append("<h3>"); errMsg.append(Localizer.getMessage( "jsp.error.tlv.invalid.page", tli.getShortName(), compiler.getPageInfo().getJspFile())); errMsg.append("</h3>"); for (int i = 0; i < errors.length; i++) { if (errors[i] != null) { errMsg.append("<p>"); errMsg.append(errors[i].getId()); errMsg.append(": "); errMsg.append(errors[i].getMessage()); errMsg.append("</p>"); } } } } if (errMsg != null) { errDisp.jspError(errMsg.toString()); } } protected static String xmlEscape(String s) { if (s == null) { return null; } int len = s.length(); /* * Look for any "bad" characters, Escape "bad" character was found */ // ASCII " 34 & 38 ' 39 < 60 > 62 for (int i = 0; i < len; i++) { char c = s.charAt(i); if (c >= '\"' && c <= '>' && (c == '<' || c == '>' || c == '\'' || c == '&' || c == '"')) { // need to escape them and then quote the whole string StringBuilder sb = new StringBuilder((int) (len * 1.2)); sb.append(s, 0, i); int pos = i + 1; for (int j = i; j < len; j++) { c = s.charAt(j); if (c >= '\"' && c <= '>') { if (c == '<') { if (j > pos) { sb.append(s, pos, j); } sb.append("&lt;"); pos = j + 1; } else if (c == '>') { if (j > pos) { sb.append(s, pos, j); } sb.append("&gt;"); pos = j + 1; } else if (c == '\'') { if (j > pos) { sb.append(s, pos, j); } sb.append("&#039;"); // &apos; pos = j + 1; } else if (c == '&') { if (j > pos) { sb.append(s, pos, j); } sb.append("&amp;"); pos = j + 1; } else if (c == '"') { if (j > pos) { sb.append(s, pos, j); } sb.append("&#034;"); // &quot; pos = j + 1; } } } if (pos < len) { sb.append(s, pos, len); } return sb.toString(); } } return s; } }
28,974
Bug 28974 Compiler error when introducing a "final" field
The aspect below fails to compile with 1.1b2, producing the compilation error: -------------------- $ ajc com/ibm/amc/*.java com/ibm/amc/ejb/*.java d:/eclipse/runtime-workspace-ajsamples/Mock EJBs/com/ibm/amc/DemoBeanEJB.java:1: Cannot assign a value to the final field com.ibm.amc.DemoBean.ajc$interField$co m_ibm_amc$verbose !! no source information available !! 1 error --------------------------- package com.ibm.amc; import com.ibm.amc.ejb.SessionBean; /** * @author colyer * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public aspect DemoBeanEJB { declare parents: DemoBean implements SessionBean; // THIS NEXT LINE IS THE CULPRIT static final boolean DemoBean.verbose = true; private transient String DemoBean.ctx; public void DemoBean.ejbActivate( ) { if ( verbose ) { System.out.println( "ejbActivate Called" ); } } } ------------------- Making the inter-type declaration non-final solves the problem...
resolved fixed
99a873c
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T19:31:02Z
2003-01-03T16:06:40Z
weaver/src/org/aspectj/weaver/AjcMemberMaker.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; public class AjcMemberMaker { private static final int PUBLIC_STATIC_FINAL = Modifier.PUBLIC | Modifier.STATIC | Modifier.FINAL; private static final int PRIVATE_STATIC = Modifier.PRIVATE | Modifier.STATIC; private static final int PUBLIC_STATIC = Modifier.PUBLIC | Modifier.STATIC; private static final int VISIBILITY = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; public static final TypeX CFLOW_STACK_TYPE = TypeX.forName(NameMangler.CFLOW_STACK_TYPE); public static final TypeX AROUND_CLOSURE_TYPE = TypeX.forName("org.aspectj.runtime.internal.AroundClosure"); public static final TypeX CONVERSIONS_TYPE = TypeX.forName("org.aspectj.runtime.internal.Conversions"); public static final TypeX NO_ASPECT_BOUND_EXCEPTION = TypeX.forName("org.aspectj.lang.NoAspectBoundException"); public static ResolvedMember ajcClinitMethod(TypeX declaringType) { return new ResolvedMember( Member.METHOD, declaringType, PRIVATE_STATIC, NameMangler.AJC_CLINIT_NAME, "()V"); } public static Member noAspectBoundExceptionInit() { return new ResolvedMember( Member.METHOD, NO_ASPECT_BOUND_EXCEPTION, Modifier.PUBLIC, "<init>", "()V"); } public static ResolvedMember perCflowPush(TypeX declaringType) { return new ResolvedMember( Member.METHOD, declaringType, PUBLIC_STATIC, NameMangler.PERCFLOW_PUSH_METHOD, "()V"); } public static ResolvedMember perCflowField(TypeX declaringType) { return new ResolvedMember( Member.FIELD, declaringType, PUBLIC_STATIC_FINAL, NameMangler.PERCFLOW_FIELD_NAME, CFLOW_STACK_TYPE.getSignature()); } public static ResolvedMember perSingletonField(TypeX declaringType) { return new ResolvedMember( Member.FIELD, declaringType, PUBLIC_STATIC_FINAL, NameMangler.PERSINGLETON_FIELD_NAME, declaringType.getSignature()); } public static ResolvedMember perObjectField(TypeX declaringType, ResolvedTypeX aspectType) { int modifiers = Modifier.PRIVATE; if (!TypeX.SERIALIZABLE.isAssignableFrom(aspectType, aspectType.getWorld())) { modifiers |= Modifier.TRANSIENT; } return new ResolvedMember( Member.FIELD, declaringType, modifiers, aspectType, NameMangler.perObjectInterfaceField(aspectType), TypeX.NONE); } public static ResolvedMember perObjectBind(TypeX declaringType) { return new ResolvedMember( Member.METHOD, declaringType, PUBLIC_STATIC, NameMangler.PEROBJECT_BIND_METHOD, "(Ljava/lang/Object;)V"); } public static TypeX perObjectInterfaceType(TypeX aspectType) { return TypeX.forName(aspectType.getName()+"$ajcMightHaveAspect"); } public static ResolvedMember perObjectInterfaceGet(TypeX aspectType) { return new ResolvedMember( Member.METHOD, perObjectInterfaceType(aspectType), Modifier.PUBLIC | Modifier.ABSTRACT, NameMangler.perObjectInterfaceGet(aspectType), "()" + aspectType.getSignature()); } public static ResolvedMember perObjectInterfaceSet(TypeX aspectType) { return new ResolvedMember( Member.METHOD, perObjectInterfaceType(aspectType), Modifier.PUBLIC | Modifier.ABSTRACT, NameMangler.perObjectInterfaceSet(aspectType), "(" + aspectType.getSignature() + ")V"); } public static ResolvedMember perSingletonAspectOfMethod(TypeX declaringType) { return new ResolvedMember(Member.METHOD, declaringType, PUBLIC_STATIC, "aspectOf", "()" + declaringType.getSignature()); } public static ResolvedMember perSingletonHasAspectMethod(TypeX declaringType) { return new ResolvedMember(Member.METHOD, declaringType, PUBLIC_STATIC, "hasAspect", "()Z"); }; public static ResolvedMember perCflowAspectOfMethod(TypeX declaringType) { return perSingletonAspectOfMethod(declaringType); } public static ResolvedMember perCflowHasAspectMethod(TypeX declaringType) { return perSingletonHasAspectMethod(declaringType); }; public static ResolvedMember perObjectAspectOfMethod(TypeX declaringType) { return new ResolvedMember(Member.METHOD, declaringType, PUBLIC_STATIC, "aspectOf", "(Ljava/lang/Object;)" + declaringType.getSignature()); } public static ResolvedMember perObjectHasAspectMethod(TypeX declaringType) { return new ResolvedMember(Member.METHOD, declaringType, PUBLIC_STATIC, "hasAspect", "(Ljava/lang/Object;)Z"); }; // -- privileged accessors public static ResolvedMember privilegedAccessMethodForMethod(TypeX aspectType, ResolvedMember method) { String sig; sig = method.getSignature(); return new ResolvedMember(Member.METHOD, method.getDeclaringType(), Modifier.PUBLIC | (method.isStatic() ? Modifier.STATIC : 0), NameMangler.privilegedAccessMethodForMethod(method.getName(), method.getDeclaringType(), aspectType), sig); //XXX needs thrown exceptions to be correct } public static ResolvedMember privilegedAccessMethodForFieldGet(TypeX aspectType, Member field) { String sig; if (field.isStatic()) { sig = "()" + field.getReturnType().getSignature(); } else { sig = "(" + field.getDeclaringType().getSignature() + ")" + field.getReturnType().getSignature(); } return new ResolvedMember(Member.METHOD, field.getDeclaringType(), PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0), NameMangler.privilegedAccessMethodForFieldGet(field.getName(), field.getDeclaringType(), aspectType), sig); } public static ResolvedMember privilegedAccessMethodForFieldSet(TypeX aspectType, Member field) { String sig; if (field.isStatic()) { sig = "(" + field.getReturnType().getSignature() + ")V"; } else { sig = "(" + field.getDeclaringType().getSignature() + field.getReturnType().getSignature() + ")V"; } return new ResolvedMember(Member.METHOD, field.getDeclaringType(), PUBLIC_STATIC, //Modifier.PUBLIC | (field.isStatic() ? Modifier.STATIC : 0), NameMangler.privilegedAccessMethodForFieldSet(field.getName(), field.getDeclaringType(), aspectType), sig); } // --- runtimeLibrary api stuff public static Member cflowStackPeekInstance() { return new Member( Member.METHOD, CFLOW_STACK_TYPE, 0, "peekInstance", "()Ljava/lang/Object;"); } public static Member cflowStackPushInstance() { return new Member( Member.METHOD, CFLOW_STACK_TYPE, 0, "pushInstance", "(Ljava/lang/Object;)V"); } public static Member cflowStackIsValid() { return new Member( Member.METHOD, CFLOW_STACK_TYPE, 0, "isValid", "()Z"); } public static Member cflowStackInit() { return new Member( Member.CONSTRUCTOR, CFLOW_STACK_TYPE, 0, "<init>", "()V"); } public static Member aroundClosurePreInitializationField() { return new Member( Member.FIELD, AROUND_CLOSURE_TYPE, 0, "preInitializationState", "[Ljava/lang/Object;"); } public static Member aroundClosurePreInitializationGetter() { return new Member( Member.METHOD, AROUND_CLOSURE_TYPE, 0, "getPreInitializationState", "()[Ljava/lang/Object;"); } public static ResolvedMember preIntroducedConstructor( TypeX aspectType, TypeX targetType, TypeX[] paramTypes) { return new ResolvedMember( Member.METHOD, aspectType, PUBLIC_STATIC_FINAL, TypeX.OBJECTARRAY, NameMangler.preIntroducedConstructor(aspectType, targetType), paramTypes); } public static ResolvedMember postIntroducedConstructor( TypeX aspectType, TypeX targetType, TypeX[] paramTypes) { return new ResolvedMember( Member.METHOD, aspectType, PUBLIC_STATIC_FINAL, ResolvedTypeX.VOID, NameMangler.postIntroducedConstructor(aspectType, targetType), TypeX.insert(targetType, paramTypes)); } public static ResolvedMember interConstructor(ResolvedTypeX targetType, ResolvedMember constructor, TypeX aspectType) { // // ResolvedTypeX targetType, // TypeX[] argTypes, // int modifiers) // { ResolvedMember ret = new ResolvedMember( Member.CONSTRUCTOR, targetType, Modifier.PUBLIC, ResolvedTypeX.VOID, "<init>", constructor.getParameterTypes()); //System.out.println("ret: " + ret + " mods: " + Modifier.toString(modifiers)); if (Modifier.isPublic(constructor.getModifiers())) return ret; int i = 0; while (true) { ret = addCookieTo(ret, aspectType); if (targetType.lookupMemberNoSupers(ret) == null) return ret; } } public static ResolvedMember interFieldInitializer(ResolvedMember field, TypeX aspectType) { return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC, NameMangler.interFieldInitializer(aspectType, field.getDeclaringType(), field.getName()), field.isStatic() ? "()V" : "(" + field.getDeclaringType().getSignature() + ")V" ); } private static int makePublic(int modifiers) { return (modifiers & ~VISIBILITY) | Modifier.PUBLIC; } /** * This static method goes on the aspect that declares the inter-type field */ public static ResolvedMember interFieldSetDispatcher(ResolvedMember field, TypeX aspectType) { return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC, ResolvedTypeX.VOID, NameMangler.interFieldSetDispatcher(aspectType, field.getDeclaringType(), field.getName()), field.isStatic() ? new TypeX[] {field.getReturnType()} : new TypeX[] {field.getDeclaringType(), field.getReturnType()} ); } /** * This static method goes on the aspect that declares the inter-type field */ public static ResolvedMember interFieldGetDispatcher(ResolvedMember field, TypeX aspectType) { return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC, field.getReturnType(), NameMangler.interFieldGetDispatcher(aspectType, field.getDeclaringType(), field.getName()), field.isStatic() ? TypeX.NONE : new TypeX[] {field.getDeclaringType()} ); } // private static int makeFieldModifiers(int declaredModifiers) { // int ret = Modifier.PUBLIC; // if (Modifier.isTransient(declaredModifiers)) ret |= Modifier.TRANSIENT; // if (Modifier.isVolatile(declaredModifiers)) ret |= Modifier.VOLATILE; // return ret; // } /** * This field goes on the class the field * is declared onto */ public static ResolvedMember interFieldClassField(ResolvedMember field, TypeX aspectType) { return new ResolvedMember(Member.FIELD, field.getDeclaringType(), makePublic(field.getModifiers()), field.getReturnType(), NameMangler.interFieldClassField(field.getModifiers(), aspectType, field.getDeclaringType(), field.getName()), TypeX.NONE ); } /** * This field goes on top-most implementers of the interface the field * is declared onto */ public static ResolvedMember interFieldInterfaceField(ResolvedMember field, TypeX onClass, TypeX aspectType) { return new ResolvedMember(Member.FIELD, onClass, makePublic(field.getModifiers()), field.getReturnType(), NameMangler.interFieldInterfaceField(aspectType, field.getDeclaringType(), field.getName()), TypeX.NONE ); } /** * This instance method goes on the interface the field is declared onto * as well as its top-most implementors */ public static ResolvedMember interFieldInterfaceSetter(ResolvedMember field, ResolvedTypeX onType, TypeX aspectType) { int modifiers = Modifier.PUBLIC; if (onType.isInterface()) modifiers |= Modifier.ABSTRACT; return new ResolvedMember(Member.METHOD, onType, modifiers, ResolvedTypeX.VOID, NameMangler.interFieldInterfaceSetter(aspectType, field.getDeclaringType(), field.getName()), new TypeX[] {field.getReturnType()} ); } /** * This instance method goes on the interface the field is declared onto * as well as its top-most implementors */ public static ResolvedMember interFieldInterfaceGetter(ResolvedMember field, ResolvedTypeX onType, TypeX aspectType) { int modifiers = Modifier.PUBLIC; if (onType.isInterface()) modifiers |= Modifier.ABSTRACT; return new ResolvedMember(Member.METHOD, onType, modifiers, field.getReturnType(), NameMangler.interFieldInterfaceGetter(aspectType, field.getDeclaringType(), field.getName()), TypeX.NONE ); } /** * This method goes on the target type of the inter-type method. (and possibly the topmost-implemeters, * if the target type is an interface) */ public static ResolvedMember interMethod(ResolvedMember meth, TypeX aspectType, boolean onInterface) { if (Modifier.isPublic(meth.getModifiers()) && !onInterface) return meth; int modifiers = makePublic(meth.getModifiers()); if (onInterface) modifiers |= Modifier.ABSTRACT; return new ResolvedMember(Member.METHOD, meth.getDeclaringType(), modifiers, meth.getReturnType(), NameMangler.interMethod(meth.getModifiers(), aspectType, meth.getDeclaringType(), meth.getName()), meth.getParameterTypes()); } /** * This static method goes on the declaring aspect of the inter-type method. */ public static ResolvedMember interMethodDispatcher(ResolvedMember meth, TypeX aspectType) { TypeX[] paramTypes = meth.getParameterTypes(); if (!meth.isStatic()) { paramTypes = TypeX.insert(meth.getDeclaringType(), paramTypes); } return new ResolvedMember(Member.METHOD, aspectType, PUBLIC_STATIC, meth.getReturnType(), NameMangler.interMethodDispatcher(aspectType, meth.getDeclaringType(), meth.getName()), paramTypes); } /** * This static method goes on the declaring aspect of the inter-type method. */ public static ResolvedMember interMethodBody(ResolvedMember meth, TypeX aspectType) { TypeX[] paramTypes = meth.getParameterTypes(); if (!meth.isStatic()) { paramTypes = TypeX.insert(meth.getDeclaringType(), paramTypes); } int modifiers = PUBLIC_STATIC; if (Modifier.isStrict(meth.getModifiers())) { modifiers |= Modifier.STRICT; } return new ResolvedMember(Member.METHOD, aspectType, modifiers, meth.getReturnType(), NameMangler.interMethodBody(aspectType, meth.getDeclaringType(), meth.getName()), paramTypes); } private static ResolvedMember addCookieTo(ResolvedMember ret, TypeX aspectType) { TypeX[] params = ret.getParameterTypes(); TypeX[] freshParams = TypeX.add(params, aspectType); return new ResolvedMember( ret.getKind(), ret.getDeclaringType(), ret.getModifiers(), ret.getReturnType(), ret.getName(), freshParams); } public static ResolvedMember toObjectConversionMethod(TypeX fromType) { if (fromType.isPrimitive()) { String name = fromType.toString() + "Object"; return new ResolvedMember( Member.METHOD, CONVERSIONS_TYPE, PUBLIC_STATIC, TypeX.OBJECT, name, new TypeX[] { fromType }); } else { return null; } } public static Member interfaceConstructor(ResolvedTypeX resolvedTypeX) { return new ResolvedMember( Member.CONSTRUCTOR, resolvedTypeX, Modifier.PUBLIC, "<init>", "()V"); } }
28,919
Bug 28919 waever tries to weave into native methods ...
If you don't find the exception below in a bug, please add a new bug To make the bug a priority, please include a test program that can reproduce this exception. bad non-abstract method with no code: private native int nativeMessagePumpInitialize() on public class plc.comm.pvi.PviCom$LinkEventHandlerImpl bad non-abstract method with no code: private native int nativeMessagePumpInitialize() on public class plc.comm.pvi.PviCom$LinkEventHandlerImpl java.lang.RuntimeException: bad non-abstract method with no code: private native int nativeMessagePumpInitialize() on public class plc.comm.pvi.PviCom$LinkEventHandlerImpl at org.aspectj.weaver.bcel.LazyMethodGen.<init>(Unknown Source) at org.aspectj.weaver.bcel.LazyClassGen.<init>(Unknown Source) at org.aspectj.weaver.bcel.BcelObjectType.getLazyClassGen(Unknown Source) at org.aspectj.weaver.bcel.BcelWeaver.weave(Unknown Source) at org.aspectj.weaver.bcel.BcelWeaver.weave(Unknown Source) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.weaveAndGenerateClassFiles (Unknown Source) at org.aspectj.ajdt.internal.core.builder.AjBuildManager.batchBuild (Unknown Source) at org.aspectj.ajdt.ajc.AjdtCommand.runCommand(Unknown Source) at org.aspectj.tools.ajc.Main.run(Unknown Source) at org.aspectj.tools.ajc.Main.runMain(Unknown Source) at org.aspectj.tools.ajc.Main.main(Unknown Source)
resolved fixed
2781720
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T20:02:43Z
2002-12-30T20:26:40Z
weaver/src/org/aspectj/weaver/bcel/LazyMethodGen.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.*; import java.lang.reflect.Modifier; import java.util.*; import org.apache.bcel.Constants; import org.apache.bcel.classfile.*; import org.apache.bcel.generic.*; import org.aspectj.weaver.*; /** * A LazyMethodGen should be treated as a MethodGen. It's our way of abstracting over the * low-level Method objects. It converts through {@link MethodGen} to create * and to serialize, but that's it. * * <p> At any rate, there are two ways to create LazyMethodGens. * One is from a method, which * does work through MethodGen to do the correct thing. * The other is the creation of a completely empty * LazyMethodGen, and it is used when we're constructing code from scratch. * * <p> We stay away from targeters for rangey things like Shadows and Exceptions. */ public final class LazyMethodGen { private int accessFlags; private final Type returnType; private final String name; private final Type[] argumentTypes; //private final String[] argumentNames; private final String[] declaredExceptions; private final InstructionList body; // leaving null for abstracts private final Attribute[] attributes; private final LazyClassGen enclosingClass; private final BcelMethod memberView; private int maxLocals; private boolean canInline = true; /** * only used by {@link BcelClassWeaver} */ List /*ShadowMungers*/ matchedShadows; // Used for interface introduction // this is the type of the interface the method is technically on public ResolvedTypeX definingType = null; public LazyMethodGen( int accessFlags, Type returnType, String name, Type[] paramTypes, String[] declaredExceptions, LazyClassGen enclosingClass) { this.memberView = null; // ??? should be okay, since constructed ones aren't woven into this.accessFlags = accessFlags; this.returnType = returnType; this.name = name; this.argumentTypes = paramTypes; //this.argumentNames = Utility.makeArgNames(paramTypes.length); this.declaredExceptions = declaredExceptions; if (!Modifier.isAbstract(accessFlags)) { body = new InstructionList(); setMaxLocals(calculateMaxLocals()); } else { body = null; } this.attributes = new Attribute[0]; this.enclosingClass = enclosingClass; assertGoodBody(); } private int calculateMaxLocals() { int ret = 0; if (!Modifier.isStatic(accessFlags)) ret++; for (int i = 0, len = argumentTypes.length; i < len; i++) { ret += argumentTypes[i].getSize(); } return ret; } // build from an existing method public LazyMethodGen(Method m, LazyClassGen enclosingClass) { this.enclosingClass = enclosingClass; if (!m.isAbstract() && m.getCode() == null) { throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass); } MethodGen gen = new MethodGen(m, enclosingClass.getName(), enclosingClass.getConstantPoolGen()); this.memberView = new BcelMethod(enclosingClass.getType(), m); this.accessFlags = gen.getAccessFlags(); this.returnType = gen.getReturnType(); this.name = gen.getName(); this.argumentTypes = gen.getArgumentTypes(); //this.argumentNames = gen.getArgumentNames(); this.declaredExceptions = gen.getExceptions(); this.attributes = gen.getAttributes(); this.maxLocals = gen.getMaxLocals(); if (gen.isAbstract() || gen.isNative()) { body = null; } else { body = gen.getInstructionList(); unpackHandlers(gen); unpackLineNumbers(gen); unpackLocals(gen); } assertGoodBody(); } // XXX we're relying on the javac promise I've just made up that we won't have an early exception // in the list mask a later exception: That is, for two exceptions E and F, // if E preceeds F, then either E \cup F = {}, or E \nonstrictsubset F. So when we add F, // we add it on the _OUTSIDE_ of any handlers that share starts or ends with it. // with that in mind, we merrily go adding ranges for exceptions. private void unpackHandlers(MethodGen gen) { CodeExceptionGen[] exns = gen.getExceptionHandlers(); if (exns != null) { int len = exns.length; int priority = len - 1; for (int i = 0; i < len; i++, priority--) { CodeExceptionGen exn = exns[i]; InstructionHandle start = Range.genStart( body, getOutermostExceptionStart(exn.getStartPC())); InstructionHandle end = Range.genEnd(body, getOutermostExceptionEnd(exn.getEndPC())); // this doesn't necessarily handle overlapping correctly!!! ExceptionRange er = new ExceptionRange( body, exn.getCatchType() == null ? null : BcelWorld.fromBcel(exn.getCatchType()), priority); er.associateWithTargets(start, end, exn.getHandlerPC()); exn.setStartPC(null); // also removes from target exn.setEndPC(null); // also removes from target exn.setHandlerPC(null); // also removes from target } gen.removeExceptionHandlers(); } } private InstructionHandle getOutermostExceptionStart(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionStart(ih.getPrev())) { ih = ih.getPrev(); } else { return ih; } } } private InstructionHandle getOutermostExceptionEnd(InstructionHandle ih) { while (true) { if (ExceptionRange.isExceptionEnd(ih.getNext())) { ih = ih.getNext(); } else { return ih; } } } private void unpackLineNumbers(MethodGen gen) { LineNumberTag lr = null; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LineNumberGen) { LineNumberGen lng = (LineNumberGen) targeter; lng.updateTarget(ih, null); lr = new LineNumberTag(lng.getSourceLine()); } } } if (lr != null) { ih.addTargeter(lr); } } gen.removeLineNumbers(); } private void unpackLocals(MethodGen gen) { Set locals = new HashSet(); for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); List ends = new ArrayList(0); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter targeter = targeters[i]; if (targeter instanceof LocalVariableGen) { LocalVariableGen lng = (LocalVariableGen) targeter; LocalVariableTag lr = new LocalVariableTag(BcelWorld.fromBcel(lng.getType()), lng.getName(), lng.getIndex()); if (lng.getStart() == ih) { lng.setStart(null); locals.add(lr); } else { lng.setEnd(null); ends.add(lr); } } } } for (Iterator i = locals.iterator(); i.hasNext(); ) { ih.addTargeter((LocalVariableTag) i.next()); } locals.removeAll(ends); } gen.removeLocalVariables(); } // =============== public int allocateLocal(Type type) { return allocateLocal(type.getSize()); } public int allocateLocal(int slots) { int max = getMaxLocals(); setMaxLocals(max + slots); return max; } public Method getMethod() { MethodGen gen = pack(); return gen.getMethod(); } // ============================= public String toString() { return toLongString(); } public String toShortString() { org.apache.bcel.classfile.Utility util = null; // EVIL! String access = util.accessToString(getAccessFlags()); StringBuffer buf = new StringBuffer(); if (!access.equals("")) { buf.append(access); buf.append(" "); } buf.append(util.signatureToString(getReturnType().getSignature(), true)); buf.append(" "); buf.append(getName()); buf.append("("); { int len = argumentTypes.length; if (len > 0) { buf.append(util.signatureToString(argumentTypes[0].getSignature(), true)); for (int i = 1; i < argumentTypes.length; i++) { buf.append(", "); buf.append(util.signatureToString(argumentTypes[i].getSignature(), true)); } } } buf.append(")"); { int len = declaredExceptions != null ? declaredExceptions.length : 0; if (len > 0) { buf.append(" throws "); buf.append(declaredExceptions[0]); for (int i = 1; i < declaredExceptions.length; i++) { buf.append(", "); buf.append(declaredExceptions[i]); } } } return buf.toString(); } public String toLongString() { ByteArrayOutputStream s = new ByteArrayOutputStream(); print(new PrintStream(s)); return new String(s.toByteArray()); } public void print() { print(System.out); } public void print(PrintStream out) { out.print(" " + toShortString()); printAspectAttributes(out); InstructionList body = getBody(); if (body == null) { out.println(";"); return; } out.println(":"); new BodyPrinter(out).run(); out.println(" end " + toShortString()); } private void printAspectAttributes(PrintStream out) { ISourceContext context = null; if (enclosingClass != null && enclosingClass.getType() != null) { context = enclosingClass.getType().getSourceContext(); } List as = BcelAttributes.readAjAttributes(attributes, context); if (! as.isEmpty()) { out.println(" " + as.get(0)); // XXX assuming exactly one attribute, munger... } } private class BodyPrinter { Map prefixMap = new HashMap(); Map suffixMap = new HashMap(); Map labelMap = new HashMap(); InstructionList body; PrintStream out; ConstantPool pool; List ranges; BodyPrinter(PrintStream out) { this.pool = enclosingClass.getConstantPoolGen().getConstantPool(); this.body = getBody(); this.out = out; } void run() { assignLabels(); print(); } // label assignment void assignLabels() { LinkedList exnTable = new LinkedList(); String pendingLabel = null; // boolean hasPendingTargeters = false; int lcounter = 0; for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof ExceptionRange) { // assert isRangeHandle(h); ExceptionRange r = (ExceptionRange) t; if (r.getStart() == ih) { insertHandler(r, exnTable); } } else if (t instanceof BranchInstruction) { if (pendingLabel == null) { pendingLabel = "L" + lcounter++; } } else { // assert isRangeHandle(h) } } } if (pendingLabel != null) { labelMap.put(ih, pendingLabel); if (! Range.isRangeHandle(ih)) { pendingLabel = null; } } } int ecounter = 0; for (Iterator i = exnTable.iterator(); i.hasNext();) { ExceptionRange er = (ExceptionRange) i.next(); String exceptionLabel = "E" + ecounter++; labelMap.put(Range.getRealStart(er.getHandler()), exceptionLabel); labelMap.put(er.getHandler(), exceptionLabel); } } // printing void print() { int depth = 0; int currLine = -1; bodyPrint: for (InstructionHandle ih = body.getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { Range r = Range.getRange(ih); // don't print empty ranges, that is, ranges who contain no actual instructions for (InstructionHandle xx = r.getStart(); Range.isRangeHandle(xx); xx = xx.getNext()) { if (xx == r.getEnd()) continue bodyPrint; } // doesn't handle nested: if (r.getStart().getNext() == r.getEnd()) continue; if (r.getStart() == ih) { printRangeString(r, depth++); } else { if (r.getEnd() != ih) throw new RuntimeException("bad"); printRangeString(r, --depth); } } else { printInstruction(ih, depth); int line = getLineNumber(ih, currLine); if (line != currLine) { currLine = line; out.println(" (line " + line + ")"); } else { out.println(); } } } } void printRangeString(Range r, int depth) { printDepth(depth); out.println(getRangeString(r, labelMap)); } String getRangeString(Range r, Map labelMap) { if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; return er.toString() + " -> " + labelMap.get(er.getHandler()); // // + " PRI " + er.getPriority(); } else { return r.toString(); } } void printDepth(int depth) { pad(BODY_INDENT); while (depth > 0) { out.print("| "); depth--; } } void printLabel(String s, int depth) { int space = Math.max(CODE_INDENT - depth * 2, 0); if (s == null) { pad(space); } else { space = Math.max(space - (s.length() + 2), 0); pad(space); out.print(s); out.print(": "); } } void printInstruction(InstructionHandle h, int depth) { printDepth(depth); printLabel((String) labelMap.get(h), depth); Instruction inst = h.getInstruction(); if (inst instanceof CPInstruction) { CPInstruction cpinst = (CPInstruction) inst; out.print(Constants.OPCODE_NAMES[cpinst.getOpcode()].toUpperCase()); out.print(" "); out.print(pool.constantToString(pool.getConstant(cpinst.getIndex()))); } else if (inst instanceof Select) { Select sinst = (Select) inst; out.println(Constants.OPCODE_NAMES[sinst.getOpcode()].toUpperCase()); int[] matches = sinst.getMatchs(); InstructionHandle[] targets = sinst.getTargets(); InstructionHandle defaultTarget = sinst.getTarget(); for (int i = 0, len = matches.length; i < len; i++) { printDepth(depth); printLabel(null, depth); out.print(" "); out.print(matches[i]); out.print(": \t"); out.println(labelMap.get(targets[i])); } printDepth(depth); printLabel(null, depth); out.print(" "); out.print("default: \t"); out.print(labelMap.get(defaultTarget)); } else if (inst instanceof BranchInstruction) { BranchInstruction brinst = (BranchInstruction) inst; out.print(Constants.OPCODE_NAMES[brinst.getOpcode()].toUpperCase()); out.print(" "); out.print(labelMap.get(brinst.getTarget())); } else if (inst instanceof LocalVariableInstruction) { LocalVariableInstruction lvinst = (LocalVariableInstruction) inst; out.print(inst.toString(false).toUpperCase()); int index = lvinst.getIndex(); LocalVariableTag tag = getLocalVariableTag(h, index); if (tag != null) { out.print(" // "); out.print(tag.getType()); out.print(" "); out.print(tag.getName()); } } else { out.print(inst.toString(false).toUpperCase()); } } static final int BODY_INDENT = 4; static final int CODE_INDENT = 16; void pad(int size) { for (int i = 0; i < size; i++) { out.print(" "); } } } static LocalVariableTag getLocalVariableTag( InstructionHandle ih, int index) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return null; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) t; if (lvt.getSlot() == index) return lvt; } } return null; } static int getLineNumber( InstructionHandle ih, int prevLine) { InstructionTargeter[] targeters = ih.getTargeters(); if (targeters == null) return prevLine; for (int i = targeters.length - 1; i >= 0; i--) { InstructionTargeter t = targeters[i]; if (t instanceof LineNumberTag) { return ((LineNumberTag)t).getLineNumber(); } } return prevLine; } public boolean isStatic() { return Modifier.isStatic(getAccessFlags()); } public void addExceptionHandler( InstructionHandle start, InstructionHandle end, InstructionHandle handlerStart, ObjectType catchType, boolean highPriority) { InstructionHandle start1 = Range.genStart(body, start); InstructionHandle end1 = Range.genEnd(body, end); ExceptionRange er = new ExceptionRange(body, BcelWorld.fromBcel(catchType), highPriority); er.associateWithTargets(start1, end1, handlerStart); } public int getAccessFlags() { return accessFlags; } public Type[] getArgumentTypes() { return argumentTypes; } // public String[] getArgumentNames() { // return argumentNames; // } public LazyClassGen getEnclosingClass() { return enclosingClass; } public int getMaxLocals() { return maxLocals; } public String getName() { return name; } public Type getReturnType() { return returnType; } public void setMaxLocals(int maxLocals) { this.maxLocals = maxLocals; } public InstructionList getBody() { return body; } public boolean hasBody() { return body != null; } public Attribute[] getAttributes() { return attributes; } public String[] getDeclaredExceptions() { return declaredExceptions; } public String getClassName() { return enclosingClass.getName(); } // ---- packing! public MethodGen pack() { MethodGen gen = new MethodGen( getAccessFlags(), getReturnType(), getArgumentTypes(), null, //getArgumentNames(), getName(), getEnclosingClass().getName(), new InstructionList(), getEnclosingClass().getConstantPoolGen()); for (int i = 0, len = declaredExceptions.length; i < len; i++) { gen.addException(declaredExceptions[i]); } for (int i = 0, len = attributes.length; i < len; i++) { gen.addAttribute(attributes[i]); } if (hasBody()) { packBody(gen); gen.setMaxLocals(); gen.setMaxStack(); } return gen; } /** fill the newly created method gen with our body, * inspired by InstructionList.copy() */ public void packBody(MethodGen gen) { HashMap map = new HashMap(); InstructionList fresh = gen.getInstructionList(); /* Make copies of all instructions, append them to the new list * and associate old instruction references with the new ones, i.e., * a 1:1 mapping. */ for (InstructionHandle ih = getBody().getStart(); ih != null; ih = ih.getNext()) { if (Range.isRangeHandle(ih)) { continue; } Instruction i = ih.getInstruction(); Instruction c = i.copy(); // Use clone for shallow copy if (c instanceof BranchInstruction) map.put(ih, fresh.append((BranchInstruction) c)); else map.put(ih, fresh.append(c)); } // at this point, no rangeHandles are in fresh. Let's use that... /* Update branch targets and insert various attributes. * Insert our exceptionHandlers * into a sorted list, so they can be added in order later. */ InstructionHandle ih = getBody().getStart(); InstructionHandle jh = fresh.getStart(); LinkedList exnList = new LinkedList(); Map localVariableStarts = new HashMap(); Map localVariableEnds = new HashMap(); int currLine = -1; while (ih != null) { if (map.get(ih) == null) { // we're a range instruction Range r = Range.getRange(ih); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; if (er.getStart() == ih) { //System.err.println("er " + er); if (!er.isEmpty()){ // order is important, insert handlers in order of start insertHandler(er, exnList); } } } else { // we must be a shadow range or something equally useless, // so forget about doing anything } // just increment ih. ih = ih.getNext(); } else { // assert map.get(ih) == jh Instruction i = ih.getInstruction(); Instruction j = jh.getInstruction(); if (i instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) i; BranchInstruction bj = (BranchInstruction) j; InstructionHandle itarget = bi.getTarget(); // old target // try { // New target is in hash map bj.setTarget(remap(itarget, map)); // } catch (NullPointerException e) { // print(); // System.out.println("Was trying to remap " + bi); // System.out.println("who's target was supposedly " + itarget); // throw e; // } if (bi instanceof Select) { // Either LOOKUPSWITCH or TABLESWITCH InstructionHandle[] itargets = ((Select) bi).getTargets(); InstructionHandle[] jtargets = ((Select) bj).getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { // Update all targets jtargets[k] = remap(itargets[k], map); jtargets[k].addTargeter(bj); } } } // now deal with line numbers // and store up info for local variables InstructionTargeter[] targeters = ih.getTargeters(); if (targeters != null) { for (int k = targeters.length - 1; k >= 0; k--) { InstructionTargeter targeter = targeters[k]; if (targeter instanceof LineNumberTag) { int line = ((LineNumberTag)targeter).getLineNumber(); if (line != currLine) { gen.addLineNumber(jh, line); currLine = line; } } else if (targeter instanceof LocalVariableTag) { LocalVariableTag lvt = (LocalVariableTag) targeter; if (i instanceof LocalVariableInstruction) { int index = ((LocalVariableInstruction)i).getIndex(); if (lvt.getSlot() == index) { if (localVariableStarts.get(lvt) == null) { localVariableStarts.put(lvt, jh); } localVariableEnds.put(lvt, jh); } } } } } // now continue ih = ih.getNext(); jh = jh.getNext(); } } // now add exception handlers for (Iterator iter = exnList.iterator(); iter.hasNext();) { ExceptionRange r = (ExceptionRange) iter.next(); if (r.isEmpty()) continue; gen.addExceptionHandler( remap(r.getRealStart(), map), remap(r.getRealEnd(), map), remap(r.getHandler(), map), (r.getCatchType() == null) ? null : (ObjectType) BcelWorld.makeBcelType(r.getCatchType())); } // now add local variables gen.removeLocalVariables(); for (Iterator iter = localVariableStarts.keySet().iterator(); iter.hasNext(); ) { LocalVariableTag tag = (LocalVariableTag) iter.next(); gen.addLocalVariable( tag.getName(), BcelWorld.makeBcelType(tag.getType()), tag.getSlot(), (InstructionHandle) localVariableStarts.get(tag), (InstructionHandle) localVariableEnds.get(tag)); } } private static InstructionHandle remap(InstructionHandle ih, Map map) { while (true) { Object ret = map.get(ih); if (ret == null) { ih = ih.getNext(); } else { return (InstructionHandle) ret; } } } // exception ordering. // What we should be doing is dealing with priority inversions way earlier than we are // and counting on the tree structure. In which case, the below code is in fact right. // XXX THIS COMMENT BELOW IS CURRENTLY WRONG. // An exception A preceeds an exception B in the exception table iff: // * A and B were in the original method, and A preceeded B in the original exception table // * If A has a higher priority than B, than it preceeds B. // * If A and B have the same priority, then the one whose START happens EARLIEST has LEAST priority. // in short, the outermost exception has least priority. // we implement this with a LinkedList. We could possibly implement this with a java.util.SortedSet, // but I don't trust the only implementation, TreeSet, to do the right thing. private static void insertHandler(ExceptionRange fresh, LinkedList l) { // for (ListIterator iter = l.listIterator(); iter.hasNext();) { // ExceptionRange r = (ExceptionRange) iter.next(); // if (fresh.getPriority() >= r.getPriority()) { // iter.previous(); // iter.add(fresh); // return; // } // } l.add(0, fresh); } public boolean isPrivate() { return Modifier.isPrivate(getAccessFlags()); } // ---- /** A good body is a body with the following properties: * * <ul> * <li> For each branch instruction S in body, target T of S is in body. * <li> For each branch instruction S in body, target T of S has S as a targeter. * <li> For each instruction T in body, for each branch instruction S that is a * targeter of T, S is in body. * <li> For each non-range-handle instruction T in body, for each instruction S * that is a targeter of T, S is * either a branch instruction, an exception range or a tag * <li> For each range-handle instruction T in body, there is exactly one targeter S * that is a range. * <li> For each range-handle instruction T in body, the range R targeting T is in body. * <li> For each instruction T in body, for each exception range R targeting T, R is * in body. * <li> For each exception range R in body, let T := R.handler. T is in body, and R is one * of T's targeters * <li> All ranges are properly nested: For all ranges Q and R, if Q.start preceeds * R.start, then R.end preceeds Q.end. * </ul> * * Where the shorthand "R is in body" means "R.start is in body, R.end is in body, and * any InstructionHandle stored in a field of R (such as an exception handle) is in body". */ public void assertGoodBody() { // XXX this is REALLY slow since we get the string first... assertGoodBody(getBody(), toString()); } // XXX we might not want to release with any calls to this incredibly inefficient method. public static void assertGoodBody(InstructionList il, String from) { if (true) return; if (il == null) return; Set body = new HashSet(); Stack ranges = new Stack(); for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { body.add(ih); if (ih.getInstruction() instanceof BranchInstruction) { body.add(ih.getInstruction()); } } for (InstructionHandle ih = il.getStart(); ih != null; ih = ih.getNext()) { assertGoodHandle(ih, body, ranges, from); InstructionTargeter[] ts = ih.getTargeters(); if (ts != null) { for (int i = ts.length - 1; i >= 0; i--) { assertGoodTargeter(ts[i], ih, body, from); } } } } private static void assertGoodHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Instruction inst = ih.getInstruction(); if ((inst instanceof BranchInstruction) ^ (ih instanceof BranchHandle)) { throw new BCException("bad instruction/handle pair in " + from); } if (Range.isRangeHandle(ih)) { assertGoodRangeHandle(ih, body, ranges, from); } else if (inst instanceof BranchInstruction) { assertGoodBranchInstruction((BranchHandle) ih, (BranchInstruction) inst, body, ranges, from); } } private static void assertGoodBranchInstruction( BranchHandle ih, BranchInstruction inst, Set body, Stack ranges, String from) { if (ih.getTarget() != inst.getTarget()) { throw new BCException("bad branch instruction/handle pair in " + from); } InstructionHandle target = ih.getTarget(); assertInBody(target, body, from); assertTargetedBy(target, inst, from); if (inst instanceof Select) { Select sel = (Select) inst; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { assertInBody(itargets[k], body, from); assertTargetedBy(itargets[k], inst, from); } } } /** ih is an InstructionHandle or a BranchInstruction */ private static void assertInBody(Object ih, Set body, String from) { if (! body.contains(ih)) throw new BCException("thing not in body in " + from); } private static void assertGoodRangeHandle(InstructionHandle ih, Set body, Stack ranges, String from) { Range r = getRangeAndAssertExactlyOne(ih, from); assertGoodRange(r, body, from); if (r.getStart() == ih) { ranges.push(r); } else if (r.getEnd() == ih) { if (ranges.peek() != r) throw new BCException("bad range inclusion in " + from); ranges.pop(); } } private static void assertGoodRange(Range r, Set body, String from) { assertInBody(r.getStart(), body, from); assertRangeHandle(r.getStart(), from); assertTargetedBy(r.getStart(), r, from); assertInBody(r.getEnd(), body, from); assertRangeHandle(r.getEnd(), from); assertTargetedBy(r.getEnd(), r, from); if (r instanceof ExceptionRange) { ExceptionRange er = (ExceptionRange) r; assertInBody(er.getHandler(), body, from); assertTargetedBy(er.getHandler(), r, from); } } private static void assertRangeHandle(InstructionHandle ih, String from) { if (! Range.isRangeHandle(ih)) throw new BCException("bad range handle " + ih + " in " + from); } private static void assertTargetedBy( InstructionHandle target, InstructionTargeter targeter, String from) { InstructionTargeter[] ts = target.getTargeters(); if (ts == null) throw new BCException("bad targeting relationship in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] == targeter) return; } throw new RuntimeException("bad targeting relationship in " + from); } private static void assertTargets(InstructionTargeter targeter, InstructionHandle target, String from) { if (targeter instanceof Range) { Range r = (Range) targeter; if (r.getStart() == target || r.getEnd() == target) return; if (r instanceof ExceptionRange) { if (((ExceptionRange)r).getHandler() == target) return; } } else if (targeter instanceof BranchInstruction) { BranchInstruction bi = (BranchInstruction) targeter; if (bi.getTarget() == target) return; if (targeter instanceof Select) { Select sel = (Select) targeter; InstructionHandle[] itargets = sel.getTargets(); for (int k = itargets.length - 1; k >= 0; k--) { if (itargets[k] == target) return; } } } else if (targeter instanceof Tag) { return; } throw new BCException(targeter + " doesn't target " + target + " in " + from ); } private static Range getRangeAndAssertExactlyOne(InstructionHandle ih, String from) { Range ret = null; InstructionTargeter[] ts = ih.getTargeters(); if (ts == null) throw new BCException("range handle with no range in " + from); for (int i = ts.length - 1; i >= 0; i--) { if (ts[i] instanceof Range) { if (ret != null) throw new BCException("range handle with multiple ranges in " + from); ret = (Range) ts[i]; } } if (ret == null) throw new BCException("range handle with no range in " + from); return ret; } private static void assertGoodTargeter( InstructionTargeter t, InstructionHandle ih, Set body, String from) { assertTargets(t, ih, from); if (t instanceof Range) { assertGoodRange((Range) t, body, from); } else if (t instanceof BranchInstruction) { assertInBody(t, body, from); } } // ---- boolean isAdviceMethod() { return memberView.getAssociatedShadowMunger() != null; } boolean isAjSynthetic() { if (memberView == null) return true; return memberView.isAjSynthetic(); } public AjAttribute.EffectiveSignatureAttribute getEffectiveSignature() { //if (memberView == null) return null; return memberView.getEffectiveSignature(); } public String getSignature() { return Member.typesToSignature(BcelWorld.fromBcel(getReturnType()), BcelWorld.fromBcel(getArgumentTypes())); } public BcelMethod getMemberView() { return memberView; } public void forcePublic() { accessFlags = Utility.makePublic(accessFlags); } public boolean getCanInline() { return canInline; } public void setCanInline(boolean canInline) { this.canInline = canInline; } }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
asm/src/org/aspectj/asm/StructureModel.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.asm; import java.io.File; import java.io.Serializable; import java.util.*; import org.aspectj.bridge.SourceLocation; /** * @author Mik Kersten */ public class StructureModel implements Serializable { protected StructureNode root = null; protected String configFile = null; private Map fileMap = null; public static final ProgramElementNode NO_STRUCTURE = new ProgramElementNode("<build to view structure>", ProgramElementNode.Kind.ERROR, null); public StructureNode getRoot() { return root; } public void setRoot(StructureNode root) { this.root = root; } public Map getFileMap() { return fileMap; } public void setFileMap(HashMap fileMap) { this.fileMap = fileMap; } public boolean isValid() { return root != null && fileMap != null; } /** * @param packageName if null default package is searched * @param className can't be null */ public ProgramElementNode findNodeForClass(String packageName, String className) { StructureNode packageNode = null; if (packageName == null) { packageNode = root; } else { for (Iterator it = root.getChildren().iterator(); it.hasNext(); ) { StructureNode node = (StructureNode)it.next(); if (packageName.equals(node.getName())) { packageNode = node; } } if (packageNode == null) return null; } // !!! this searches each file for a class for (Iterator it = packageNode.getChildren().iterator(); it.hasNext(); ) { ProgramElementNode fileNode = (ProgramElementNode)it.next(); for (Iterator j = fileNode.getChildren().iterator(); j.hasNext(); ) { ProgramElementNode classNode = (ProgramElementNode)j.next(); if (classNode instanceof ProgramElementNode && className.equals(classNode.getName())) { return (ProgramElementNode)classNode; } } } return null; } /** * @param sourceFilePath modified to '/' delimited path for consistency * @return a new structure node for the file if it was not found in the model */ public StructureNode findRootNodeForSourceFile(String sourceFilePath) { if (!isValid() || sourceFilePath == null) { return StructureModel.NO_STRUCTURE; } else { String correctedPath = sourceFilePath.replace('\\', '/'); StructureNode node = (StructureNode)getFileMap().get(correctedPath);//findFileNode(filePath, model); if (node != null) { return node; } else { return createFileStructureNode(sourceFilePath); } } } /** * Never returns null * * @param sourceFilePath modified to '/' delimited path for consistency * @param lineNumber if 0 or 1 the corresponding file node will be returned * @return a new structure node for the file if it was not found in the model */ public StructureNode findNodeForSourceLine(String sourceFilePath, int lineNumber) { String correctedPath = sourceFilePath.replace('\\', '/'); StructureNode node = findNodeForSourceLineHelper(root, correctedPath, lineNumber); if (node != null) { return node; } else { return createFileStructureNode(sourceFilePath); } } private StructureNode createFileStructureNode(String sourceFilePath) { String fileName = new File(sourceFilePath).getName(); ProgramElementNode fileNode = new ProgramElementNode(fileName, ProgramElementNode.Kind.FILE_JAVA, null); fileNode.setSourceLocation(new SourceLocation(new File(sourceFilePath), 1, 1)); fileNode.addChild(NO_STRUCTURE); return fileNode; } private StructureNode findNodeForSourceLineHelper(StructureNode node, String sourceFilePath, int lineNumber) { if (matches(node, sourceFilePath, lineNumber) && !hasMoreSpecificChild(node, sourceFilePath, lineNumber)) { return node; } if (node != null && node.getChildren() != null) { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { StructureNode foundNode = findNodeForSourceLineHelper( (StructureNode)it.next(), sourceFilePath, lineNumber); if (foundNode != null) return foundNode; } } return null; } private boolean matches(StructureNode node, String sourceFilePath, int lineNumber) { return node != null && node.getSourceLocation() != null && node.getSourceLocation().getSourceFile().getAbsolutePath().equals(sourceFilePath) && ((node.getSourceLocation().getLine() <= lineNumber && node.getSourceLocation().getEndLine() >= lineNumber) || (lineNumber <= 1 && node instanceof ProgramElementNode && ((ProgramElementNode)node).getProgramElementKind().isSourceFileKind()) ); } private boolean hasMoreSpecificChild(StructureNode node, String sourceFilePath, int lineNumber) { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { ProgramElementNode child = (ProgramElementNode)it.next(); if (matches(child, sourceFilePath, lineNumber)) return true; } return false; } public String getConfigFile() { return configFile; } public void setConfigFile(String configFile) { this.configFile = configFile; } }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AsmBuilder.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.text.CollationElementIterator; import java.util.*; import java.util.List; import org.aspectj.ajdt.internal.compiler.ast.*; import org.aspectj.ajdt.internal.compiler.ast.AdviceDeclaration; import org.aspectj.ajdt.internal.compiler.lookup.*; import org.aspectj.ajdt.internal.compiler.lookup.EclipseShadow; import org.aspectj.asm.*; import org.aspectj.asm.StructureModel; import org.aspectj.bridge.*; import org.aspectj.bridge.ISourceLocation; import org.aspectj.weaver.Member; import org.eclipse.jdt.core.dom.ASTNode; import org.eclipse.jdt.internal.compiler.*; import org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter; import org.eclipse.jdt.internal.compiler.ast.*; import org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration; import org.eclipse.jdt.internal.compiler.impl.ReferenceContext; import org.eclipse.jdt.internal.compiler.lookup.*; import org.eclipse.jdt.internal.compiler.lookup.CompilationUnitScope; import org.eclipse.jdt.internal.compiler.problem.ProblemHandler; public class AsmBuilder extends AbstractSyntaxTreeVisitorAdapter { private Stack stack = new Stack(); private CompilationResult currCompilationResult = null; public static void build( CompilationUnitDeclaration unit, StructureModel structureModel) { new AsmBuilder().internalBuild(unit, structureModel); } private void internalBuild(CompilationUnitDeclaration unit, StructureModel structureModel) { currCompilationResult = unit.compilationResult(); File file = new File(new String(unit.getFileName())); ISourceLocation sourceLocation = new SourceLocation(file, 1); ProgramElementNode cuNode = new ProgramElementNode( new String(file.getName()), ProgramElementNode.Kind.FILE_JAVA, sourceLocation, 0, "", new ArrayList()); ImportReference currentPackage = unit.currentPackage; if (currentPackage != null) { StringBuffer nameBuffer = new StringBuffer(); for (int i = 0; i < currentPackage.getImportName().length; i++) { nameBuffer.append(new String(currentPackage.getImportName()[i])); if (i < currentPackage.getImportName().length-1) nameBuffer.append('.'); } String pkgName = nameBuffer.toString(); boolean found = false; ProgramElementNode pkgNode = null; for (Iterator it = StructureModelManager.INSTANCE.getStructureModel().getRoot().getChildren().iterator(); it.hasNext(); ) { ProgramElementNode currNode = (ProgramElementNode)it.next(); if (currNode.getName().equals(pkgName)) pkgNode = currNode; } if (pkgNode == null) { pkgNode = new ProgramElementNode( pkgName, ProgramElementNode.Kind.PACKAGE, new ArrayList()); StructureModelManager.INSTANCE.getStructureModel().getRoot().addChild(pkgNode); } pkgNode.addChild(cuNode); } else { StructureModelManager.INSTANCE.getStructureModel().getRoot().addChild(cuNode); } stack.push(cuNode); unit.traverse(this, unit.scope); StructureModelManager.INSTANCE.getStructureModel().getFileMap().put( file.getAbsolutePath().replace('\\', '/'), cuNode ); // if (currImports != null) peNode.addChild(0, currImports); // currImports = null; } public boolean visit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { String name = new String(typeDeclaration.name); ProgramElementNode.Kind kind = ProgramElementNode.Kind.CLASS; if (typeDeclaration instanceof AspectDeclaration) kind = ProgramElementNode.Kind.ASPECT; else if (typeDeclaration.isInterface()) kind = ProgramElementNode.Kind.INTERFACE; ProgramElementNode peNode = new ProgramElementNode( name, kind, makeLocation(typeDeclaration), typeDeclaration.modifiers, "", new ArrayList()); ((StructureNode)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(TypeDeclaration typeDeclaration, CompilationUnitScope scope) { stack.pop(); } // ??? share impl with visit(TypeDeclaration, ..) ? public boolean visit(MemberTypeDeclaration memberTypeDeclaration, ClassScope scope) { String name = new String(memberTypeDeclaration.name); ProgramElementNode.Kind kind = ProgramElementNode.Kind.CLASS; if (memberTypeDeclaration instanceof AspectDeclaration) kind = ProgramElementNode.Kind.ASPECT; else if (memberTypeDeclaration.isInterface()) kind = ProgramElementNode.Kind.INTERFACE; ProgramElementNode peNode = new ProgramElementNode( name, kind, makeLocation(memberTypeDeclaration), memberTypeDeclaration.modifiers, "", new ArrayList()); ((StructureNode)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(MemberTypeDeclaration memberTypeDeclaration, ClassScope scope) { stack.pop(); } // !!! improve name and type generation public boolean visit(MethodDeclaration methodDeclaration, ClassScope scope) { ProgramElementNode.Kind kind = ProgramElementNode.Kind.METHOD; String label = new String(methodDeclaration.selector); if (methodDeclaration instanceof AdviceDeclaration) { kind = ProgramElementNode.Kind.ADVICE; label = translateAdviceName(label); } else if (methodDeclaration instanceof PointcutDeclaration) { kind = ProgramElementNode.Kind.POINTCUT; } else if (methodDeclaration instanceof DeclareDeclaration) { DeclareDeclaration declare = (DeclareDeclaration)methodDeclaration; label = translateDeclareName(declare.toString()); if (label.indexOf("warning") != -1) kind = ProgramElementNode.Kind.DECLARE_WARNING; if (label.indexOf("error") != -1) kind = ProgramElementNode.Kind.DECLARE_ERROR; } else if (methodDeclaration instanceof InterTypeDeclaration) { kind = ProgramElementNode.Kind.INTRODUCTION; label = translateInterTypeDecName(new String(((InterTypeDeclaration)methodDeclaration).selector)); } ProgramElementNode peNode = new ProgramElementNode( label, kind, makeLocation(methodDeclaration), methodDeclaration.modifiers, "", new ArrayList()); Member member = EclipseWorld.makeResolvedMember(methodDeclaration.binding); peNode.setBytecodeName(member.getName()); peNode.setBytecodeSignature(member.getSignature()); ((StructureNode)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(MethodDeclaration methodDeclaration, ClassScope scope) { stack.pop(); } public boolean visit(FieldDeclaration fieldDeclaration, MethodScope scope) { ProgramElementNode peNode = new ProgramElementNode( new String(fieldDeclaration.name), ProgramElementNode.Kind.FIELD, makeLocation(fieldDeclaration), fieldDeclaration.modifiers, "", new ArrayList()); ((StructureNode)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(FieldDeclaration fieldDeclaration, MethodScope scope) { stack.pop(); } // public boolean visit(ImportReference importRef, CompilationUnitScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // new String(importRef.toString()), // ProgramElementNode.Kind., // makeLocation(importRef), // 0, // "", // new ArrayList()); // ((StructureNode)stack.peek()).addChild(0, peNode); // stack.push(peNode); // return true; // } // public void endVisit(ImportReference importRef,CompilationUnitScope scope) { // stack.pop(); // } public boolean visit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { if (constructorDeclaration.isDefaultConstructor) { stack.push(null); // a little wierd but does the job return true; } ProgramElementNode peNode = new ProgramElementNode( new String(constructorDeclaration.selector), ProgramElementNode.Kind.CONSTRUCTOR, makeLocation(constructorDeclaration), constructorDeclaration.modifiers, "", new ArrayList()); ((StructureNode)stack.peek()).addChild(peNode); stack.push(peNode); return true; } public void endVisit(ConstructorDeclaration constructorDeclaration, ClassScope scope) { stack.pop(); } // public boolean visit(Clinit clinit, ClassScope scope) { // ProgramElementNode peNode = new ProgramElementNode( // "<clinit>", // ProgramElementNode.Kind.INITIALIZER, // makeLocation(clinit), // clinit.modifiers, // "", // new ArrayList()); // ((StructureNode)stack.peek()).addChild(peNode); // stack.push(peNode); // return false; // } // public void endVisit(Clinit clinit, ClassScope scope) { // stack.pop(); // } /** This method works-around an odd traverse implementation on Initializer */ private Initializer inInitializer = null; public boolean visit(Initializer initializer, MethodScope scope) { if (initializer == inInitializer) return false; inInitializer = initializer; ProgramElementNode peNode = new ProgramElementNode( "...", ProgramElementNode.Kind.INITIALIZER, makeLocation(initializer), initializer.modifiers, "", new ArrayList()); ((StructureNode)stack.peek()).addChild(peNode); stack.push(peNode); initializer.block.traverse(this, scope); stack.pop(); return false; } // ??? handle non-existant files private ISourceLocation makeLocation(AstNode node) { String fileName = new String(currCompilationResult.getFileName()); int line = ProblemHandler.searchLineNumber( currCompilationResult.lineSeparatorPositions, node.sourceStart); return new SourceLocation(new File(fileName), line); } // !!! move or replace private String translateAdviceName(String label) { if (label.indexOf("before") != -1) return "before"; if (label.indexOf("returning") != -1) return "after returning"; if (label.indexOf("after") != -1) return "after"; if (label.indexOf("around") != -1) return "around"; else return "<advice>"; } // !!! move or replace private String translateDeclareName(String name) { int colonIndex = name.indexOf(":"); if (colonIndex != -1) { return name.substring(0, colonIndex); } else { return name; } } // !!! move or replace private String translateInterTypeDecName(String name) { int index = name.lastIndexOf('$'); if (index != -1) { return name.substring(index+1); } else { return name; } } }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
weaver/src/org/aspectj/weaver/AsmAdaptor.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.util.*; import java.util.Iterator; import org.aspectj.asm.*; import org.aspectj.asm.StructureModel; import org.aspectj.bridge.*; import org.aspectj.bridge.SourceLocation; public class AsmAdaptor { public static void noteMunger(StructureModel model, Shadow shadow, ShadowMunger munger) { if (munger instanceof Advice) { Advice a = (Advice)munger; if (a.getKind().isPerEntry() || a.getKind().isCflow()) { // ??? might want to show these in the future return; } // System.out.println("--------------------------"); ProgramElementNode targetNode = getNode(model, shadow); ProgramElementNode adviceNode = getNode(model, a); // System.out.println("> target: " + targetNode + ", advice: " + adviceNode); createAppropriateLinks(targetNode, adviceNode); } } private static void createAppropriateLinks( ProgramElementNode target, ProgramElementNode advice) { if (target == null || advice == null) return; addLink(target, new LinkNode(advice), org.aspectj.asm.AdviceAssociation.METHOD_RELATION, true); addLink(advice, new LinkNode(target), org.aspectj.asm.AdviceAssociation.METHOD_RELATION, false); // System.out.println(">> added target: " + target + ", advice: " + advice); } private static void addLink( ProgramElementNode onNode, LinkNode linkNode, Relation relation, boolean isBack) { RelationNode node = null; String relationName = isBack ? relation.getBackNavigationName() : relation.getForwardNavigationName(); //System.err.println("on: " + onNode + " relationName: " + relationName + " existin: " + onNode.getRelations()); for (Iterator i = onNode.getRelations().iterator(); i.hasNext();) { RelationNode relationNode = (RelationNode) i.next(); if (relationName.equals(relationNode.getName())) { node = relationNode; break; } } if (node == null) { node = new RelationNode(relation, relationName, new ArrayList()); onNode.getRelations().add(node); } node.getChildren().add(linkNode); } private static ProgramElementNode getNode(StructureModel model, Advice a) { //ResolvedTypeX inAspect = a.getConcreteAspect(); Member member = a.getSignature(); return lookupMember(model, member); } private static ProgramElementNode getNode(StructureModel model, Shadow shadow) { Member enclosingMember = shadow.getEnclosingCodeSignature(); ProgramElementNode enclosingNode = lookupMember(model, enclosingMember); Member shadowSig = shadow.getSignature(); if (!shadowSig.equals(enclosingMember)) { ProgramElementNode bodyNode = findOrCreateBodyNode(enclosingNode, shadowSig, shadow); return bodyNode; } else { return enclosingNode; } } private static ProgramElementNode findOrCreateBodyNode( ProgramElementNode enclosingNode, Member shadowSig, Shadow shadow) { for (Iterator it = enclosingNode.getChildren().iterator(); it.hasNext(); ) { ProgramElementNode node = (ProgramElementNode)it.next(); if (shadowSig.getName().equals(node.getBytecodeName()) && shadowSig.getSignature().equals(node.getBytecodeSignature())) { return node; } } ISourceLocation sl = shadow.getSourceLocation(); ProgramElementNode peNode = new ProgramElementNode( shadow.toString(), ProgramElementNode.Kind.CODE, new SourceLocation(enclosingNode.getSourceLocation().getSourceFile(), sl.getLine()), 0, "", new ArrayList()); System.err.println(peNode.getSourceLocation()); peNode.setBytecodeName(shadowSig.getName()); peNode.setBytecodeSignature(shadowSig.getSignature()); enclosingNode.addChild(peNode); return peNode; } public static ProgramElementNode lookupMember(StructureModel model, Member member) { TypeX declaringType = member.getDeclaringType(); ProgramElementNode classNode = model.findNodeForClass(declaringType.getPackageName(), declaringType.getClassName()); return findMemberInClass(classNode, member); } private static ProgramElementNode findMemberInClass( ProgramElementNode classNode, Member member) { if (classNode == null) return null; // XXX remove this check for (Iterator it = classNode.getChildren().iterator(); it.hasNext(); ) { ProgramElementNode node = (ProgramElementNode)it.next(); if (member.getName().equals(node.getBytecodeName()) && member.getSignature().equals(node.getBytecodeSignature())) { return node; } } return null; } }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
weaver/src/org/aspectj/weaver/Lint.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.*; import java.io.File; import java.text.MessageFormat; import java.util.*; import org.aspectj.bridge.*; import org.aspectj.bridge.IMessage.Kind; public class Lint { private Map kinds = new HashMap(); private World world; public final Kind invalidAbsoluteTypeName = new Kind("invalidAbsoluteTypeName", "no match for this type name: {0}"); public final Kind invalidWildcardTypeName = new Kind("invalidWildcardTypeName", "no match for this type pattern: {0}"); public final Kind unresolvableMember = new Kind("unresolvableMember", "can not resolve this member: {0}"); public final Kind typeNotExposedToWeaver = new Kind("typeNotExposedToWeaver", "this affected type is not exposed to the weaver: {0}"); public Lint(World world) { this.world = world; } public void setAll(String messageKind) { setAll(getMessageKind(messageKind)); } private void setAll(IMessage.Kind messageKind) { for (Iterator i = kinds.values().iterator(); i.hasNext(); ) { Kind kind = (Kind)i.next(); kind.setKind(messageKind); } } public void setFromProperties(File file) { try { InputStream s = new FileInputStream(file); setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), "problem loading Xlint properties file: " + file.getPath() + ", " + ioe.getMessage()); } } public void loadDefaultProperties() { InputStream s = getClass().getResourceAsStream("XlintDefault.properties"); if (s == null) { MessageUtil.warn(world.getMessageHandler(), "couldn't load XlintDefault.properties"); return; } try { setFromProperties(s); } catch (IOException ioe) { MessageUtil.error(world.getMessageHandler(), "problem loading XlintDefault.properties, " + ioe.getMessage()); } } private void setFromProperties(InputStream s) throws IOException { Properties p = new Properties(); p.load(s); setFromProperties(p); } public void setFromProperties(Properties properties) { for (Iterator i = properties.entrySet().iterator(); i.hasNext(); ) { Map.Entry entry = (Map.Entry)i.next(); Kind kind = (Kind)kinds.get(entry.getKey()); if (kind == null) { MessageUtil.error(world.getMessageHandler(), "invalid Xlint key: " + entry.getKey()); } else { kind.setKind(getMessageKind((String)entry.getValue())); } } } private IMessage.Kind getMessageKind(String v) { if (v.equals("ignore")) return null; else if (v.equals("warning")) return IMessage.WARNING; else if (v.equals("error")) return IMessage.ERROR; MessageUtil.error(world.getMessageHandler(), "invalid Xlint message kind (must be one of ignore, warning, error): " + v); return null; } public class Kind { private String name; private String message; private IMessage.Kind kind = IMessage.WARNING; public Kind(String name, String message) { this.name = name; this.message = message; kinds.put(this.name, this); } public boolean isEnabled() { return kind != null; } public IMessage.Kind getKind() { return kind; } public void setKind(IMessage.Kind kind) { this.kind = kind; } public void signal(String info, ISourceLocation location) { if (kind == null) return; String text = MessageFormat.format(message, new Object[] {info} ); text += " [Xlint:" + name + "]"; world.getMessageHandler().handleMessage(new Message(text, kind, null, location)); } } }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
weaver/src/org/aspectj/weaver/ResolvedTypeX.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.lang.reflect.Modifier; import java.util.*; import org.aspectj.bridge.*; import org.aspectj.bridge.MessageUtil; import org.aspectj.weaver.bcel.BcelObjectType; import org.aspectj.weaver.patterns.*; import org.aspectj.weaver.patterns.PerClause; public abstract class ResolvedTypeX extends TypeX { protected World world; ResolvedTypeX(String signature, World world) { super(signature); this.world = world; } // ---- things that don't require a world /** returns Iterator&lt;ResolvedTypeX&gt; */ public final Iterator getDirectSupertypes() { Iterator ifacesIterator = Iterators.array(getDeclaredInterfaces()); ResolvedTypeX superclass = getSuperclass(); if (superclass == null) { return ifacesIterator; } else { return Iterators.snoc(ifacesIterator, superclass); } } public abstract ResolvedMember[] getDeclaredFields(); public abstract ResolvedMember[] getDeclaredMethods(); public abstract ResolvedTypeX[] getDeclaredInterfaces(); public abstract ResolvedMember[] getDeclaredPointcuts(); public abstract ResolvedTypeX getSuperclass(); public abstract int getModifiers(); public abstract boolean needsNoConversionFrom(TypeX other); public abstract boolean isCoerceableFrom(TypeX other); public abstract boolean isAssignableFrom(TypeX other); // ---- things that would require a world if I weren't resolved public final Iterator getDirectSupertypes(World world) { return getDirectSupertypes(); } public final ResolvedMember[] getDeclaredFields(World world) { return getDeclaredFields(); } public final ResolvedMember[] getDeclaredMethods(World world) { return getDeclaredMethods(); } public final TypeX[] getDeclaredInterfaces(World world) { return getDeclaredInterfaces(); } public final ResolvedMember[] getDeclaredPointcuts(World world) { return getDeclaredPointcuts(); } public final int getModifiers(World world) { return getModifiers(); } public final TypeX getSuperclass(World world) { return getSuperclass(); } // conversions public final boolean isAssignableFrom(TypeX other, World world) { return isAssignableFrom(other); } public final boolean isCoerceableFrom(TypeX other, World world) { return isCoerceableFrom(other); } public boolean needsNoConversionFrom(TypeX other, World world) { return needsNoConversionFrom(other); } public final boolean isConvertableFrom(TypeX other) { if (this.equals(OBJECT) || other.equals(OBJECT)) return true; return this.isCoerceableFrom(other); } // utilities public ResolvedTypeX getResolvedComponentType() { return null; } public ResolvedTypeX resolve(World world) { return this; } public World getWorld() { return world; } // ---- things from object public final boolean equals(Object other) { if (other instanceof ResolvedTypeX) { return this == other; } else { return super.equals(other); } } // ---- difficult things /** * returns an iterator through all of the fields of this type, in order * for checking from JVM spec 2ed 5.4.3.2. This means that the order is * * <ul><li> fields from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getFields() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter fieldGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredFields()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), fieldGetter); } /** * returns an iterator through all of the methods of this type, in order * for checking from JVM spec 2ed 5.4.3.3. This means that the order is * * <ul><li> methods from current class </li> * <li> recur into superclass, all the way up, not touching interfaces </li> * <li> recur into all superinterfaces, in some unspecified order </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getMethods() { final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter ifaceGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( Iterators.array(((ResolvedTypeX)o).getDeclaredInterfaces()) ); } }; Iterators.Getter methodGetter = new Iterators.Getter() { public Iterator get(Object o) { return Iterators.array(((ResolvedTypeX)o).getDeclaredMethods()); } }; return Iterators.mapOver( Iterators.append( new Iterator() { ResolvedTypeX curr = ResolvedTypeX.this; public boolean hasNext() { return curr != null; } public Object next() { ResolvedTypeX ret = curr; curr = curr.getSuperclass(); return ret; } public void remove() { throw new UnsupportedOperationException(); } }, Iterators.recur(this, ifaceGetter)), methodGetter); } /** * described in JVM spec 2ed 5.4.3.2 */ public ResolvedMember lookupField(Member m) { return lookupMember(m, getFields()); } /** * described in JVM spec 2ed 5.4.3.3 */ public ResolvedMember lookupMethod(Member m) { return lookupMember(m, getMethods()); } /** return null if not found */ private ResolvedMember lookupMember(Member m, Iterator i) { while (i.hasNext()) { ResolvedMember f = (ResolvedMember) i.next(); if (matches(f, m)) return f; } return null; //ResolvedMember.Missing; //throw new BCException("can't find " + m); } /** return null if not found */ private ResolvedMember lookupMember(Member m, ResolvedMember[] a) { for (int i = 0; i < a.length; i++) { ResolvedMember f = a[i]; if (matches(f, m)) return f; } return null; } public static boolean matches(Member m1, Member m2) { return m1.getName().equals(m2.getName()) && m1.getSignature().equals(m2.getSignature()); } public static boolean conflictingSignature(Member m1, Member m2) { if (m1 == null || m2 == null) return false; if (!m1.getName().equals(m2.getName())) { return false; } if (m1.getKind() != m2.getKind()) { return false; } if (m1.getKind() == Member.FIELD) { return m1.getDeclaringType().equals(m2.getDeclaringType()); } else if (m1.getKind() == Member.POINTCUT) { return true; } TypeX[] p1 = m1.getParameterTypes(); TypeX[] p2 = m2.getParameterTypes(); int n = p1.length; if (n != p2.length) return false; for (int i=0; i < n; i++) { if (!p1[i].equals(p2[i])) return false; } return true; } /** * returns an iterator through all of the pointcuts of this type, in order * for checking from JVM spec 2ed 5.4.3.2 (as for fields). This means that the order is * * <ul><li> pointcuts from current class </li> * <li> recur into direct superinterfaces </li> * <li> recur into superclass </li> * </ul> * * We keep a hashSet of interfaces that we've visited so we don't spiral * out into 2^n land. */ public Iterator getPointcuts() { final Iterators.Filter dupFilter = Iterators.dupFilter(); // same order as fields Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterators.Getter pointcutGetter = new Iterators.Getter() { public Iterator get(Object o) { //System.err.println("getting for " + o); return Iterators.array(((ResolvedTypeX)o).getDeclaredPointcuts()); } }; return Iterators.mapOver( Iterators.recur(this, typeGetter), pointcutGetter); } public ResolvedPointcutDefinition findPointcut(String name) { //System.err.println("looking for pointcuts " + this); for (Iterator i = getPointcuts(); i.hasNext(); ) { ResolvedPointcutDefinition f = (ResolvedPointcutDefinition) i.next(); //System.err.println(f); if (name.equals(f.getName())) { return f; } } return null; // should we throw an exception here? } // all about collecting CrosscuttingMembers //??? collecting data-structure, shouldn't really be a field public CrosscuttingMembers crosscuttingMembers; // // private List extraConcreteShadowMungers = new ArrayList(); //XXX makes testing easier... // public void addExtraConcreteShadowMunger(ShadowMunger munger) { // munger.pointcut.assertState(Pointcut.CONCRETE); // extraConcreteShadowMungers.add(munger); // } // public List getExtraConcreteShadowMungers() { // return extraConcreteShadowMungers; // } // // private List extraConcreteTypeMungers = new ArrayList(); //XXX makes testing easier...Collections.EMPTY_LIST; // public void addExtraConcreteTypeMunger(ConcreteTypeMunger munger) { // //munger.pointcut.assertState(Pointcut.CONCRETE); // extraConcreteTypeMungers.add(munger); // } // public List getExtraConcreteTypeMungers() { // return extraConcreteTypeMungers; // } public CrosscuttingMembers collectCrosscuttingMembers() { crosscuttingMembers = new CrosscuttingMembers(this); crosscuttingMembers.setPerClause(getPerClause()); crosscuttingMembers.addShadowMungers(collectShadowMungers()); crosscuttingMembers.addTypeMungers(getTypeMungers()); crosscuttingMembers.addDeclares(collectDeclares()); crosscuttingMembers.addPrivilegedAccesses(getPrivilegedAccesses()); //System.err.println("collected cc members: " + this + ", " + collectDeclares()); return crosscuttingMembers; } private final Collection collectDeclares() { if (! this.isAspect() ) return Collections.EMPTY_LIST; ArrayList ret = new ArrayList(); //if (this.isAbstract()) { for (Iterator i = getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (!dec.isAdviceLike()) ret.add(dec); } if (!this.isAbstract()) { //ret.addAll(getDeclares()); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); //System.out.println("super: " + ty + ", " + ); for (Iterator i = ty.getDeclares().iterator(); i.hasNext();) { Declare dec = (Declare) i.next(); if (dec.isAdviceLike()) ret.add(dec); } } } return ret; } private final Collection collectShadowMungers() { if (! this.isAspect() || this.isAbstract()) return Collections.EMPTY_LIST; ArrayList acc = new ArrayList(); final Iterators.Filter dupFilter = Iterators.dupFilter(); Iterators.Getter typeGetter = new Iterators.Getter() { public Iterator get(Object o) { return dupFilter.filter( ((ResolvedTypeX)o).getDirectSupertypes()); } }; Iterator typeIterator = Iterators.recur(this, typeGetter); while (typeIterator.hasNext()) { ResolvedTypeX ty = (ResolvedTypeX) typeIterator.next(); acc.addAll(ty.getDeclaredShadowMungers()); } return acc; } public PerClause getPerClause() { return null; } protected Collection getDeclares() { return Collections.EMPTY_LIST; } protected Collection getTypeMungers() { return Collections.EMPTY_LIST; } protected Collection getPrivilegedAccesses() { return Collections.EMPTY_LIST; } // ---- useful things public final boolean isInterface() { return Modifier.isInterface(getModifiers()); } public final boolean isAbstract() { return Modifier.isAbstract(getModifiers()); } public boolean isClass() { return false; } public boolean isAspect() { return false; } public final boolean isFinal() { return Modifier.isFinal(getModifiers()); } public Collection getDeclaredAdvice() { List l = new ArrayList(); ResolvedMember[] methods = getDeclaredMethods(); for (int i=0, len = methods.length; i < len; i++) { ShadowMunger munger = methods[i].getAssociatedShadowMunger(); if (munger != null) l.add(munger); } return l; } private List shadowMungers = new ArrayList(0); public Collection getDeclaredShadowMungers() { Collection c = getDeclaredAdvice(); c.addAll(shadowMungers); return c; } public void addShadowMunger(ShadowMunger munger) { shadowMungers.add(munger); } // ---- only for testing! public ResolvedMember[] getDeclaredJavaFields() { return filterInJavaVisible(getDeclaredFields()); } public ResolvedMember[] getDeclaredJavaMethods() { return filterInJavaVisible(getDeclaredMethods()); } public ShadowMunger[] getDeclaredShadowMungersArray() { List l = (List) getDeclaredShadowMungers(); return (ShadowMunger[]) l.toArray(new ShadowMunger[l.size()]); } private ResolvedMember[] filterInJavaVisible(ResolvedMember[] ms) { List l = new ArrayList(); for (int i=0, len = ms.length; i < len; i++) { if (! ms[i].isAjSynthetic() && ms[i].getAssociatedShadowMunger() == null) { l.add(ms[i]); } } return (ResolvedMember[]) l.toArray(new ResolvedMember[l.size()]); } public abstract ISourceContext getSourceContext(); // ---- fields public static final ResolvedTypeX[] NONE = new ResolvedTypeX[0]; public static final Primitive BYTE = new Primitive("B", 1, 0); public static final Primitive CHAR = new Primitive("C", 1, 1); public static final Primitive DOUBLE = new Primitive("D", 2, 2); public static final Primitive FLOAT = new Primitive("F", 1, 3); public static final Primitive INT = new Primitive("I", 1, 4); public static final Primitive LONG = new Primitive("J", 2, 5); public static final Primitive SHORT = new Primitive("S", 1, 6); public static final Primitive VOID = new Primitive("V", 0, 8); public static final Primitive BOOLEAN = new Primitive("Z", 1, 7); public static final Missing MISSING = new Missing(); // ---- types public static abstract class Name extends ResolvedTypeX { protected ISourceContext sourceContext; protected boolean exposedToWeaver; public Name(String signature, World world, boolean exposedToWeaver) { super(signature, world); this.exposedToWeaver = exposedToWeaver; } public final boolean isClass() { return !isAspect() && !isInterface(); } public abstract boolean isAspect(); public final boolean isAssignableFrom(TypeX o) { if (o.isPrimitive()) return false; ResolvedTypeX other = o.resolve(world); return isAssignableFrom(other); } private boolean isAssignableFrom(ResolvedTypeX other) { if (this == other) return true; for(Iterator i = other.getDirectSupertypes(); i.hasNext(); ) { if (this.isAssignableFrom((ResolvedTypeX) i.next())) return true; } return false; } public final boolean isCoerceableFrom(TypeX o) { ResolvedTypeX other = o.resolve(world); if (this.isAssignableFrom(other) || other.isAssignableFrom(this)) { return true; } if (!this.isInterface() && !other.isInterface()) { return false; } if (this.isFinal() || other.isFinal()) { return false; } // ??? needs to be Methods, not just declared methods? JLS 5.5 unclear ResolvedMember[] a = getDeclaredMethods(); ResolvedMember[] b = ((Name)other).getDeclaredMethods(); for (int ai = 0, alen = a.length; ai < alen; ai++) { for (int bi = 0, blen = b.length; bi < blen; bi++) { if (! b[bi].isCompatibleWith(a[ai])) return false; } } return true; } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public ResolvedMember addPerSingletonField() { throw new RuntimeException("unimplemented"); } public ISourceContext getSourceContext() { return sourceContext; } public boolean isExposedToWeaver() { return exposedToWeaver; } } static class Array extends ResolvedTypeX { ResolvedTypeX componentType; Array(String s, World world, ResolvedTypeX componentType) { super(s, world); this.componentType = componentType; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { // ??? should this return clone? Probably not... return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return new ResolvedTypeX[] { world.resolve(CLONEABLE), world.resolve(SERIALIZABLE) }; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return world.resolve(OBJECT); } public final boolean isAssignableFrom(TypeX o) { if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isAssignableFrom(o.getComponentType(), world); } } public final boolean isCoerceableFrom(TypeX o) { if (o.equals(TypeX.OBJECT) || o.equals(TypeX.SERIALIZABLE) || o.equals(TypeX.CLONEABLE)) { return true; } if (! o.isArray()) return false; if (o.getComponentType().isPrimitive()) { return o.equals(this); } else { return getComponentType().isCoerceableFrom(o.getComponentType(), world); } } public final boolean needsNoConversionFrom(TypeX o) { return isAssignableFrom(o); } public final int getModifiers() { int mask = Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED; return (componentType.getModifiers() & mask) | Modifier.FINAL; } public TypeX getComponentType() { return componentType; } public ResolvedTypeX getResolvedComponentType() { return componentType; } public ISourceContext getSourceContext() { return getResolvedComponentType().getSourceContext(); } } static class Primitive extends ResolvedTypeX { private int size; private int index; Primitive(String signature, int size, int index) { super(signature, null); this.size = size; this.index = index; } public final int getSize() { return size; } public final int getModifiers() { return Modifier.PUBLIC | Modifier.FINAL; } public final boolean isPrimitive() { return true; } public final boolean isAssignableFrom(TypeX other) { if (! other.isPrimitive()) return false; return assignTable[((Primitive)other).index][index]; } public final boolean isCoerceableFrom(TypeX other) { if (this == other) return true; if (! other.isPrimitive()) return false; if (index > 6 || ((Primitive)other).index > 6) return false; return true; } public final boolean needsNoConversionFrom(TypeX other) { if (! other.isPrimitive()) return false; return noConvertTable[((Primitive)other).index][index]; } private static final boolean[][] assignTable = {// to: B C D F I J S V Z from { true , true , true , true , true , true , true , false, false }, // B { false, true , true , true , true , true , false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, true , true , false, false, false, false, false }, // F { false, false, true , true , true , true , false, false, false }, // I { false, false, true , true , false, true , false, false, false }, // J { false, false, true , true , true , true , true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; private static final boolean[][] noConvertTable = {// to: B C D F I J S V Z from { true , true , false, false, true , false, true , false, false }, // B { false, true , false, false, true , false, false, false, false }, // C { false, false, true , false, false, false, false, false, false }, // D { false, false, false, true , false, false, false, false, false }, // F { false, false, false, false, true , false, false, false, false }, // I { false, false, false, false, false, true , false, false, false }, // J { false, false, false, false, true , false, true , false, false }, // S { false, false, false, false, false, false, false, true , false }, // V { false, false, false, false, false, false, false, false, true }, // Z }; // ---- public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public ISourceContext getSourceContext() { return null; } } static class Missing extends ResolvedTypeX { Missing() { super(MISSING_NAME, null); } // public final String toString() { // return "<missing>"; // } public final String getName() { return MISSING_NAME; } public final ResolvedMember[] getDeclaredFields() { return ResolvedMember.NONE; } public final ResolvedMember[] getDeclaredMethods() { return ResolvedMember.NONE; } public final ResolvedTypeX[] getDeclaredInterfaces() { return ResolvedTypeX.NONE; } public final ResolvedMember[] getDeclaredPointcuts() { return ResolvedMember.NONE; } public final ResolvedTypeX getSuperclass() { return null; } public final int getModifiers() { return 0; } public final boolean isAssignableFrom(TypeX other) { return false; } public final boolean isCoerceableFrom(TypeX other) { return false; } public boolean needsNoConversionFrom(TypeX other) { return false; } public ISourceContext getSourceContext() { return null; } } /** return null if not found */ public ResolvedMember lookupMemberNoSupers(Member member) { if (member.getKind() == Member.FIELD) { return lookupMember(member, getDeclaredFields()); } else { // assert member.getKind() == Member.METHOD || member.getKind() == Member.CONSTRUCTOR return lookupMember(member, getDeclaredMethods()); } } protected List interTypeMungers = new ArrayList(0); public List getInterTypeMungers() { return interTypeMungers; } private static ResolvedTypeX getOutermostType(ResolvedTypeX t) { TypeX dec = t.getDeclaringType(); if (dec == null) return t; return getOutermostType(dec.resolve(t.getWorld())); } public static boolean isVisible(int modifiers, ResolvedTypeX targetType, ResolvedTypeX fromType) { //System.err.println("mod: " + modifiers + ", " + targetType + " and " + fromType); if (Modifier.isPublic(modifiers)) { return true; } else if (Modifier.isPrivate(modifiers)) { return getOutermostType(targetType).equals(getOutermostType(fromType)); } else if (Modifier.isProtected(modifiers)) { return samePackage(targetType, fromType) || targetType.isAssignableFrom(fromType); } else { // package-visible return samePackage(targetType, fromType); } } private static boolean samePackage( ResolvedTypeX targetType, ResolvedTypeX fromType) { String p1 = targetType.getPackageName(); String p2 = fromType.getPackageName(); if (p1 == null) return p2 == null; if (p2 == null) return false; return p1.equals(p2); } public void addInterTypeMunger(ConcreteTypeMunger munger) { ResolvedMember sig = munger.getSignature(); if (sig == null || munger.getMunger() == null || munger.getMunger().getKind() == ResolvedTypeMunger.PrivilegedAccess) { interTypeMungers.add(munger); return; } //System.err.println("add: " + munger + " to " + this.getClassName() + " with " + interTypeMungers); if (sig.getKind() == Member.METHOD) { if (!compareToExistingMembers(munger, getMethods())) return; if (this.isInterface()) { if (!compareToExistingMembers(munger, Arrays.asList(world.resolve(OBJECT).getDeclaredMethods()).iterator())) return; } } else if (sig.getKind() == Member.FIELD) { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredFields()).iterator())) return; } else { if (!compareToExistingMembers(munger, Arrays.asList(getDeclaredMethods()).iterator())) return; } // now compare to existingMungers for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger existingMunger = (ConcreteTypeMunger)i.next(); if (conflictingSignature(existingMunger.getSignature(), munger.getSignature())) { //System.err.println("match " + munger + " with " + existingMunger); if (isVisible(munger.getSignature().getModifiers(), munger.getAspectType(), existingMunger.getAspectType())) { //System.err.println(" is visible"); int c = compareMemberPrecedence(sig, existingMunger.getSignature()); if (c == 0) { c = getWorld().comparePrecedence(munger.getAspectType(), existingMunger.getAspectType()); } //System.err.println(" compare: " + c); if (c < 0) { // the existing munger dominates the new munger checkLegalOverride(munger.getSignature(), existingMunger.getSignature()); return; } else if (c > 0) { // the new munger dominates the existing one checkLegalOverride(existingMunger.getSignature(), munger.getSignature()); i.remove(); break; } else { interTypeConflictError(munger, existingMunger); interTypeConflictError(existingMunger, munger); return; } } } } //System.err.println("adding: " + munger + " to " + this); interTypeMungers.add(munger); } //??? returning too soon private boolean compareToExistingMembers(ConcreteTypeMunger munger, Iterator existingMembers) { ResolvedMember sig = munger.getSignature(); while (existingMembers.hasNext()) { ResolvedMember existingMember = (ResolvedMember)existingMembers.next(); if (conflictingSignature(existingMember, munger.getSignature())) { //System.err.println("conflict: " + existingMember + " with " + munger); //System.err.println(munger.getSourceLocation() + ", " + munger.getSignature() + ", " + munger.getSignature().getSourceLocation()); if (isVisible(existingMember.getModifiers(), this, munger.getAspectType())) { int c = compareMemberPrecedence(sig, existingMember); //System.err.println(" c: " + c); if (c < 0) { // existingMember dominates munger checkLegalOverride(munger.getSignature(), existingMember); return false; } else if (c > 0) { // munger dominates existingMember checkLegalOverride(existingMember, munger.getSignature()); //interTypeMungers.add(munger); //??? might need list of these overridden abstracts continue; } else { if (this instanceof BcelObjectType) return false; //XXX ignores separate comp getWorld().getMessageHandler().handleMessage( MessageUtil.error("inter-type declaration from " + munger.getAspectType().getName() + " conflicts with existing member: " + existingMember, munger.getSourceLocation()) ); } } else { //interTypeMungers.add(munger); } //return; } } return true; } public boolean checkLegalOverride(ResolvedMember parent, ResolvedMember child) { //System.err.println("check: " + child.getDeclaringType() + " overrides " + parent.getDeclaringType()); if (!parent.getReturnType().equals(child.getReturnType())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " return types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } if (parent.getKind() == Member.POINTCUT) { TypeX[] pTypes = parent.getParameterTypes(); TypeX[] cTypes = child.getParameterTypes(); if (!Arrays.equals(pTypes, cTypes)) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " parameter types don't match", child.getSourceLocation(), parent.getSourceLocation()); return false; } } //System.err.println("check: " + child.getModifiers() + " more visible " + parent.getModifiers()); if (isMoreVisible(parent.getModifiers(), child.getModifiers())) { world.showMessage(IMessage.ERROR, "can't override " + parent + " with " + child + " visibility is reduced", child.getSourceLocation(), parent.getSourceLocation()); return false; } // check declared exceptions ResolvedTypeX[] childExceptions = world.resolve(child.getExceptions()); ResolvedTypeX[] parentExceptions = world.resolve(parent.getExceptions()); ResolvedTypeX runtimeException = world.resolve("java.lang.RuntimeException"); ResolvedTypeX error = world.resolve("java.lang.Error"); outer: for (int i=0, leni = childExceptions.length; i < leni; i++) { //System.err.println("checking: " + childExceptions[i]); if (runtimeException.isAssignableFrom(childExceptions[i])) continue; if (error.isAssignableFrom(childExceptions[i])) continue; for (int j = 0, lenj = parentExceptions.length; j < lenj; j++) { if (parentExceptions[j].isAssignableFrom(childExceptions[i])) continue outer; } world.showMessage(IMessage.ERROR, "overriden method doesn't throw " + childExceptions[i].getName(), child.getSourceLocation(), null); return false; } return true; } private int compareMemberPrecedence(ResolvedMember m1, ResolvedMember m2) { //if (!m1.getReturnType().equals(m2.getReturnType())) return 0; if (Modifier.isAbstract(m1.getModifiers())) return -1; if (Modifier.isAbstract(m2.getModifiers())) return +1; if (m1.getDeclaringType().equals(m2.getDeclaringType())) return 0; ResolvedTypeX t1 = m1.getDeclaringType().resolve(world); ResolvedTypeX t2 = m2.getDeclaringType().resolve(world); if (t1.isAssignableFrom(t2)) { return -1; } if (t2.isAssignableFrom(t1)) { return +1; } return 0; } public static boolean isMoreVisible(int m1, int m2) { if (Modifier.isPrivate(m1)) return false; if (isPackage(m1)) return Modifier.isPrivate(m2); if (Modifier.isProtected(m1)) return /* private package */ (Modifier.isPrivate(m2) || isPackage(m2)); if (Modifier.isPublic(m1)) return /* private package protected */ ! Modifier.isPublic(m2); throw new RuntimeException("bad modifier: " + m1); } private static boolean isPackage(int i) { return (0 == (i & (Modifier.PUBLIC | Modifier.PRIVATE | Modifier.PROTECTED))); } private void interTypeConflictError( ConcreteTypeMunger m1, ConcreteTypeMunger m2) { //XXX this works only if we ignore separate compilation issues if (this instanceof BcelObjectType) return; //System.err.println("conflict at " + m2.getSourceLocation()); getWorld().showMessage(IMessage.ERROR, "intertype declaration from " + m1.getAspectType().getName() + " conflicts with intertype declaration: " + m2.getSignature() + " from " + m2.getAspectType().getName(), m2.getSourceLocation(), getSourceLocation()); } public ResolvedMember lookupSyntheticMember(Member member) { //??? horribly inefficient //for (Iterator i = //System.err.println("lookup " + member + " in " + interTypeMungers); for (Iterator i = interTypeMungers.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); ResolvedMember ret = m.getMatchingSyntheticMember(member); if (ret != null) { //System.err.println(" found: " + ret); return ret; } } return null; } public void clearInterTypeMungers() { interTypeMungers = new ArrayList(); } public boolean isTopmostImplementor(ResolvedTypeX interfaceType) { if (isInterface()) return false; if (!interfaceType.isAssignableFrom(this)) return false; // check that I'm truly the topmost implementor if (interfaceType.isAssignableFrom(this.getSuperclass())) { return false; } return true; } public List getExposedPointcuts() { List ret = new ArrayList(); if (getSuperclass() != null) ret.addAll(getSuperclass().getExposedPointcuts()); for (Iterator i = Arrays.asList(getDeclaredInterfaces()).iterator(); i.hasNext(); ) { ResolvedTypeX t = (ResolvedTypeX)i.next(); addPointcutsResolvingConflicts(ret, Arrays.asList(t.getDeclaredPointcuts()), false); } addPointcutsResolvingConflicts(ret, Arrays.asList(getDeclaredPointcuts()), true); for (Iterator i = ret.iterator(); i.hasNext(); ) { ResolvedPointcutDefinition inherited = (ResolvedPointcutDefinition)i.next(); if (inherited.isAbstract()) { if (!this.isAbstract()) { getWorld().showMessage(IMessage.ERROR, "inherited abstract pointcut " + inherited.getSignature() + " is not made concrete in " + this.getName(), inherited.getSourceLocation(), this.getSourceLocation()); } } } return ret; } private void addPointcutsResolvingConflicts(List acc, List added, boolean isOverriding) { for (Iterator i = added.iterator(); i.hasNext();) { ResolvedPointcutDefinition toAdd = (ResolvedPointcutDefinition) i.next(); for (Iterator j = acc.iterator(); j.hasNext();) { ResolvedPointcutDefinition existing = (ResolvedPointcutDefinition) j.next(); if (existing == toAdd) continue; if (!isVisible(existing.getModifiers(), existing.getDeclaringType().resolve(getWorld()), this)) { continue; } if (conflictingSignature(existing, toAdd)) { if (isOverriding) { checkLegalOverride(existing, toAdd); j.remove(); } else { getWorld().showMessage( IMessage.ERROR, "conflicting inherited pointcuts in " + this.getName() + toAdd.getSignature(), existing.getSourceLocation(), toAdd.getSourceLocation()); j.remove(); } } } acc.add(toAdd); } } public ISourceLocation getSourceLocation() { return null; } public boolean isExposedToWeaver() { return false; } }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
weaver/src/org/aspectj/weaver/Shadow.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver; import java.io.*; import java.lang.reflect.Modifier; import java.util.*; import org.apache.bcel.Constants; import org.apache.bcel.classfile.Field; import org.aspectj.weaver.ast.Var; import org.aspectj.weaver.patterns.IScope; import org.aspectj.bridge.*; import org.aspectj.bridge.SourceLocation; import org.aspectj.lang.JoinPoint; import org.aspectj.util.*; /* * The superclass of anything representing a the shadow of a join point. A shadow represents * some bit of code, and encompasses both entry and exit from that code. All shadows have a kind * and a signature. */ public abstract class Shadow { private final Kind kind; private final Member signature; protected final Shadow enclosingShadow; protected List mungers = new ArrayList(1); // ---- protected Shadow(Kind kind, Member signature, Shadow enclosingShadow) { this.kind = kind; this.signature = signature; this.enclosingShadow = enclosingShadow; } // ---- public abstract World getIWorld(); /** * could this(*) pcd ever match */ public final boolean hasThis() { if (getKind().neverHasThis()) { return false; } else if (getKind().isEnclosingKind()) { return !getSignature().isStatic(); } else if (enclosingShadow == null) { return false; } else { return enclosingShadow.hasThis(); } } /** * the type of the this object here * * @throws IllegalStateException if there is no this here */ public final TypeX getThisType() { if (!hasThis()) throw new IllegalStateException("no this"); if (getKind().isEnclosingKind()) { return getSignature().getDeclaringType(); } else { return enclosingShadow.getThisType(); } } /** * a var referencing this * * @throws IllegalStateException if there is no target here */ public abstract Var getThisVar(); /** * could target(*) pcd ever match */ public final boolean hasTarget() { if (getKind().neverHasTarget()) { return false; } else if (getKind().isTargetSameAsThis()) { return hasThis(); } else { return !getSignature().isStatic(); } } /** * the type of the target object here * * @throws IllegalStateException if there is no target here */ public final TypeX getTargetType() { if (!hasTarget()) throw new IllegalStateException("no target"); return getSignature().getDeclaringType(); } /** * a var referencing the target * * @throws IllegalStateException if there is no target here */ public abstract Var getTargetVar(); public TypeX[] getArgTypes() { if (getKind() == FieldSet) return new TypeX[] { getSignature().getReturnType() }; return getSignature().getParameterTypes(); } public TypeX getArgType(int arg) { if (getKind() == FieldSet) return getSignature().getReturnType(); return getSignature().getParameterTypes()[arg]; } public int getArgCount() { if (getKind() == FieldSet) return 1; return getSignature() .getParameterTypes().length; } public abstract TypeX getEnclosingType(); public abstract Var getArgVar(int i); public abstract Var getThisJoinPointVar(); public abstract Var getThisJoinPointStaticPartVar(); public abstract Var getThisEnclosingJoinPointStaticPartVar(); public abstract Member getEnclosingCodeSignature(); /** returns the kind of shadow this is, representing what happens under this shadow */ public Kind getKind() { return kind; } /** returns the signature of the thing under this shadow */ public Member getSignature() { return signature; } public TypeX getReturnType() { if (kind == ConstructorCall) return getSignature().getDeclaringType(); else if (kind == FieldSet) return ResolvedTypeX.VOID; return getSignature().getReturnType(); } /** * These names are the ones that will be returned by thisJoinPoint.getKind() * Those need to be documented somewhere */ public static final Kind MethodCall = new Kind(JoinPoint.METHOD_CALL, 1, true); public static final Kind ConstructorCall = new Kind(JoinPoint.CONSTRUCTOR_CALL, 2, true); public static final Kind MethodExecution = new Kind(JoinPoint.METHOD_EXECUTION, 3, false); public static final Kind ConstructorExecution = new Kind(JoinPoint.CONSTRUCTOR_EXECUTION, 4, false); public static final Kind FieldGet = new Kind(JoinPoint.FIELD_GET, 5, true); public static final Kind FieldSet = new Kind(JoinPoint.FIELD_SET, 6, true); public static final Kind StaticInitialization = new Kind(JoinPoint.STATICINITIALIZATION, 7, false); public static final Kind PreInitialization = new Kind(JoinPoint.PREINTIALIZATION, 8, false); public static final Kind AdviceExecution = new Kind(JoinPoint.ADVICE_EXECUTION, 9, false); public static final Kind Initialization = new Kind(JoinPoint.INITIALIZATION, 10, false); public static final Kind ExceptionHandler = new Kind(JoinPoint.EXCEPTION_HANDLER, 11, true); /** A type-safe enum representing the kind of shadows */ public static final class Kind extends TypeSafeEnum { private boolean argsOnStack; //XXX unused public Kind(String name, int key, boolean argsOnStack) { super(name, key); this.argsOnStack = argsOnStack; } public String toLegalJavaIdentifier() { return getName().replace('-', '_'); } public boolean argsOnStack() { return !isTargetSameAsThis(); } // !!! this is false for handlers! public boolean allowsExtraction() { return true; } // XXX revisit along with removal of priorities public boolean hasHighPriorityExceptions() { return !isTargetSameAsThis(); } /** * These are all the shadows that contains other shadows within them and * are often directly associated with methods. */ public boolean isEnclosingKind() { return this == MethodExecution || this == ConstructorExecution || this == AdviceExecution || this == StaticInitialization || this == Initialization; } public boolean isTargetSameAsThis() { return this == MethodExecution || this == ConstructorExecution || this == StaticInitialization || this == PreInitialization || this == AdviceExecution || this == Initialization; } public boolean neverHasTarget() { return this == ConstructorCall || this == ExceptionHandler || this == PreInitialization || this == StaticInitialization; } public boolean neverHasThis() { return this == PreInitialization || this == StaticInitialization; } public String getSimpleName() { int dash = getName().lastIndexOf('-'); if (dash == -1) return getName(); else return getName().substring(dash+1); } public static Kind read(DataInputStream s) throws IOException { int key = s.readByte(); switch(key) { case 1: return MethodCall; case 2: return ConstructorCall; case 3: return MethodExecution; case 4: return ConstructorExecution; case 5: return FieldGet; case 6: return FieldSet; case 7: return StaticInitialization; case 8: return PreInitialization; case 9: return AdviceExecution; case 10: return Initialization; case 11: return ExceptionHandler; } throw new BCException("unknown kind: " + key); } } public void addMunger(ShadowMunger munger) { this.mungers.add(munger); } public final void implement() { sortMungers(); if (mungers == null) return; prepareForMungers(); implementMungers(); } private void sortMungers() { List sorted = PartialOrder.sort(mungers); if (sorted == null) { // this means that we have circular dependencies for (Iterator i = mungers.iterator(); i.hasNext(); ) { ShadowMunger m = (ShadowMunger)i.next(); getIWorld().getMessageHandler().handleMessage( MessageUtil.error("circular dependency at " + this, m.getSourceLocation())); } } mungers = sorted; } /** Prepare the shadow for implementation. After this is done, the shadow * should be in such a position that each munger simply needs to be implemented. */ protected void prepareForMungers() { throw new RuntimeException("Generic shadows cannot be prepared"); } /** Actually implement the (non-empty) mungers associated with this shadow */ private void implementMungers() { World world = getIWorld(); for (Iterator iter = mungers.iterator(); iter.hasNext();) { ShadowMunger munger = (ShadowMunger) iter.next(); munger.implementOn(this); if (world.getModel() != null) { System.err.println("munger: " + munger + " on " + this); AsmAdaptor.noteMunger(world.getModel(), this, munger); } } } public String makeReflectiveFactoryString() { return null; //XXX } public abstract SourceLocation getSourceLocation(); // ---- utility public String toString() { return getKind() + "(" + getSignature() + ")"; // + getSourceLines(); } // ---- type access methods }
29,186
Bug 29186 ajc -emacssym chokes on pointcut that includes an intertype method
null
resolved fixed
c1260e6
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-14T21:36:18Z
2003-01-09T02:40:00Z
weaver/src/org/aspectj/weaver/bcel/BcelWeaver.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.weaver.bcel; import java.io.*; import java.util.*; import java.util.zip.*; import org.apache.bcel.classfile.*; import org.apache.bcel.classfile.JavaClass; import org.aspectj.bridge.IMessage; import org.aspectj.util.FileUtil; import org.aspectj.weaver.*; public class BcelWeaver implements IWeaver { private BcelWorld world; private CrosscuttingMembersSet xcutSet; public BcelWeaver(BcelWorld world) { super(); this.world = world; this.xcutSet = world.getCrosscuttingMembersSet(); } public BcelWeaver() { this(new BcelWorld()); } // ---- fields private Map sourceJavaClasses = new HashMap(); /* String -> UnwovenClassFile */ private List addedClasses = new ArrayList(); /* List<UnovenClassFile> */ private List deletedTypenames = new ArrayList(); /* List<String> */ private boolean needToReweaveWorld = false; private List shadowMungerList = null; // setup by prepareForWeave private List typeMungerList = null; // setup by prepareForWeave private ZipOutputStream zipOutputStream; // ---- // only called for testing public void setShadowMungers(List l) { shadowMungerList = l; } public void addLibraryAspect(String aspectName) { ResolvedTypeX type = world.resolve(aspectName); System.out.println("type: " + type + " for " + aspectName); if (type.isAspect()) { xcutSet.addOrReplaceAspect(type); } else { throw new RuntimeException("unimplemented"); } } public void addLibraryJarFile(File inFile) throws IOException { ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered List addedAspects = new ArrayList(); while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; } ClassParser parser = new ClassParser(new ByteArrayInputStream(FileUtil.readAsByteArray(inStream)), entry.getName()); JavaClass jc = parser.parse(); inStream.closeEntry(); ResolvedTypeX type = world.addSourceObjectType(jc); if (type.isAspect()) { addedAspects.add(type); } } inStream.close(); for (Iterator i = addedAspects.iterator(); i.hasNext();) { ResolvedTypeX aspectX = (ResolvedTypeX) i.next(); xcutSet.addOrReplaceAspect(aspectX); } } /** Adds all class files in the jar */ public void addJarFile(File inFile, File outDir) throws IOException { needToReweaveWorld = true; //System.err.println("adding jar: " + inFile); ZipInputStream inStream = new ZipInputStream(new FileInputStream(inFile)); //??? buffered while (true) { ZipEntry entry = inStream.getNextEntry(); if (entry == null) break; if (entry.isDirectory() || !entry.getName().endsWith(".class")) { continue; //??? need to pass other things along untouched // outStream.putNextEntry(entry); // outStream.write(Utility.getByteArray(inStream)); // outStream.closeEntry(); // return; } //System.err.println("adding class: " + entry.getName()); byte[] bytes = FileUtil.readAsByteArray(inStream); String filename = entry.getName(); UnwovenClassFile classFile = new UnwovenClassFile(new File(outDir, filename).getAbsolutePath(), bytes); inStream.closeEntry(); this.addClassFile(classFile); } inStream.close(); } /** Should be addOrReplace */ public void addClassFile(UnwovenClassFile classFile) { addedClasses.add(classFile); sourceJavaClasses.put(classFile.getClassName(), classFile); world.addSourceObjectType(classFile.getJavaClass()); } public void deleteClassFile(String typename) { deletedTypenames.add(typename); sourceJavaClasses.remove(typename); world.deleteSourceObjectType(TypeX.forName(typename)); } // ---- weave preparation public void prepareForWeave() { needToReweaveWorld = false; // update mungers for (Iterator i = addedClasses.iterator(); i.hasNext(); ) { UnwovenClassFile jc = (UnwovenClassFile)i.next(); String name = jc.getClassName(); ResolvedTypeX type = world.resolve(name); //System.err.println("added: " + type + " aspect? " + type.isAspect()); if (type.isAspect()) { needToReweaveWorld |= xcutSet.addOrReplaceAspect(type); } } for (Iterator i = deletedTypenames.iterator(); i.hasNext(); ) { String name = (String)i.next(); if (xcutSet.deleteAspect(TypeX.forName(name))) needToReweaveWorld = true; } shadowMungerList = xcutSet.getShadowMungers(); typeMungerList = xcutSet.getTypeMungers(); //XXX this gets us a stable (but completely meaningless) order Collections.sort( shadowMungerList, new Comparator() { public int compare(Object o1, Object o2) { return o1.toString().compareTo(o2.toString()); } }); } public void dumpUnwoven(File file) throws IOException { BufferedOutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); dumpUnwoven(); zipOutputStream.close(); //this flushes and closes the acutal file } public void dumpUnwoven() throws IOException { Collection filesToDump = new HashSet(sourceJavaClasses.values()); for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); dumpUnchanged(classFile); } } // ---- weaving public Collection weave(File file) throws IOException { OutputStream os = FileUtil.makeOutputStream(file); this.zipOutputStream = new ZipOutputStream(os); Collection c = weave(); zipOutputStream.close(); //this flushes and closes the acutal file return c; } public Collection weave() throws IOException { prepareForWeave(); Collection filesToWeave; if (needToReweaveWorld) { filesToWeave = sourceJavaClasses.values(); } else { filesToWeave = addedClasses; } Collection wovenClassNames = new ArrayList(); world.showMessage(IMessage.INFO, "might need to weave " + filesToWeave + "(world=" + needToReweaveWorld + ")", null, null); //System.err.println("typeMungers: " + typeMungerList); // clear all state from files we'll be reweaving for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = (BcelObjectType) world.resolve(className); classType.resetState(); } //XXX this isn't quite the right place for this... for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); ResolvedTypeX onType = world.resolve(className); weave(onType); } // first weave into aspects for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = (BcelObjectType) world.resolve(className); if (classType.isAspect()) { weave(classFile, classType); wovenClassNames.add(className); } } // then weave into non-aspects for (Iterator i = filesToWeave.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); String className = classFile.getClassName(); BcelObjectType classType = (BcelObjectType) world.resolve(className); if (! classType.isAspect()) { weave(classFile, classType); wovenClassNames.add(className); } } if (zipOutputStream != null && !needToReweaveWorld) { Collection filesToDump = new HashSet(sourceJavaClasses.values()); filesToDump.removeAll(filesToWeave); for (Iterator i = filesToDump.iterator(); i.hasNext(); ) { UnwovenClassFile classFile = (UnwovenClassFile)i.next(); dumpUnchanged(classFile); } } addedClasses = new ArrayList(); deletedTypenames = new ArrayList(); return wovenClassNames; } private void weave(ResolvedTypeX onType) { onType.clearInterTypeMungers(); for (Iterator i = typeMungerList.iterator(); i.hasNext(); ) { ConcreteTypeMunger m = (ConcreteTypeMunger)i.next(); if (m.matches(onType)) { onType.addInterTypeMunger(m); } } } // non-private for testing LazyClassGen weave(UnwovenClassFile classFile, BcelObjectType classType) throws IOException { JavaClass javaClass = classType.getJavaClass(); List shadowMungers = fastMatch(shadowMungerList, javaClass); List typeMungers = fastMatch(classType.getInterTypeMungers(), javaClass); LazyClassGen clazz = null; if (shadowMungers.size() > 0 || typeMungers.size() > 0 || classType.isAspect()) { clazz = classType.getLazyClassGen(); //System.err.println("got lazy gen: " + clazz + ", " + clazz.getWeaverState()); try { boolean isChanged = BcelClassWeaver.weave(world, clazz, shadowMungers, typeMungers); if (isChanged) { dump(classFile, clazz); return clazz; } } catch (RuntimeException re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } catch (Error re) { System.err.println("trouble in: "); clazz.print(System.err); throw re; } } dumpUnchanged(classFile); return clazz; } // ---- writing private void dumpUnchanged(UnwovenClassFile classFile) throws IOException { if (zipOutputStream != null) { writeZipEntry(getEntryName(classFile.getJavaClass().getClassName()), classFile.getBytes()); } else { classFile.writeUnchangedBytes(); } } private String getEntryName(String className) { //XXX what does bcel's getClassName do for inner names return className.replace('.', '/') + ".class"; } private void dump(UnwovenClassFile classFile, LazyClassGen clazz) throws IOException { if (zipOutputStream != null) { String mainClassName = classFile.getJavaClass().getClassName(); writeZipEntry(getEntryName(mainClassName), clazz.getJavaClass().getBytes()); if (!clazz.getChildClasses().isEmpty()) { for (Iterator i = clazz.getChildClasses().iterator(); i.hasNext();) { UnwovenClassFile.ChildClass c = (UnwovenClassFile.ChildClass) i.next(); writeZipEntry(getEntryName(mainClassName + "$" + c.name), c.bytes); } } } else { classFile.writeWovenBytes( clazz.getJavaClass().getBytes(), clazz.getChildClasses() ); } } private void writeZipEntry(String name, byte[] bytes) throws IOException { ZipEntry newEntry = new ZipEntry(name); //??? get compression scheme right zipOutputStream.putNextEntry(newEntry); zipOutputStream.write(bytes); zipOutputStream.closeEntry(); } // ---- fast matching // boolean fastMatch(JavaClass jc) { // ConstantPool pool = jc.getConstantPool(); // for (int i=0, len=pool.getLength(); i < len; i++) { // Constant c = pool.getConstant(i); // if (c instanceof ConstantNameAndType) { // ConstantNameAndType nt = (ConstantNameAndType)c; // if (nt.getName(pool).equals("toShortString")) { // //System.out.println("found in " + jc); // return true; // } // } // } // return false; // } //XXX need to implement a real fast-match here private List fastMatch(List list, JavaClass javaClass) { if (list == null) return Collections.EMPTY_LIST; return list; } }
29,662
Bug 29662 VerifyError on accessing objects not accessible to the weaver: Incompatible object argument for invokespecial
I use aspectj1.1b4 (the version list box did not let me choose, it offered only "unspecified"). Compiling the program below yields a warning that a affected type is not exposed to the weaver. Running it crashes the program with this message: "java.lang.VerifyError: (class: VerifyError, method: finalize signature: ()V) Incompatible object argument for invokespecial" public class VerifyError { public static void main(String args[]) { VerifyError ve = new VerifyError(); } protected void finalize() {} } aspect FinalizeContract { pointcut finalizeCall(Object o): this(Object+) && this(o) && execution(void finalize()); void around(Object o) throws Throwable: finalizeCall(o) { super.finalize(); proceed(o); } }
resolved fixed
2d297d7
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-21T23:58:42Z
2003-01-16T20:46:40Z
tests/bugs/AroundAccess.java
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajbrowser/src/org/aspectj/tools/ajbrowser/BrowserProperties.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.tools.ajbrowser; import java.util.*; import java.io.*; import org.aspectj.ajde.*; import org.aspectj.ajde.ui.*; public class BrowserProperties implements ProjectPropertiesAdapter { UserPreferencesAdapter preferencesAdapter = null; public BrowserProperties(UserPreferencesAdapter preferencesAdapter) { this.preferencesAdapter = preferencesAdapter; } public String getLastOpenSourceFilePath() { return preferencesAdapter.getProjectPreference("editor.lastOpenFile"); } public void setLastOpenSourceFilePath(String value) { preferencesAdapter.setProjectPreference("editor.lastOpenFile",value); } public String getLastOpenSourceLineNumber() { return preferencesAdapter.getProjectPreference("editor.lastOpenLineNumber"); } public void setLastOpenSourceLineNumber(String value) { preferencesAdapter.setProjectPreference("editor.lastOpenLineNumber",value); } public List getBuildConfigFiles() { return BrowserManager.getDefault().getConfigFiles(); } public String getDefaultBuildConfigFile() { return null; } public String getLastActiveBuildConfigFile() { return null; } public String getProjectName() { return null; } public String getClassToExecute() { return preferencesAdapter.getProjectPreference("runtime.mainClass"); } public void setClassToExecute(String mainClass) { preferencesAdapter.setProjectPreference("runtime.mainClass", mainClass); } public String getRootProjectDir() { return new File(Ajde.getDefault().getConfigurationManager().getActiveConfigFile()).getParent(); } public String getExecutionArgs() { return null; } public List getProjectSourceFiles() { return null; } public String getVmArgs() { return null; } public String getProjectSourcePath() { return null; } public String getBootClasspath() { return System.getProperty("sun.boot.class.path"); } public void setAjcOptions(String flags) { preferencesAdapter.setProjectPreference("build.flags", flags); } public String getAjcOptions() { return preferencesAdapter.getProjectPreference("build.flags"); } public String getOutputPath() { String outputPath = preferencesAdapter.getProjectPreference("build.outputpath"); if (outputPath == null) { return "."; } else { return outputPath; } } public void setOutputPath(String path) { preferencesAdapter.setProjectPreference("build.outputpath", path); } public String getUserClasspath() { return preferencesAdapter.getProjectPreference("build.classpath"); } public String getClasspath() { String systemPath = System.getProperty("java.class.path", "."); String userPath = preferencesAdapter.getProjectPreference("build.classpath"); if (userPath != null && userPath.trim().length() != 0) { return userPath; } else { return systemPath; } } public void setClasspath(String path) { preferencesAdapter.setProjectPreference("build.classpath", path); } public String getAjcWorkingDir() { String workingDir = preferencesAdapter.getProjectPreference("build.workingdir"); if (workingDir == null || workingDir.equals(getOutputPath())) { return getOutputPath() + "./ajworkingdir"; } else { return workingDir; } } public void setAjcWorkingDir(String path) { preferencesAdapter.setProjectPreference("build.workingdir", path); } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/src/org/aspectj/ajde/BuildOptionsAdapter.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; /** * When a particular option is not set its documented default is used. */ public interface BuildOptionsAdapter { /** * Use javac to generate .class files. The default is "false". */ public boolean getUseJavacMode(); /** * Only relevant with Use Javac or Preprocess modes. Specify where to place * intermediate .java files. The default is "workingdir". */ public String getWorkingOutputPath(); /** * Generate regular Java code into the Working OutputPath. Don't try to generate * any .class files. The default is "false". */ public boolean getPreprocessMode(); /** * Specify character encoding used by source files. The default is the current * JVM's default. */ public String getCharacterEncoding(); /** * Support assertions as defined in JLS-1.4. The default is "false". */ public boolean getSourceOnePointFourMode(); /** * Be extra-lenient in interpreting the Java specification. The default is "false", * i.e. "regular" mode. */ public boolean getLenientSpecMode(); /** * Be extra-strict in interpreting the Java specification. The default is "false", * i.e. "regular" mode. */ public boolean getStrictSpecMode(); /** * Make the use of some features from pre-1.0 versions of AspectJ be warnings to ease * porting of old code. The default is "false". */ public boolean getPortingMode(); /** * The non-standard, typically prefaced with -X when used with a command line compiler. * The default is no non-standard options. */ public String getNonStandardOptions(); }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/src/org/aspectj/ajde/ProjectPropertiesAdapter.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import java.util.List; /** * @author Mik Kersten */ public interface ProjectPropertiesAdapter { public String getProjectName(); public String getRootProjectDir(); public List getBuildConfigFiles(); public String getDefaultBuildConfigFile(); /** * @return The last selected build configuration for this project. If no selection * is present the default build config file for this project is returned. */ public String getLastActiveBuildConfigFile(); public List getProjectSourceFiles(); public String getProjectSourcePath(); public String getClasspath(); public String getOutputPath(); public String getAjcWorkingDir(); // @todo: move to build options public String getBootClasspath(); // @todo: move all below to execution options public String getClassToExecute(); public String getExecutionArgs(); public String getVmArgs(); }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/src/org/aspectj/ajde/internal/AspectJBuildManager.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde.internal; import java.io.*; import java.util.*; import org.aspectj.ajde.*; import org.aspectj.asm.StructureNode; import org.aspectj.bridge.*; import org.aspectj.util.ConfigParser; /** * Responsible for the build process, including compiler invocation, threading, and error * reporting. * * @author Mik Kersten */ public class AspectJBuildManager implements BuildManager { private CompilerAdapter compiler = null; private TaskListManager compilerMessages = null; private BuildProgressMonitor progressMonitor = null; private BuildOptionsAdapter buildOptions = null; private ArrayList compilerListeners = new ArrayList(); private String configFile = ""; private int lastCompileTime = 50; private boolean buildStrucutreOnly = false; public AspectJBuildManager( TaskListManager compilerMessages, BuildProgressMonitor progressMonitor, BuildOptionsAdapter buildOptions) { this.compilerMessages = compilerMessages; this.progressMonitor = progressMonitor; this.buildOptions = buildOptions; this.compiler = new CompilerAdapter(); } public void build() { if (Ajde.getDefault().getConfigurationManager().getActiveConfigFile() == null) { Ajde.getDefault().getErrorHandler().handleWarning("Nothing to compile, please add a \".lst\" file."); return; } else { build(Ajde.getDefault().getConfigurationManager().getActiveConfigFile()); } } public void buildStructure() { buildStrucutreOnly = true; build(); } public void build(String configFile) { buildStrucutreOnly = false; if (configFile == null) { Ajde.getDefault().getErrorHandler().handleWarning("Please add a configuration file to compile."); } else { this.configFile = configFile; CompilerThread compilerThread = new CompilerThread(); compilerThread.start(); } } public void abortBuild() { if (compiler != null) { compiler.requestCompileExit(); } } // public CompilerAdapter getCurrCompiler() { // return currCompiler; // } public boolean isStructureDirty() { if (compiler != null) { return compiler.isStructureDirty(); } else { return false; } } public void setStructureDirty(boolean structureDirty) { if (compiler != null) { compiler.setStructureDirty(structureDirty); } } public void addListener(BuildListener compilerListener) { compilerListeners.add(compilerListener); } public void removeListener(BuildListener compilerListener) { compilerListeners.remove(compilerListener); } private void notifyCompileFinished(String configFile, int buildTime, boolean succeeded, boolean warnings) { Ajde.getDefault().logEvent("build finished, succeeded: " + succeeded); for (Iterator it = compilerListeners.iterator(); it.hasNext(); ) { ((BuildListener)it.next()).compileFinished(configFile, buildTime, succeeded, warnings); } } private void notifyCompileStarted(String configFile) { Ajde.getDefault().logEvent("build started: " + configFile); for (Iterator it = compilerListeners.iterator(); it.hasNext(); ) { ((BuildListener)it.next()).compileStarted(configFile); } } private void notifyCompileAborted(String configFile, String message) { for (Iterator it = compilerListeners.iterator(); it.hasNext(); ) { ((BuildListener)it.next()).compileAborted(configFile, message); } } /** * @todo use structured error messages instead */ private void displayMessages(CompileResult compileResult) { String[] descriptions = compileResult.getDescriptions(); String[] files = compileResult.getfiles(); Integer[] lineNumbers = compileResult.getLineNumbers(); if (descriptions.length == 0 && compileResult.getResult().trim() != "") { //compilerMessages.addSourcelineTask(compileResult.getResult(), "", 0, 0, TaskListManager.ERROR_MESSAGE); compilerMessages.addSourcelineTask( compileResult.getResult(), new SourceLocation(null, 0, 0), IMessage.ERROR); return; } for ( int i = 0; i < descriptions.length && i < files.length && i < lineNumbers.length; i++ ) { String message = ""; if (files[i] != "") { message += "\"" + files[i] + "\": "; } if (lineNumbers[i].intValue() != -1 && lineNumbers[i].intValue() != 0) { message += descriptions[i] + ", at line: " + lineNumbers[i]; } else { message += descriptions[i]; } if (message.startsWith("Nothing to compile.")) { message = "Nothing to compile, please select the project, package(s), or class(es) to compile."; } IMessage.Kind kind = IMessage.ERROR; if (descriptions[i].endsWith("(warning)")) kind = IMessage.WARNING; compilerMessages.addSourcelineTask( message, new SourceLocation(new File(files[i]), lineNumbers[i].intValue(), 0), kind); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( files[i], lineNumbers[i].intValue() ); if (node != null) { node.setMessage(new Message(message, kind, null, null)); } } } /** * @todo clean up this mess. */ public class CompilerThread extends Thread { public void run() { boolean succeeded = true; boolean warnings = false; try { long timeStart = System.currentTimeMillis(); notifyCompileStarted(configFile); progressMonitor.start(configFile); compilerMessages.clearTasks(); Ajde.getDefault().logEvent("building with options: " + getFormattedOptionsString(buildOptions, Ajde.getDefault().getProjectProperties())); succeeded = compiler.compile(configFile, progressMonitor); long timeEnd = System.currentTimeMillis(); lastCompileTime = (int)(timeEnd - timeStart); } catch (ConfigParser.ParseException pe) { Ajde.getDefault().getErrorHandler().handleWarning( "Config file entry invalid, file: " + pe.getFile().getPath() + ", line number: " + pe.getLine()); // } // catch (ExitRequestException ere) { // if (ere.getValue() == 0) { // notifyCompileAborted(configFile, "Build cancelled by user."); // } else { // Ajde.getDefault().getErrorHandler().handleWarning("Compile could not complete. See the console for more details. " // + "If no console is available re-launch the application from the command line."); // } // } catch (InternalCompilerError compilerError) { // if (compilerError.uncaughtThrowable instanceof OutOfMemoryError) { // Ajde.getDefault().getErrorHandler().handleError("Out of memory. " // + "Increase memory by setting the -Xmx parameter that this VM was launched with.\n" // + "Note that some AJDE structure persists across compiles." , // compilerError.uncaughtThrowable); // } else if (compilerError.uncaughtThrowable instanceof MissingRuntimeError) { // Ajde.getDefault().getErrorHandler().handleWarning("Compilation aborted because the AspectJ runtime was not found. " // + "Please place aspectjrt.jar in the lib/ext directory."); // } else if (compilerError.uncaughtThrowable instanceof BadRuntimeError) { // Ajde.getDefault().getErrorHandler().handleWarning("Compilation aborted because an out-of-date version of " + // "the AspectJ runtime was found. " // + "Please place a current version of aspectjrt.jar in the lib/ext directory."); // } else { // Ajde.getDefault().getErrorHandler().handleError("Compile error.", compilerError.uncaughtThrowable); // } } catch (Throwable e) { Ajde.getDefault().getErrorHandler().handleError("Compile error, caught Throwable: " + e.toString(), e); } finally { progressMonitor.finish(); } notifyCompileFinished(configFile, lastCompileTime, succeeded, warnings); } private String getFormattedOptionsString(BuildOptionsAdapter buildOptions, ProjectPropertiesAdapter properties) { return "Building with settings: " + "\n-> output path: " + properties.getOutputPath() + "\n-> classpath: " + properties.getClasspath() + "\n-> bootclasspath: " + properties.getBootClasspath() + "\n-> non-standard options: " + buildOptions.getNonStandardOptions() + "\n-> porting mode: " + buildOptions.getPortingMode() + "\n-> source 1.4 mode: " + buildOptions.getSourceOnePointFourMode() + "\n-> strict spec mode: " + buildOptions.getStrictSpecMode() + "\n-> lenient spec mode: " + buildOptions.getLenientSpecMode() + "\n-> use javac mode: " + buildOptions.getUseJavacMode() + "\n-> preprocess mode: " + buildOptions.getPreprocessMode() + "\n-> working dir: " + buildOptions.getWorkingOutputPath(); } } public BuildOptionsAdapter getBuildOptions() { return buildOptions; } // private void setCompilerOptions(AjdeCompiler compiler) { // String nonstandardOptions = buildOptions.getNonStandardOptions(); // if (nonstandardOptions != null && !nonstandardOptions.trim().equals("")) { // StringTokenizer st = new StringTokenizer(nonstandardOptions, " "); // while (st.hasMoreTokens()) { // String flag = (String)st.nextToken(); // compiler.getOptions().set(flag.substring(1, flag.length()), Boolean.TRUE); // } // } // // if (Ajde.getDefault().getProjectProperties().getOutputPath() != null // && !compiler.getOptions().XtargetNearSource) { // compiler.getOptions().outputDir = new File(Ajde.getDefault().getProjectProperties().getOutputPath()); // } // if (Ajde.getDefault().getProjectProperties().getBootClasspath() != null) { // compiler.getOptions().bootclasspath = Ajde.getDefault().getProjectProperties().getBootClasspath(); // } // if (Ajde.getDefault().getProjectProperties().getClasspath() != null) { // compiler.getOptions().classpath = Ajde.getDefault().getProjectProperties().getClasspath(); // } // if (buildOptions.getWorkingOutputPath() != null) { // compiler.getOptions().workingDir = new File(buildOptions.getWorkingOutputPath()); // } //// if (buildOptions.getCharacterEncoding() != null) { //// compiler.getOptions().encoding = buildOptions.getCharacterEncoding(); //// } // // compiler.getOptions().lenient = buildOptions.getLenientSpecMode(); // compiler.getOptions().strict = buildOptions.getStrictSpecMode(); // compiler.getOptions().usejavac = buildOptions.getUseJavacMode(); // compiler.getOptions().porting = buildOptions.getPortingMode(); // compiler.getOptions().preprocess = buildOptions.getPreprocessMode(); // // if (buildOptions.getSourceOnePointFourMode()) { // compiler.getOptions().source = "1.4"; // } // } static class CompileResult { private String[] files = null; private Integer[] lineNumbers = null; private String[] descriptions = null; private String resultString = ""; private boolean resultContainsErrors = false; /** * Parses out warning messages, error messages, "file not found" messages, javac "Note:" messages. * * @todo get error message structure directly from compiler */ public CompileResult( String result ) { resultString = result; BufferedReader reader = new BufferedReader( new StringReader( result ) ); Vector fileV = new Vector(); Vector lineV = new Vector(); Vector descV = new Vector(); try { for (String line = reader.readLine(); line != null; line = reader.readLine()) { String originalLine = line; String description = ""; String file = ""; Integer lineNo = new Integer(0); int index = line.indexOf( ":", 2 ); // @todo skip the initial drive ":" (fix, Windows only) try { if (line.indexOf("Note: ") != -1) { int index1 = line.indexOf(".java"); if (index1 != -1) { description = line.substring(index1+5) + " (warning)"; file = line.substring("Note: ".length(), index1+5); lineNo = new Integer(0); } else { description = line + " (warning)"; file = ""; lineNo = new Integer(-1); } } else if (line.indexOf("file not found: ") != -1) { description = "file not found: "; file = line.substring("file not found: ".length()); lineNo = new Integer(0); } else if (index != -1 && line.indexOf( "java" ) != -1) { file = line.substring( 0, index ); line = line.substring( index+1 ); index = line.indexOf( ":" ); lineNo = new Integer( Integer.parseInt( line.substring( 0, index ) ) ) ; line = line.substring( index+1 ); if (!resultContainsErrors) { if (!line.endsWith("(warning)")) { resultContainsErrors = true; } } description = line.substring( line.indexOf( ":" ) + 2 ); } } catch (Exception e) { description = "Internal ajc message: " + originalLine; file = ""; lineNo = new Integer(-1); } if (description.trim() != "") { descV.addElement(description); fileV.addElement(file); lineV.addElement(lineNo); } } } catch ( IOException ioe ) { resultString = "ERROR: could not parse result at line for string: " + result; } files = new String[fileV.size()]; lineNumbers = new Integer[lineV.size()]; descriptions = new String[descV.size()]; fileV.copyInto(files); lineV.copyInto(lineNumbers); descV.copyInto(descriptions); } public String toString() { return resultString; } public String[] getfiles() { return files; } public Integer[] getLineNumbers() { return lineNumbers; } public String[] getDescriptions() { return descriptions; } public String getResult() { return resultString; } public boolean containsErrors() { return resultContainsErrors; } } } class ConfigFileDoesNotExistException extends Exception { public ConfigFileDoesNotExistException(String filePath) { super(filePath); } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/src/org/aspectj/ajde/internal/CompilerAdapter.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde.internal; import java.io.File; import java.util.*; import org.aspectj.ajde.*; import org.aspectj.ajdt.internal.core.builder.AjBuildConfig; import org.aspectj.ajdt.internal.core.builder.AjBuildManager; import org.aspectj.bridge.*; import org.aspectj.util.ConfigParser; import org.eclipse.core.runtime.OperationCanceledException; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class CompilerAdapter { private AjBuildManager buildManager = null; private MessageHandlerAdapter messageHandler = null; private BuildNotifierAdapter currNotifier = null; private boolean initialized = false; private boolean structureDirty = true; private boolean firstBuild = true; public CompilerAdapter() { super(); } public void requestCompileExit() { if (currNotifier != null) currNotifier.cancelBuild(); // buildManager.getJavaBuilder().notifier.setCancelling(true); } public boolean isStructureDirty() { return structureDirty; } public void setStructureDirty(boolean structureDirty) { this.structureDirty = structureDirty; } public boolean compile(String configFile, BuildProgressMonitor progressMonitor) { init(); try { AjBuildConfig buildConfig = genBuildConfig(configFile); buildConfig.setGenerateModelMode(true); currNotifier = new BuildNotifierAdapter( AjBuildManager.DEFAULT_PROJECT, progressMonitor, buildConfig.getFiles().size()); buildManager.setBuildNotifier(currNotifier); messageHandler.setBuildNotifierAdapter(currNotifier); String rtInfo = buildManager.checkRtJar(buildConfig); // !!! will get called twice if (rtInfo != null) { Ajde.getDefault().getErrorHandler().handleWarning( "AspectJ Runtime error: " + rtInfo + " Please place a valid aspectjrt.jar in the lib/ext directory."); return false; } if (firstBuild) { firstBuild = false; return buildManager.batchBuild(buildConfig, messageHandler); } else { return buildManager.batchBuild(buildConfig, messageHandler); // XXX incremental not implemented // return buildManager.incrementalBuild(buildConfig); } } catch (OperationCanceledException ce) { Ajde.getDefault().getIdeUIAdapter().displayStatusInformation("build cancelled by user"); return false; } catch (Throwable t) { t.printStackTrace(); return false; // messageHandler.handleMessage(new Message(t.toString(), Message.ERROR, t, null)); } } public AjBuildConfig genBuildConfig(String configFile) { AjBuildConfig buildConfig = new AjBuildConfig(); File config = new File(configFile); if (!config.exists()) { Ajde.getDefault().getErrorHandler().handleWarning("Config file \"" + configFile + "\" does not exist."); } else { ConfigParser configParser = new ConfigParser(); configParser.parseConfigFile(config); buildConfig.setFiles(configParser.getFiles()); buildConfig.setConfigFile(config); } String classpathString = Ajde.getDefault().getProjectProperties().getBootClasspath() + File.pathSeparator + Ajde.getDefault().getProjectProperties().getClasspath(); StringTokenizer st = new StringTokenizer( classpathString, File.pathSeparator ); List classpath = new ArrayList(); while (st.hasMoreTokens()) classpath.add(st.nextToken()); buildConfig.setClasspath(classpath); Ajde.getDefault().logEvent("building with classpath: " + classpath); if (Ajde.getDefault().getBuildManager().getBuildOptions().getSourceOnePointFourMode()) { buildConfig.getJavaOptions().put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_4); } // XXX problematic restriction, support multiple source roots List sourceRoots = new ArrayList(); sourceRoots.add(new File(configFile).getParentFile()); buildConfig.setSourceRoots(sourceRoots); buildConfig.setOutputDir( new File(Ajde.getDefault().getProjectProperties().getOutputPath()) ); buildConfig.setGenerateModelMode(true); return buildConfig; } private void init() { if (!initialized) { // XXX plug into AJDE initialization // Ajde.getDefault().setErrorHandler(new DebugErrorHandler()); this.messageHandler = new MessageHandlerAdapter(); buildManager = new AjBuildManager(messageHandler); initialized = true; } } class MessageHandlerAdapter implements IMessageHandler { private TaskListManager taskListManager; private BuildNotifierAdapter buildNotifierAdapter; public MessageHandlerAdapter() { this.taskListManager = Ajde.getDefault().getTaskListManager(); } public boolean handleMessage(IMessage message) throws AbortException { if (isIgnoring(message.getKind())) return true; // ??? relies on only info messages being class-file written messages if (message.getKind().equals(IMessage.INFO)) { if (buildNotifierAdapter != null) { buildNotifierAdapter.generatedBytecode(message.getMessage()); } } else { taskListManager.addSourcelineTask( message.getMessage(), message.getISourceLocation(), message.getKind() ); } return true; } public boolean isIgnoring(IMessage.Kind kind) { // XXX implement for INFO, DEBUG? return false; } public void setBuildNotifierAdapter(BuildNotifierAdapter buildNotifierAdapter) { this.buildNotifierAdapter = buildNotifierAdapter; } } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/src/org/aspectj/ajde/ui/internal/AjcBuildOptions.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde.ui.internal; import org.aspectj.ajde.*; import org.aspectj.ajde.ui.*; public class AjcBuildOptions implements BuildOptionsAdapter { private UserPreferencesAdapter preferencesAdapter = null; private static final String AJC = "ajc"; private static final String USE_JAVAC_MODE = AJC + ".useJavacMode"; private static final String WORKING_DIR = AJC + ".workingDir"; private static final String PREPROCESS_MODE = AJC + ".preprocessMode"; private static final String CHARACTER_ENCODING = AJC + ".characterEncoding"; private static final String SOURCE_ONE_POINT_FOUR_MODE = AJC + ".sourceOnePointFourMode"; private static final String LENIENT_MODE = AJC + ".lenientSpecMode"; private static final String STRICT_MODE = AJC + ".strictSpecMode"; private static final String PORTING_MODE = AJC + ".portingMode"; private static final String VERBOSE_MODE = AJC + ".verboseMode"; private static final String NONSTANDARD_OPTIONS = AJC + ".nonStandardOptions"; public AjcBuildOptions(UserPreferencesAdapter userPreferencesAdapter) { this.preferencesAdapter = userPreferencesAdapter; } public boolean getUseJavacMode() { return getBooleanOptionVal(USE_JAVAC_MODE); } public void setUseJavacMode(boolean value) { setBooleanOptionVal(USE_JAVAC_MODE, value); } public String getWorkingOutputPath() { return preferencesAdapter.getProjectPreference(WORKING_DIR); } public void setWorkingDir(String path) { preferencesAdapter.setProjectPreference(WORKING_DIR, path); } public boolean getPreprocessMode() { return getBooleanOptionVal(PREPROCESS_MODE); } public void setPreprocessMode(boolean value) { setBooleanOptionVal(PREPROCESS_MODE, value); } public String getCharacterEncoding() { return preferencesAdapter.getProjectPreference(CHARACTER_ENCODING); } public void setCharacterEncoding(String value) { preferencesAdapter.setProjectPreference(CHARACTER_ENCODING, value); } public boolean getSourceOnePointFourMode() { return getBooleanOptionVal(SOURCE_ONE_POINT_FOUR_MODE); } public void setSourceOnePointFourMode(boolean value) { setBooleanOptionVal(SOURCE_ONE_POINT_FOUR_MODE, value); } public boolean getLenientSpecMode() { return getBooleanOptionVal(LENIENT_MODE); } public void setLenientSpecMode(boolean value) { setBooleanOptionVal(LENIENT_MODE, value); } public boolean getStrictSpecMode() { return getBooleanOptionVal(STRICT_MODE); } public void setStrictSpecMode(boolean value) { setBooleanOptionVal(STRICT_MODE, value); } public boolean getPortingMode() { return getBooleanOptionVal(PORTING_MODE); } public void setPortingMode(boolean value) { setBooleanOptionVal(PORTING_MODE, value); } public boolean getVerboseMode() { return getBooleanOptionVal(VERBOSE_MODE); } public void setVerboseMode(boolean value) { setBooleanOptionVal(VERBOSE_MODE, value); } public String getNonStandardOptions() { return preferencesAdapter.getProjectPreference(NONSTANDARD_OPTIONS); } public void setNonStandardOptions(String value) { preferencesAdapter.setProjectPreference(NONSTANDARD_OPTIONS, value); } private boolean getBooleanOptionVal(String name) { if (preferencesAdapter.getProjectPreference(name) != null) { return preferencesAdapter.getProjectPreference(name).equals("true"); } else { return false; } } private void setBooleanOptionVal(String name, boolean value) { if (value) { preferencesAdapter.setProjectPreference(name, "true"); } else { preferencesAdapter.setProjectPreference(name, "false"); } } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testdata/examples/figures-coverage/figures/Figure.java
package figures; //import figures.primitives.planar.Point; import java.awt.Canvas; aspect Figure { //pointcut sendSuccess(): cflow(setX()) && !handler(Exception); public String Point.getName() { return Point.name; } public int figures.primitives.planar.Point.DEFAULT_X = 0; public pointcut constructions(): call(Point.new(int, int)) || call(SolidPoint.new(int, int, int)); public pointcut moves(FigureElement fe): target(fe) && (call(String Point.getName()) || call(void FigureElement.incrXY(int, int)) || call(void Point.setX(int)) || call(void Point.setY(int)) || call(void SolidPoint.setZ(int))); pointcut mainExecution(): execution(int main(*)); pointcut runtimeHandlers(): mainExecution() || handler(RuntimeException); public pointcut mumble(): runtimeHandlers(); before(int newValue): set(int *.*) && args(newValue) { } before(): get(int *.*) { } before(): constructions() { System.out.println("> before construction, jp: " + thisJoinPoint.getSignature()); } before(FigureElement fe): moves(fe) { System.out.println("> about to move FigureElement at X-coord: "); } after(): initialization(Point.new(..)) || staticinitialization(Point) { System.out.println("> Point initialized"); } // should be around after(): mumble() { System.err.println(">> in after advice..."); //proceed(); } after(FigureElement fe): target(fe) && (call(void FigureElement.incrXY(int, int)) || call(void Point.setX(int)) || call(void Point.setY(int)) || call(void SolidPoint.setZ(int))) { System.out.println("> yo."); } after(FigureElement fe): target(fe) && (call(void FigureElement.incrXY(int, int)) || call(void Line.setP1(Point)) || call(void Line.setP2(Point)) || call(void Point.setX(int)) || call(void Point.setY(int))) { } declare parents: Point extends java.io.Serializable; declare parents: Point implements java.util.Observable; declare soft: Point: call(* *(..)); } aspect Checks { pointcut illegalNewFigElt(): call(FigureElement+.new(..)) && !withincode(* Main.main(..)); declare error: illegalNewFigElt(): "Illegal figure element constructor call."; declare warning: illegalNewFigElt(): "Illegal figure element constructor call."; }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/AjdeTests.java
/* ******************************************************************* * Copyright (c) 1999-2001 Xerox Corporation, * 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import junit.framework.*; public class AjdeTests extends TestCase { public static Test suite() { TestSuite suite = new TestSuite(AjdeTests.class.getName()); //$JUnit-BEGIN$ suite.addTestSuite(BuildOptionsTest.class); suite.addTestSuite(StructureModelRegressionTest.class); suite.addTestSuite(StructureModelTest.class); suite.addTestSuite(VersionTest.class); //$JUnit-END$ return suite; } public AjdeTests(String name) { super(name); } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/BuildConfigurationTests.java
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/BuildOptionsTest.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import junit.framework.TestSuite; import org.aspectj.ajde.ui.UserPreferencesAdapter; import org.aspectj.ajde.ui.internal.AjcBuildOptions; import org.aspectj.ajde.ui.internal.UserPreferencesStore; public class BuildOptionsTest extends AjdeTestCase { private AjcBuildOptions buildOptions = null; private UserPreferencesAdapter preferencesAdapter = null; public BuildOptionsTest(String name) { super(name); } public static void main(String[] args) { junit.swingui.TestRunner.run(BuildOptionsTest.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(BuildOptionsTest.class); return result; } public void testCharacterEncoding() { buildOptions.setCharacterEncoding("mumble"); assertTrue("character encoding", buildOptions.getCharacterEncoding().equals("mumble")); } public void testPortingMode() { buildOptions.setPortingMode(true); assertTrue("porting mode", buildOptions.getPortingMode()); } protected void setUp() throws Exception { super.setUp(); preferencesAdapter = new UserPreferencesStore(); buildOptions = new AjcBuildOptions(preferencesAdapter); } protected void tearDown() throws Exception { super.tearDown(); buildOptions.setCharacterEncoding(""); buildOptions.setPortingMode(true); } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/NullIdeManager.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import javax.swing.JFrame; import org.aspectj.ajde.ui.IdeUIAdapter; import org.aspectj.ajde.ui.UserPreferencesAdapter; import org.aspectj.ajde.ui.internal.UserPreferencesStore; import org.aspectj.ajde.ui.swing.*; /** * @author Mik Kersten */ public class NullIdeManager { public void init(String testProjectPath) { try { UserPreferencesAdapter preferencesAdapter = new UserPreferencesStore(); ProjectPropertiesAdapter browserProjectProperties = new NullIdeProperties(testProjectPath); TaskListManager taskListManager = new NullIdeTaskListManager(); BasicEditor ajdeEditor = new BasicEditor(); IdeUIAdapter uiAdapter = new NullIdeUIAdapter(); JFrame nullFrame = new JFrame(); //configurationManager.setConfigFiles(getConfigFilesList(configFiles)); AjdeUIManager.getDefault().init( ajdeEditor, taskListManager, browserProjectProperties, preferencesAdapter, uiAdapter, new IconRegistry(), nullFrame, true); } catch (Throwable t) { t.printStackTrace(); Ajde.getDefault().getErrorHandler().handleError( "Null IDE failed to initialize.", t); } } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/NullIdeProperties.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import java.io.File; import java.util.*; /** * @author Mik Kersten */ public class NullIdeProperties implements ProjectPropertiesAdapter { private String testProjectPath = ""; private List buildConfigFiles = new ArrayList(); public NullIdeProperties(String testProjectPath) { this.testProjectPath = testProjectPath; } public List getBuildConfigFiles() { return buildConfigFiles; } public String getLastActiveBuildConfigFile() { return null; } public String getDefaultBuildConfigFile() { return null; } public String getProjectName() { return "test"; } public String getRootProjectDir() { return testProjectPath; } public List getProjectSourceFiles() { return null; } public String getProjectSourcePath() { return testProjectPath + "/src"; } public String getClasspath() { //XXX return testProjectPath + System.getProperty("sun.boot.class.path") + File.pathSeparator + "../../../runtime/bin"; } public String getOutputPath() { return testProjectPath + "/bin"; } public String getAjcWorkingDir() { return testProjectPath + "/ajworkingdir"; } public String getBootClasspath() { return null; } public String getClassToExecute() { return "figures.Main"; } public String getExecutionArgs() { return null; } public String getVmArgs() { return null; } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/StructureModelRegressionTest.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import java.io.File; import junit.framework.TestSuite; import org.aspectj.asm.StructureModel; public class StructureModelRegressionTest extends AjdeTestCase { public StructureModelRegressionTest(String name) { super(name); } public static void main(String[] args) { junit.swingui.TestRunner.run(StructureModelRegressionTest.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(StructureModelRegressionTest.class); return result; } public void test() { String testLstFile = "StructureModelRegressionTest/example.lst"; File f = new File(testLstFile); assertTrue(testLstFile, f.canRead()); assertTrue("saved model: " + testLstFile, verifyAgainstSavedModel(testLstFile)); } public boolean verifyAgainstSavedModel(String lstFile) { File modelFile = new File(genStructureModelExternFilePath(lstFile)); StructureModel model = getModelForFile(lstFile); System.out.println(">> model: " + model.getRoot()); if (modelFile.exists()) { Ajde.getDefault().getStructureModelManager().readStructureModel(lstFile); StructureModel savedModel = Ajde.getDefault().getStructureModelManager().getStructureModel(); //System.err.println( savedModel.getRoot().getClass() + ", " + savedModel.getRoot()); return savedModel.getRoot().equals(model.getRoot()); } else { Ajde.getDefault().getStructureModelManager().writeStructureModel(lstFile); return true; } //return true; } private StructureModel getModelForFile(String lstFile) { Ajde.getDefault().getConfigurationManager().setActiveConfigFile(lstFile); Ajde.getDefault().getBuildManager().buildStructure(); while(!testerBuildListener.getBuildFinished()) { try { Thread.sleep(300); } catch (InterruptedException ie) { } } return Ajde.getDefault().getStructureModelManager().getStructureModel(); } protected void setUp() throws Exception { super.setUp("StructureModelRegressionTest"); Ajde.getDefault().getStructureModelManager().setShouldSaveModel(false); } public void testModelExists() { assertTrue(Ajde.getDefault().getStructureModelManager().getStructureModel() != null); } protected void tearDown() throws Exception { super.tearDown(); } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/StructureModelTest.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import junit.framework.TestSuite; import org.aspectj.asm.*; /** * @author Mik Kersten */ public class StructureModelTest extends AjdeTestCase { private final String CONFIG_FILE_PATH = "../examples/figures-coverage/all.lst"; public StructureModelTest(String name) { super(name); } public static void main(String[] args) { junit.swingui.TestRunner.run(StructureModelTest.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(StructureModelTest.class); return result; } public void testFieldInitializerCorrespondence() throws IOException { File testFile = createFile("../examples/figures-coverage/figures/Figure.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( testFile.getCanonicalPath(), 28); assertTrue("find result", node != null) ; ProgramElementNode pNode = (ProgramElementNode)node; ProgramElementNode foundNode = null; final List list = pNode.getRelations(); assertNotNull("pNode.getRelations()", list); for (Iterator it = list.iterator(); it.hasNext(); ) { RelationNode relation = (RelationNode)it.next(); if (relation.getRelation().equals(AdviceAssociation.FIELD_ACCESS_RELATION)) { for (Iterator it2 = relation.getChildren().iterator(); it2.hasNext(); ) { LinkNode linkNode = (LinkNode)it2.next(); if (linkNode.getProgramElementNode().getName().equals("this.currVal = 0")) { foundNode = linkNode.getProgramElementNode(); } } } } assertTrue("find associated node", foundNode != null) ; File pointFile = createFile("../examples/figures-coverage/figures/primitives/planar/Point.java"); StructureNode fieldNode = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( pointFile.getCanonicalPath(), 12); assertTrue("find result", fieldNode != null); assertTrue("matches", foundNode.getParent() == fieldNode.getParent()); } public void testFileNodeFind() throws IOException { File testFile = createFile("../examples/figures-coverage/figures/Main.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( testFile.getCanonicalPath(), 1); assertTrue("find result", node != null) ; ProgramElementNode pNode = (ProgramElementNode)node; assertTrue("found node: " + pNode.getName(), pNode.getProgramElementKind().equals(ProgramElementNode.Kind.FILE_JAVA)); } /** * @todo add negative test to make sure things that aren't runnable aren't annotated */ public void testMainClassNodeInfo() throws IOException { assertTrue("root exists", Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot() != null); File testFile = createFile("../examples/figures-coverage/figures/Main.java"); StructureNode node = Ajde.getDefault().getStructureModelManager().getStructureModel().findNodeForSourceLine( testFile.getCanonicalPath(), 11); assertTrue("find result", node != null); ProgramElementNode pNode = (ProgramElementNode)((ProgramElementNode)node).getParent(); assertTrue("found node: " + pNode.getName(), pNode.isRunnable()); } /** * Integrity could be checked somewhere in the API. */ public void testModelIntegrity() { StructureNode modelRoot = Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot(); assertTrue("root exists", modelRoot != null); try { testModelIntegrityHelper(modelRoot); } catch (Exception e) { assertTrue(e.toString(), false); } } private void testModelIntegrityHelper(StructureNode node) throws Exception { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { StructureNode child = (StructureNode)it.next(); if (node == child.getParent()) { testModelIntegrityHelper(child); } else { throw new Exception("parent-child check failed for child: " + child.toString()); } } } public void testNoChildIsNull() { ModelWalker walker = new ModelWalker() { public void preProcess(StructureNode node) { if (node.getChildren() == null) return; for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { if (it.next() == null) throw new NullPointerException("null child on node: " + node.getName()); } } }; Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot().walk(walker); } protected void setUp() throws Exception { super.setUp("StructureModelTest"); doSynchronousBuild(CONFIG_FILE_PATH); } protected void tearDown() throws Exception { super.tearDown(); } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
ajde/testsrc/org/aspectj/ajde/ui/StructureViewManagerTest.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * Xerox/PARC initial implementation * ******************************************************************/ package org.aspectj.ajde.ui; import java.io.File; import java.util.Iterator; import junit.framework.TestSuite; import org.aspectj.ajde.Ajde; import org.aspectj.ajde.AjdeTestCase; import org.aspectj.asm.StructureModelManager; import org.aspectj.asm.StructureNode; /** * @author Mik Kersten */ public class StructureViewManagerTest extends AjdeTestCase { private final String CONFIG_FILE_PATH = "../examples/figures-coverage/all.lst"; private final String CONFIG_FILE_PATH_2 = "../examples/inheritance/inheritance.lst"; private FileStructureView currentView; private NullIdeStructureViewRenderer renderer = new NullIdeStructureViewRenderer(); private File testFile; private StructureViewProperties properties; public StructureViewManagerTest(String name) { super(name); } public static void main(String[] args) { junit.swingui.TestRunner.run(StructureViewManagerTest.class); } public static TestSuite suite() { TestSuite result = new TestSuite(); result.addTestSuite(StructureViewManagerTest.class); return result; } public void testModelExists() { assertTrue(Ajde.getDefault().getStructureModelManager().getStructureModel() != null); } public void testNotificationAfterConfigFileChange() { doSynchronousBuild(CONFIG_FILE_PATH_2); renderer.setHasBeenNotified(false); assertTrue("not yet notified", !renderer.getHasBeenNotified()); Ajde.getDefault().getConfigurationManager().setActiveConfigFile(CONFIG_FILE_PATH_2); assertTrue("notified", renderer.getHasBeenNotified()); renderer.setHasBeenNotified(false); Ajde.getDefault().getConfigurationManager().setActiveConfigFile("MumbleDoesNotExist.lst"); assertTrue("notified", renderer.getHasBeenNotified()); assertTrue( "no structure", currentView.getRootNode().getStructureNode().getChildren().get(0) == StructureModelManager.INSTANCE.getStructureModel().NO_STRUCTURE ); } /** * @todo this should be moved to a StructureModelManager test */ public void testFreshStructureModelCreation() { renderer.setHasBeenNotified(false); String modelPath = genStructureModelExternFilePath(CONFIG_FILE_PATH); createFile(modelPath).delete(); //System.err.println("> path: " + modelPath); Ajde.getDefault().getStructureModelManager().readStructureModel(CONFIG_FILE_PATH); assertTrue("notified", renderer.getHasBeenNotified()); //System.err.println(">>>>>> " + currentView.getRootNode().getStructureNode()); assertTrue( "no structure", currentView.getRootNode().getStructureNode().getChildren().get(0) == StructureModelManager.INSTANCE.getStructureModel().NO_STRUCTURE ); } public void testModelIntegrity() { doSynchronousBuild(CONFIG_FILE_PATH); StructureNode modelRoot = Ajde.getDefault().getStructureModelManager().getStructureModel().getRoot(); assertTrue("root exists", modelRoot != null); try { testModelIntegrityHelper(modelRoot); } catch (Exception e) { assertTrue(e.toString(), false); } } private void testModelIntegrityHelper(StructureNode node) throws Exception { for (Iterator it = node.getChildren().iterator(); it.hasNext(); ) { StructureNode child = (StructureNode)it.next(); if (node == child.getParent()) { testModelIntegrityHelper(child); } else { throw new Exception("parent-child check failed for child: " + child.toString()); } } } public void testNotificationAfterBuild() { renderer.setHasBeenNotified(false); doSynchronousBuild(CONFIG_FILE_PATH); assertTrue("notified", renderer.getHasBeenNotified()); } public void testViewCreationWithNullSourceFileAndProperties() { currentView = Ajde.getDefault().getStructureViewManager().createViewForSourceFile(null, null); assertTrue( "no structure", currentView.getRootNode().getStructureNode() == StructureModelManager.INSTANCE.getStructureModel().NO_STRUCTURE ); } protected void setUp() throws Exception { super.setUp("StructureViewManagerTest"); doSynchronousBuild(CONFIG_FILE_PATH); properties = Ajde.getDefault().getStructureViewManager().getDefaultViewProperties(); testFile = createFile("../examples/figures-coverage/figures/Figure.java"); currentView = Ajde.getDefault().getStructureViewManager().createViewForSourceFile(testFile.getAbsolutePath(), properties); currentView.setRenderer(renderer); } protected void tearDown() throws Exception { super.tearDown(); } // public void testViewListenerRegistrations() { // System.err.println("> starting..."); // Ajde.getDefault().getBuildManager().build("C:/Dev/aspectj/tests/ajde/examples/coverage-figures/src/AllFiles.lst"); // while(!testerBuildListener.getBuildFinished()) { // try { // Thread.sleep(300); // } catch (InterruptedException ie) { } // } // List renderers = Ajde.getDefault().getStructureViewManager().getDefaultFileStructureView().getRenderers(); // System.err.println("> renderers (1): " + renderers); // // testerBuildListener.reset(); // Ajde.getDefault().getBuildManager().build("C:/Dev/aspectj/tests/ajde/examples/coverage-figures/src/AllFiles.lst"); // while(!testerBuildListener.getBuildFinished()) { // try { // Thread.sleep(300); // } catch (InterruptedException ie) { } // } // System.err.println("> renderers (2): " + renderers); // assertTrue("checking renderers", true); // } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/ajc/BuildArgParser.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import java.io.*; import java.util.*; import org.aspectj.ajdt.internal.core.builder.*; import org.aspectj.weaver.bcel.*; import org.apache.bcel.util.ClassPath; import org.aspectj.bridge.*; import org.aspectj.bridge.IMessage.Kind; import org.aspectj.util.*; import org.eclipse.jdt.core.JavaCore; import org.eclipse.jdt.core.compiler.*; import org.eclipse.jdt.internal.compiler.*; import org.eclipse.jdt.internal.compiler.batch.*; import org.eclipse.jdt.internal.compiler.problem.*; import org.eclipse.jdt.internal.core.util.*; import org.aspectj.ajdt.internal.core.builder.AjCompilerOptions; import org.aspectj.util.ConfigParser; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; public class BuildArgParser extends org.eclipse.jdt.internal.compiler.batch.Main { private static final String BUNDLE_NAME = "org.aspectj.ajdt.ajc.messages"; /** to initialize super's PrintWriter but refer to underlying StringWriter */ private static class StringPrintWriter extends PrintWriter { public final StringWriter stringWriter; StringPrintWriter(StringWriter sw) { super(sw); this.stringWriter = sw; } } /** * StringWriter sink for some errors. * This only captures errors not handled by any IMessageHandler parameter * and only when no PrintWriter is set in the constructor. * XXX This relies on (Sun's) implementation of StringWriter, * which returns the actual (not copy) internal StringBuffer. */ private final StringBuffer errorSink; /** * Overrides super's bundle. */ public BuildArgParser(PrintWriter writer) { super(writer, false); bundle = ResourceBundle.getBundle(BUNDLE_NAME); if (writer instanceof StringPrintWriter) { errorSink = ((StringPrintWriter) writer).stringWriter.getBuffer(); } else { errorSink = null; } } /** Set up to capture messages using getOtherMessages(boolean) */ public BuildArgParser() { this(new StringPrintWriter(new StringWriter())); } public AjBuildConfig genBuildConfig(String[] args, IMessageHandler handler) { AjBuildConfig buildConfig = new AjBuildConfig(); try { // sets filenames to be non-null in order to make sure that file paramters are ignored super.filenames = new String[] { "" }; List optionsList = new ArrayList(Arrays.asList(args)); List fileList = new ArrayList(); boolean incrementalMode = false; if (optionsList.remove("-incremental")) { incrementalMode = true; args = (String[])optionsList.toArray(new String[optionsList.size()]); } AjcConfigParser parser = new AjcConfigParser(buildConfig, handler, incrementalMode); parser.parseCommandLine(args); if (!incrementalMode) { if (parser.getFiles() != null) { for (Iterator it = parser.getFiles().iterator(); it.hasNext(); ) { fileList.add((File)it.next()); } } } else { if (parser.getFiles() != null && !parser.getFiles().isEmpty()) { handler.handleMessage(new Message("can not directly specify files in incremental mode, use -sourceroots instead", Message.ERROR, null, null)); } } List javaArgList = parser.getUnparsedArgs(); if (javaArgList.size() != 0) { super.configure((String[])javaArgList.toArray(new String[javaArgList.size()])); } if (buildConfig.getSourceRoots() != null) { for (Iterator i = buildConfig.getSourceRoots().iterator(); i.hasNext(); ) { fileList.addAll(collectSourceRootFiles((File)i.next())); } } buildConfig.setFiles(fileList); if (destinationPath != null) { buildConfig.setOutputDir(new File(destinationPath)); } buildConfig.setClasspath(getClasspath(parser)); if (incrementalMode) { if (buildConfig.getSourceRoots().size() == 0) { handler.handleMessage(new Message("must specify a source root when in incremental mode", Message.ERROR, null, null)); } } setDebugOptions(); buildConfig.setJavaOptions(options); } catch (InvalidInputException iie) { handler.handleMessage(new Message(iie.getMessage(), Message.ERROR, null, null)); printUsage(); } return buildConfig; } /** * Get messages not dumped to handler or any PrintWriter. * @param flush if true, empty errors * @return null if none, String otherwise * @see BuildArgParser() */ public String getOtherMessages(boolean flush) { if (null == errorSink) { return null; } String result = errorSink.toString().trim(); if (0 == result.length()) { result = null; } if (flush) { errorSink.setLength(0); } return result; } private void setDebugOptions() { options.put( CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE); options.put( CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE); } private Collection collectSourceRootFiles(File dir) { return Arrays.asList(FileUtil.listFiles(dir, FileUtil.aspectjSourceFileFilter)); } public List getClasspath(AjcConfigParser parser) { List ret = new ArrayList(); if (parser.bootclasspath == null) { addClasspath(System.getProperty("sun.boot.class.path", ""), ret); } else { addClasspath(parser.bootclasspath, ret); } String extdirs = parser.extdirs; if (extdirs == null) { extdirs = System.getProperty("java.ext.dirs", ""); } addExtDirs(extdirs, ret); if ((classpaths == null || classpaths.length == 0) || (classpaths != null && classpaths[0] == ".")) { //??? this puts the compiler's classes on the classpath //??? this is ajc-1.0 compatible addClasspath(System.getProperty("java.class.path", ""), ret); } else { ret.addAll(Arrays.asList(classpaths)); } //??? eclipse seems to put outdir on the classpath //??? we're brave and believe we don't need it return ret; } private void addExtDirs(String extdirs, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(extdirs, File.pathSeparator); while (tokenizer.hasMoreTokens()) { // classpathCollector.add(tokenizer.nextToken()); File dirFile = new File((String)tokenizer.nextToken()); if (dirFile.exists() && dirFile.isDirectory()) { File[] files = FileUtil.listFiles(dirFile, new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().endsWith(".jar"); } }); for (int i = 0; i < files.length; i++) { classpathCollector.add(files[i].getAbsolutePath()); } } } } private void addClasspath(String classpath, List classpathCollector) { StringTokenizer tokenizer = new StringTokenizer(classpath, File.pathSeparator); while (tokenizer.hasMoreTokens()) { classpathCollector.add(tokenizer.nextToken()); } } // !!! extract error handling to be common so that the IDEs can use it private class AjcConfigParser extends ConfigParser { private String bootclasspath = null; private String extdirs = null; private boolean incrementalArgsMode = false; private List unparsedArgs = new ArrayList(); private AjBuildConfig buildConfig; private IMessageHandler handler; public AjcConfigParser(AjBuildConfig buildConfig, IMessageHandler handler, boolean incrementalMode) { this.buildConfig = buildConfig; this.handler = handler; this.incrementalArgsMode = incrementalMode; } public List getUnparsedArgs() { return unparsedArgs; } public void parseOption(String arg, LinkedList args) { int nextArgIndex = args.indexOf(arg)+1; if (arg.equals("-Xlint")) {; buildConfig.getAjOptions().put( AjCompilerOptions.OPTION_Xlint, CompilerOptions.GENERATE); } else if (arg.equals("-injars")) {; if (args.size() > nextArgIndex) { buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_InJARs, CompilerOptions.PRESERVE); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (filename.endsWith(".jar") && jarFile.exists()) { buildConfig.getInJars().add(jarFile); } else { handler.handleMessage(new Message( "ignoring bad injar: " + filename, Message.WARNING, null, null)); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-aspectpath")) {; if (args.size() > nextArgIndex) { StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { String filename = st.nextToken(); File jarFile = makeFile(filename); if (filename.endsWith(".jar") && jarFile.exists()) { buildConfig.getAspectpath().add(jarFile); } else { handler.handleMessage(new Message( "ignoring bad injar: " + filename, Message.WARNING, null, null)); } } args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-sourceroots")) { if (args.size() > nextArgIndex) { List sourceRoots = new ArrayList(); StringTokenizer st = new StringTokenizer( ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(), File.pathSeparator); while (st.hasMoreTokens()) { File f = makeFile(st.nextToken()); if (f.isDirectory()) { sourceRoots.add(f); } else { handler.handleMessage(new Message( f.getName() + " is not a file, not adding to sourceroots", Message.WARNING, null, null)); } } // if (sourceRoots.size() > 1) { // handler.handleMessage(new Message( // "can not specify more than one source root (compiler limitation)\n" // + "using source root: " + sourceRoots.get(0), // Message.WARNING, null, null)); // } else if (sourceRoots.size() < 1) { out.println("must specify a valid source root in incremental mode"); } else { buildConfig.setSourceRoots(sourceRoots); } args.remove(args.get(nextArgIndex)); } else { out.println("must specify a valid source root in incremental mode"); } } else if (arg.equals("-outjar")) { if (args.size() > nextArgIndex) { buildConfig.getAjOptions().put(AjCompilerOptions.OPTION_OutJAR, CompilerOptions.GENERATE); File jarFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (jarFile.getName().endsWith(".jar")) { try { if (!jarFile.exists()) jarFile.createNewFile(); } catch (IOException ioe) { // fail siltenty } buildConfig.setOutputJar(jarFile); } else { out.println("file specified with -outjar is not a valid JAR file, ignoring"); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { out.println("must specify a file for -outjar"); } } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-emacssym")) { buildConfig.setEmacsSymMode(true); buildConfig.setGenerateModelMode(true); } else if (arg.equals("-noweave")) { buildConfig.setNoWeave(true); } else if (arg.equals("-XserializableAspects")) { buildConfig.setXserializableAspects(true); } else if (arg.equals("-XnoInline")) { buildConfig.setXnoInline(true); } else if (arg.equals("-Xlintfile")) { if (args.size() > nextArgIndex) { File lintSpecFile = makeFile(((ConfigParser.Arg)args.get(nextArgIndex)).getValue()); if (lintSpecFile.exists() && lintSpecFile.getName().endsWith(".properties")) { buildConfig.setLintSpecFile(lintSpecFile); } else { out.println("file specified with -Xlintfile does not exist, ignoring"); buildConfig.setLintSpecFile(null); } args.remove(args.get(nextArgIndex)); } else { out.println("must specify a file for -outjar"); } } else if (arg.startsWith("-Xlint")) { int index = arg.indexOf(":"); if (index != -1) { buildConfig.setLintMode(arg.substring(index+1)); } else { buildConfig.setLintMode(AjBuildConfig.AJLINT_DEFAULT); } } else if (arg.equals("-bootclasspath")) { if (args.size() > nextArgIndex) { bootclasspath = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } } else if (arg.equals("-extdirs")) { if (args.size() > nextArgIndex) { extdirs = ((ConfigParser.Arg)args.get(nextArgIndex)).getValue(); args.remove(args.get(nextArgIndex)); } } else { // if (arg.equals("-d")) { // int nextArgIndex = args.indexOf(arg)+1; // if (args.size() > nextArgIndex) { // ConfigParser.Arg path = (ConfigParser.Arg)args.get(nextArgIndex); // path.setValue(makeFile(path.getValue()).getPath()); // } // } unparsedArgs.add(arg); } } public void showError(String message) { // out.println(message); handler.handleMessage(new Message(message, Message.ERROR, null, null)); } protected void showWarning(String message) { handler.handleMessage(new Message(message, Message.WARNING, null, null)); } } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/core/builder/AjBuildConfig.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.core.builder; import java.io.File; import java.util.*; /** * All configuration information needed to run the AspectJ compiler. */ public class AjBuildConfig { public static final String AJLINT_INGORE = "ignore"; public static final String AJLINT_WARN = "warn"; public static final String AJLINT_ERROR = "error"; public static final String AJLINT_DEFAULT = "default"; private File outputDir; private File outputJar; private List/*File*/ sourceRoots = new ArrayList(); private List/*File*/ files = new ArrayList(); private List/*File*/ inJars = new ArrayList(); private List/*File*/ aspectpath = new ArrayList(); private List/*String*/ classpath = new ArrayList(); private Map javaOptions = new HashMap(); private Map ajOptions = new HashMap(); private File configFile; private boolean generateModelMode = false; private boolean emacsSymMode = false; private boolean noWeave = false; private boolean XserializableAspects = false; private boolean XnoInline = false; private String lintMode = AJLINT_DEFAULT; private File lintSpecFile = null; /** * returned files includes <ul> * <li>files explicitly listed on command-line</li> * <li>files listed by reference in argument list files</li> * <li>files contained in sourceRootDir if that exists</li> * </ul> * * @return all source files that should be compiled. */ public List/*File*/ getFiles() { return files; } public File getOutputDir() { return outputDir; } public void setFiles(List files) { this.files = files; } public void setOutputDir(File outputDir) { this.outputDir = outputDir; } public Map getAjOptions() { return ajOptions; } /** * @return the Map expected by org.eclipse.jdt.core.internal.Compiler. */ public Map getJavaOptions() { return javaOptions; } public void setAjOptions(Map ajOptions) { this.ajOptions = ajOptions; } public void setJavaOptions(Map javaOptions) { this.javaOptions = javaOptions; } /** * This includes all entries from -bootclasspath, -extdirs, -classpath, */ public List getClasspath() { return classpath; } public void setClasspath(List classpath) { this.classpath = classpath; } public File getOutputJar() { return outputJar; } public List/*File*/ getInJars() { return inJars; } public void setOutputJar(File outputJar) { this.outputJar = outputJar; } public void setInJars(List sourceJars) { this.inJars = sourceJars; } public List getSourceRoots() { return sourceRoots; } public void setSourceRoots(List sourceRootDir) { this.sourceRoots = sourceRootDir; } public File getConfigFile() { return configFile; } public void setConfigFile(File configFile) { this.configFile = configFile; } public boolean isEmacsSymMode() { return emacsSymMode; } public void setEmacsSymMode(boolean emacsSymMode) { this.emacsSymMode = emacsSymMode; } public boolean isGenerateModelMode() { return generateModelMode; } public void setGenerateModelMode(boolean structureModelMode) { this.generateModelMode = structureModelMode; } /** * This includes injars and aspectpath */ public List getFullClasspath() { if (inJars.isEmpty() && aspectpath.isEmpty()) return getClasspath(); List full = new ArrayList(); for (Iterator i = inJars.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } for (Iterator i = aspectpath.iterator(); i.hasNext(); ) { full.add(((File)i.next()).getAbsolutePath()); } full.addAll(getClasspath()); return full; } public String getLintMode() { return lintMode; } public File getLintSpecFile() { return lintSpecFile; } public List getAspectpath() { return aspectpath; } public boolean isNoWeave() { return noWeave; } public void setLintMode(String lintMode) { this.lintMode = lintMode; } public void setLintSpecFile(File lintSpecFile) { this.lintSpecFile = lintSpecFile; } public void setAspectpath(List aspectpath) { this.aspectpath = aspectpath; } public void setNoWeave(boolean noWeave) { this.noWeave = noWeave; } public boolean isXserializableAspects() { return XserializableAspects; } public void setXserializableAspects(boolean xserializableAspects) { XserializableAspects = xserializableAspects; } public boolean isXnoInline() { return XnoInline; } public void setXnoInline(boolean xnoInline) { XnoInline = xnoInline; } }
29,769
Bug 29769 Ajde does not support new AspectJ 1.1 compiler options
The org.aspectj.ajde.BuildOptionsAdapter interface does not yet support the new AspectJ 1.1 compiler options. These need to be added to the interface, any old or renamed options deprecated, and then the correct processing needs to happen within Ajde to pass these options to the compiler. This enhancement is needed by the various IDE projects for there AspectJ 1.1 support.
resolved fixed
85a827a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-01-25T01:25:30Z
2003-01-19T15:26:40Z
org.aspectj.ajdt.core/testsrc/org/aspectj/ajdt/ajc/BuildArgParserTestCase.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.ajc; import org.aspectj.ajdt.internal.core.builder.AjBuildConfig; import org.aspectj.ajdt.internal.core.builder.AjCompilerOptions; import org.aspectj.bridge.MessageWriter; import org.aspectj.testing.util.TestUtil; import org.eclipse.jdt.core.compiler.InvalidInputException; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; import java.util.Arrays; import java.util.Collection; import java.util.List; import junit.framework.TestCase; /** * Some black-box test is happening here. */ public class BuildArgParserTestCase extends TestCase { private BuildArgParser parser = new BuildArgParser(); private static final String TEST_DIR = "testdata" + File.separator + "ajc" + File.separator; private MessageWriter messageWriter = new MessageWriter(new PrintWriter(System.out), false); public BuildArgParserTestCase(String name) { super(name); } public void testDefaultClasspathAndTargetCombo() throws InvalidInputException { String ENTRY = "1.jar;2.jar"; final String classpath = System.getProperty("java.class.path"); try { System.setProperty("java.class.path", ENTRY); // see finally below AjBuildConfig config = parser.genBuildConfig(new String[] { }, messageWriter); String err = parser.getOtherMessages(true); assertTrue(err, null == err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); config = parser.genBuildConfig(new String[] { "-1.3" }, messageWriter); err = parser.getOtherMessages(true); assertTrue(err, null == err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); config = parser.genBuildConfig(new String[] { "-1.3" }, messageWriter); err = parser.getOtherMessages(true); assertTrue(err, null == err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); config = parser.genBuildConfig(new String[] { "-classpath", ENTRY, "-1.4" }, messageWriter); err = parser.getOtherMessages(true); assertTrue("expected errors for missing jars", null != err); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); } finally { // do finally to avoid messing up classpath for other tests System.setProperty("java.class.path", classpath); String setPath = System.getProperty("java.class.path"); String m = "other tests will fail - classpath not reset"; assertEquals(m, classpath, setPath); } } public void testAjOptions() throws InvalidInputException { AjBuildConfig config = parser.genBuildConfig(new String[] { "-Xlint" }, messageWriter); assertTrue( "default options", config.getAjOptions().get(AjCompilerOptions.OPTION_Xlint).equals( CompilerOptions.GENERATE)); } public void testAspectpath() throws InvalidInputException { final String SOURCE_JAR = "testdata/testclasses.jar"; final String SOURCE_JARS = "testdata/testclasses.jar" + File.pathSeparator + "../weaver/testdata/tracing.jar" + File.pathSeparator + "../weaver/testdata/dummyAspect.jar"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-aspectpath", SOURCE_JAR }, messageWriter); assertTrue(((File)config.getAspectpath().get(0)).getName(), ((File)config.getAspectpath().get(0)).getName().equals("testclasses.jar")); config = parser.genBuildConfig(new String[] { "-aspectpath", SOURCE_JARS }, messageWriter); assertTrue("size", + config.getAspectpath().size() == 3); } public void testInJars() throws InvalidInputException { final String SOURCE_JAR = "testdata/testclasses.jar"; final String SOURCE_JARS = "testdata/testclasses.jar" + File.pathSeparator + "../weaver/testdata/tracing.jar" + File.pathSeparator + "../weaver/testdata/dummyAspect.jar"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-injars", SOURCE_JAR }, messageWriter); //XXX don't let this remain in both places in beta1 assertTrue( "" + config.getAjOptions().get(AjCompilerOptions.OPTION_InJARs), config.getAjOptions().get(AjCompilerOptions.OPTION_InJARs).equals(CompilerOptions.PRESERVE)); assertTrue(((File)config.getInJars().get(0)).getName(), ((File)config.getInJars().get(0)).getName().equals("testclasses.jar")); config = parser.genBuildConfig(new String[] { "-injars", SOURCE_JARS }, messageWriter); assertTrue("size", + config.getInJars().size() == 3); } public void testBadInJars() throws InvalidInputException { final String SOURCE_JARS = "testdata/testclasses.jar" + File.pathSeparator + "b.far" + File.pathSeparator + "c.jar"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-injars", SOURCE_JARS }, messageWriter); assertTrue("size: " + config.getInJars().size(), config.getInJars().size() == 1); } public void testMultipleSourceRoots() throws InvalidInputException { final String SRCROOT_1 = "testdata/src1/p1"; final String SRCROOT_2 = "testdata/ajc"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-sourceroots", SRCROOT_1 + File.pathSeparator + SRCROOT_2 }, messageWriter); assertEquals(new File(SRCROOT_1).getAbsolutePath(), ((File)config.getSourceRoots().get(0)).getAbsolutePath()); Collection expectedFiles = Arrays.asList(new File[] { new File(SRCROOT_1+File.separator+"A.java").getAbsoluteFile(), new File(SRCROOT_1+File.separator+"Foo.java").getAbsoluteFile(), new File(SRCROOT_2+File.separator+"A.java").getAbsoluteFile(), new File(SRCROOT_2+File.separator+"B.java").getAbsoluteFile(), new File(SRCROOT_2+File.separator+"X.aj").getAbsoluteFile(), new File(SRCROOT_2+File.separator+"Y.aj").getAbsoluteFile(), new File(SRCROOT_2+File.separator+"pkg"+File.separator+"Hello.java").getAbsoluteFile(), }); //System.out.println(config.getFiles()); TestUtil.assertSetEquals(expectedFiles, config.getFiles()); } public void testSourceRootDir() throws InvalidInputException { final String SRCROOT = "testdata/ajc"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-sourceroots", SRCROOT }, messageWriter); assertEquals(new File(SRCROOT).getAbsolutePath(), ((File)config.getSourceRoots().get(0)).getAbsolutePath()); Collection expectedFiles = Arrays.asList(new File[] { new File(SRCROOT+File.separator+"A.java").getAbsoluteFile(), new File(SRCROOT+File.separator+"B.java").getAbsoluteFile(), new File(SRCROOT+File.separator+"X.aj").getAbsoluteFile(), new File(SRCROOT+File.separator+"Y.aj").getAbsoluteFile(), new File(SRCROOT+File.separator+"pkg"+File.separator+"Hello.java").getAbsoluteFile(), }); //System.out.println(config.getFiles()); TestUtil.assertSetEquals(expectedFiles, config.getFiles()); } public void testBadSourceRootDir() throws InvalidInputException { AjBuildConfig config = parser.genBuildConfig(new String[] { "-sourceroots", "testdata/mumbleDoesNotExist;testdata/ajc" }, messageWriter); assertTrue(config.getSourceRoots().toString(), config.getSourceRoots().size() == 1); config = parser.genBuildConfig(new String[] { "-sourceroots" }, messageWriter); assertTrue("" + config.getSourceRoots(), config.getSourceRoots().size() == 0); } //??? we've decided not to make this an error public void testSourceRootDirWithFiles() throws InvalidInputException { final String SRCROOT = "testdata/ajc/pkg"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-sourceroots", SRCROOT, "testdata/src1/A.java"}, messageWriter); assertEquals(new File(SRCROOT).getAbsolutePath(), ((File)config.getSourceRoots().get(0)).getAbsolutePath()); Collection expectedFiles = Arrays.asList(new File[] { new File(SRCROOT+File.separator+"Hello.java").getAbsoluteFile(), new File("testdata"+File.separator+"src1"+File.separator+"A.java").getAbsoluteFile(), }); TestUtil.assertSetEquals(expectedFiles, config.getFiles()); } public void testExtDirs() throws InvalidInputException { final String DIR = "testdata"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-extdirs", DIR }, messageWriter); assertTrue(config.getClasspath().toString(), config.getClasspath().contains( new File(DIR + File.separator + "testclasses.jar").getAbsolutePath() )); } public void testBootclasspath() throws InvalidInputException { final String PATH = "mumble/rt.jar"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-bootclasspath", PATH }, messageWriter); assertTrue(config.getClasspath().toString(), config.getClasspath().get(0).equals(PATH)); config = parser.genBuildConfig(new String[] { }, messageWriter); assertTrue(config.getClasspath().toString(), !config.getClasspath().get(0).equals(PATH)); } public void testOutputJar() throws InvalidInputException { final String OUT_JAR = "testdata/testclasses.jar"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-outjar", OUT_JAR }, messageWriter); //XXX don't let this remain in both places in beta1 assertTrue( "will generate: " + config.getAjOptions().get(AjCompilerOptions.OPTION_OutJAR), config.getAjOptions().get(AjCompilerOptions.OPTION_OutJAR).equals(CompilerOptions.GENERATE)); assertTrue( "testclasses jar: " + config.getOutputJar().getName(), config.getOutputJar().getAbsolutePath().equals(new File(OUT_JAR).getAbsolutePath())); File nonExistingJar = new File("testdata/mumbleDoesNotExist.jar"); config = parser.genBuildConfig(new String[] { "-outjar", nonExistingJar.getAbsolutePath() }, messageWriter); assertTrue( "testclasses jar: " + config.getOutputJar().getName(), config.getOutputJar().getAbsolutePath().equals(nonExistingJar.getAbsolutePath())); nonExistingJar.delete(); } //XXX shouldn't need -1.4 to get this to pass public void testCombinedOptions() throws InvalidInputException { AjBuildConfig config = parser.genBuildConfig(new String[] { "-Xlint", "-target", "1.4", "-1.4" }, messageWriter); String TARGET = "1.4"; assertTrue( "target set", config.getJavaOptions().get(CompilerOptions.OPTION_TargetPlatform).equals(TARGET)); assertTrue( "Xlint option set", config.getAjOptions().get(AjCompilerOptions.OPTION_Xlint).equals( CompilerOptions.GENERATE)); } public void testOutputDirectorySetting() throws InvalidInputException { AjBuildConfig config = parser.genBuildConfig(new String[] { "-d", TEST_DIR }, messageWriter); assertTrue( new File(config.getOutputDir().getPath()).getAbsolutePath() + " ?= " + new File(TEST_DIR).getAbsolutePath(), config.getOutputDir().getAbsolutePath().equals((new File(TEST_DIR)).getAbsolutePath())); } public void testClasspathSetting() throws InvalidInputException { String ENTRY = "1.jar;2.jar"; AjBuildConfig config = parser.genBuildConfig(new String[] { "-classpath", ENTRY }, messageWriter); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("1.jar")); assertTrue( config.getClasspath().toString(), config.getClasspath().contains("2.jar")); } public void testArgInConfigFile() throws InvalidInputException { String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst"; String OUT_PATH = "bin"; AjBuildConfig config = parser.genBuildConfig(new String[] { FILE_PATH }, messageWriter); assertNotNull(config); File outputDir = config.getOutputDir(); assertNotNull(outputDir); assertEquals(outputDir.getPath(), OUT_PATH); } public void testXlint() throws InvalidInputException { AjdtCommand command = new AjdtCommand(); AjBuildConfig config = parser.genBuildConfig(new String[] {"-Xlint"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_DEFAULT)); config = parser.genBuildConfig(new String[] {"-Xlint:warn"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_WARN)); config = parser.genBuildConfig(new String[] {"-Xlint:error"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_ERROR)); config = parser.genBuildConfig(new String[] {"-Xlint:ignore"}, messageWriter); assertTrue("", config.getLintMode().equals(AjBuildConfig.AJLINT_INGORE)); } public void testXlintfile() throws InvalidInputException { String lintFile = "testdata/lintspec.properties"; String badLintFile = "lint.props"; AjBuildConfig config = parser.genBuildConfig(new String[] {"-Xlintfile", lintFile}, messageWriter); assertTrue(new File(lintFile).exists()); assertTrue(config.getLintSpecFile().getAbsolutePath(), config.getLintSpecFile().getAbsolutePath().equals(new File(lintFile).getAbsolutePath())); } public void testOptions() throws InvalidInputException { AjdtCommand command = new AjdtCommand(); String TARGET = "1.4"; AjBuildConfig config = parser.genBuildConfig(new String[] {"-target", TARGET, "-source", TARGET}, messageWriter); assertTrue( "target set", config.getJavaOptions().get(CompilerOptions.OPTION_TargetPlatform).equals(TARGET)); assertTrue( "source set", config.getJavaOptions().get(CompilerOptions.OPTION_Compliance).equals(CompilerOptions.VERSION_1_4)); } public void testLstFileExpansion() throws IOException, FileNotFoundException, InvalidInputException { String FILE_PATH = TEST_DIR + "config.lst"; String SOURCE_PATH_1 = "A.java"; String SOURCE_PATH_2 = "B.java"; File f = new File(FILE_PATH); AjBuildConfig config = parser.genBuildConfig(new String[] { "@" + FILE_PATH }, messageWriter); List resultList = config.getFiles(); assertTrue("correct number of files", resultList.size() == 2); assertTrue(resultList.toString() + new File(TEST_DIR + SOURCE_PATH_1).getAbsoluteFile(), resultList.contains(new File(TEST_DIR + SOURCE_PATH_1).getAbsoluteFile())); assertTrue(resultList.toString() + SOURCE_PATH_2, resultList.contains(new File(TEST_DIR + SOURCE_PATH_2).getAbsoluteFile())); } //??? do we need to remove this limitation // public void testArgInConfigFileAndRelativizingPathParam() throws InvalidInputException { // String FILE_PATH = "@" + TEST_DIR + "configWithArgs.lst"; // String OUT_PATH = TEST_DIR + "bin"; // AjBuildConfig config = parser.genBuildConfig(new String[] { FILE_PATH }); // // assertTrue( // config.getOutputDir().getPath() + " ?= " + OUT_PATH, // config.getOutputDir().getAbsolutePath().equals((new File(OUT_PATH)).getAbsolutePath())); // } public void testAjFileInclusion() throws InvalidInputException { parser.genBuildConfig(new String[] { TEST_DIR + "X.aj", TEST_DIR + "Y.aj"}, messageWriter); } protected void setUp() throws Exception { super.setUp(); } protected void tearDown() throws Exception { super.tearDown(); } }
29,959
Bug 29959 super call in intertype method declaration body causes VerifyError
AspectJ Compiler 1.1beta4 This program: aspect Foo { void A.foo() { } void B.foo() { super.foo(); } } class A { } class B extends A { } class Main { public static void main(String[] args) { new B(); } } causes this error at runtime: Exception in thread "main" java.lang.VerifyError: (class: B, method: ajc$superDispatch$B$foo signature: ()V) Illegal use of nonvirtual function call at Main.main(Foo.java:11) Note that foo is never even called; the error happens at load time when the new B() expression causes class B to be loaded. There's no error if either one of the foo methods is declared in its class directly. This is kind of a showstopper... --Doug
resolved fixed
3e2801a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-02-13T21:00:35Z
2003-01-22T12:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/InterTypeConstructorDeclaration.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import org.aspectj.ajdt.internal.compiler.lookup.*; import org.aspectj.weaver.*; import org.eclipse.jdt.internal.compiler.*; import org.eclipse.jdt.internal.compiler.ast.*; import org.eclipse.jdt.internal.compiler.lookup.*; import org.eclipse.jdt.internal.compiler.parser.Parser; public class InterTypeConstructorDeclaration extends InterTypeDeclaration { private MethodDeclaration preMethod; private ExplicitConstructorCall explicitConstructorCall = null; public InterTypeConstructorDeclaration(CompilationResult result, TypeReference onType) { super(result, onType); } public void parseStatements(Parser parser, CompilationUnitDeclaration unit) { if (ignoreFurtherInvestigation) return; parser.parseAsConstructor(this, unit); } public void resolve(ClassScope upperScope) { if (munger == null || binding == null) ignoreFurtherInvestigation = true; if (ignoreFurtherInvestigation) return; explicitConstructorCall = null; if (statements != null && statements.length > 0 && statements[0] instanceof ExplicitConstructorCall) { explicitConstructorCall = (ExplicitConstructorCall) statements[0]; statements = AstUtil.remove(0, statements); } preMethod = makePreMethod(upperScope, explicitConstructorCall); binding.parameters = AstUtil.insert(onTypeBinding, binding.parameters); this.arguments = AstUtil.insert( AstUtil.makeFinalArgument("ajc$this_".toCharArray(), onTypeBinding), this.arguments); super.resolve(upperScope); } private MethodDeclaration makePreMethod(ClassScope scope, ExplicitConstructorCall explicitConstructorCall) { EclipseWorld world = EclipseWorld.fromScopeLookupEnvironment(scope); TypeX aspectTypeX = EclipseWorld.fromBinding(binding.declaringClass); TypeX targetTypeX = EclipseWorld.fromBinding(onTypeBinding); ArrayBinding objectArrayBinding = scope.createArray(scope.getJavaLangObject(), 1); MethodDeclaration pre = new MethodDeclaration(compilationResult); pre.modifiers = AccPublic | AccStatic; pre.returnType = AstUtil.makeTypeReference(objectArrayBinding); pre.selector = NameMangler.postIntroducedConstructor(aspectTypeX, targetTypeX).toCharArray(); pre.arguments = AstUtil.copyArguments(this.arguments); //XXX should do exceptions pre.scope = new MethodScope(scope, pre, true); //??? do we need to do anything with scope??? pre.binding = world.makeMethodBinding( AjcMemberMaker.preIntroducedConstructor(aspectTypeX, targetTypeX, world.fromBindings(binding.parameters))); pre.bindArguments(); pre.bindThrownExceptions(); if (explicitConstructorCall == null) { pre.statements = new Statement[] {}; } else { pre.statements = new Statement[] { explicitConstructorCall }; } InterTypeScope newParent = new InterTypeScope(scope, onTypeBinding); pre.scope.parent = newParent; pre.resolveStatements(newParent); int nParams = pre.arguments.length; MethodBinding explicitConstructor = null; if (explicitConstructorCall != null) { explicitConstructor = explicitConstructorCall.binding; if (explicitConstructor.alwaysNeedsAccessMethod()) { explicitConstructor = explicitConstructor.getAccessMethod(); } } int nExprs; if (explicitConstructor == null) nExprs = 0; else nExprs = explicitConstructor.parameters.length; ArrayInitializer init = new ArrayInitializer(); init.expressions = new Expression[nExprs + nParams]; int index = 0; for (int i=0; i < nExprs; i++) { if (i >= explicitConstructorCall.arguments.length) { init.expressions[index++] = new NullLiteral(0, 0); continue; } Expression arg = explicitConstructorCall.arguments[i]; ResolvedMember conversionMethod = AjcMemberMaker.toObjectConversionMethod(world.fromBinding(explicitConstructorCall.binding.parameters[i])); if (conversionMethod != null) { arg = new KnownMessageSend(world.makeMethodBindingForCall(conversionMethod), new CastExpression(new NullLiteral(0, 0), AstUtil.makeTypeReference(world.makeTypeBinding(AjcMemberMaker.CONVERSIONS_TYPE))), new Expression[] {arg }); } init.expressions[index++] = arg; } for (int i=0; i < nParams; i++) { LocalVariableBinding binding = pre.arguments[i].binding; Expression arg = AstUtil.makeResolvedLocalVariableReference(binding); ResolvedMember conversionMethod = AjcMemberMaker.toObjectConversionMethod(world.fromBinding(binding.type)); if (conversionMethod != null) { arg = new KnownMessageSend(world.makeMethodBindingForCall(conversionMethod), new CastExpression(new NullLiteral(0, 0), AstUtil.makeTypeReference(world.makeTypeBinding(AjcMemberMaker.CONVERSIONS_TYPE))), new Expression[] {arg }); } init.expressions[index++] = arg; } init.binding =objectArrayBinding; ArrayAllocationExpression newArray = new ArrayAllocationExpression(); newArray.initializer = init; newArray.type = AstUtil.makeTypeReference(scope.getJavaLangObject()); newArray.dimensions = new Expression[1]; newArray.constant = NotAConstant; pre.statements = new Statement[] { new ReturnStatement(newArray, 0, 0), }; return pre; } public void build(ClassScope classScope, CrosscuttingMembers xcut) { EclipseWorld world = EclipseWorld.fromScopeLookupEnvironment(classScope); binding = classScope.referenceContext.binding.resolveTypesFor(binding); resolveOnType(classScope); if (ignoreFurtherInvestigation) return; if (onTypeBinding.isInterface()) { ignoreFurtherInvestigation = true; return; } if (onTypeBinding.isNestedType()) { classScope.problemReporter().signalError(sourceStart, sourceEnd, "can't define constructors on nested types (compiler limitation)"); ignoreFurtherInvestigation = true; return; } ResolvedTypeX declaringTypeX = world.fromEclipse(onTypeBinding); ResolvedTypeX aspectType = world.fromEclipse(classScope.referenceContext.binding); ResolvedMember bindingAsMember = world.makeResolvedMember(binding); ResolvedMember signature = new ResolvedMember(Member.CONSTRUCTOR, declaringTypeX, declaredModifiers, ResolvedTypeX.VOID, "<init>", bindingAsMember.getParameterTypes()); signature.setCheckedExceptions(world.fromEclipse(binding.thrownExceptions)); ResolvedMember syntheticInterMember = AjcMemberMaker.interConstructor(declaringTypeX, signature, aspectType); NewConstructorTypeMunger myMunger = new NewConstructorTypeMunger(signature, syntheticInterMember, null, null); setMunger(myMunger); myMunger.check(world); this.selector = binding.selector = NameMangler.postIntroducedConstructor( EclipseWorld.fromBinding(binding.declaringClass), declaringTypeX).toCharArray(); xcut.addTypeMunger(new EclipseTypeMunger(myMunger, aspectType, this)); } private AjAttribute makeAttribute(EclipseWorld world) { if (explicitConstructorCall != null && !(explicitConstructorCall.binding instanceof ProblemMethodBinding)) { MethodBinding explicitConstructor = explicitConstructorCall.binding; if (explicitConstructor.alwaysNeedsAccessMethod()) { explicitConstructor = explicitConstructor.getAccessMethod(); } ((NewConstructorTypeMunger)munger).setExplicitConstructor( world.makeResolvedMember(explicitConstructor)); } else { ((NewConstructorTypeMunger)munger).setExplicitConstructor( new ResolvedMember(Member.CONSTRUCTOR, EclipseWorld.fromBinding(onTypeBinding.superclass()), 0, ResolvedTypeX.VOID, "<init>", TypeX.NONE)); } return new AjAttribute.TypeMunger(munger); } public void generateCode(ClassScope classScope, ClassFile classFile) { if (ignoreFurtherInvestigation) return; EclipseWorld world = EclipseWorld.fromScopeLookupEnvironment(classScope); classFile.extraAttributes.add(new EclipseAttributeAdapter(makeAttribute(world))); super.generateCode(classScope, classFile); preMethod.generateCode(classScope, classFile); } protected Shadow.Kind getShadowKindForBody() { return Shadow.ConstructorExecution; } }
29,959
Bug 29959 super call in intertype method declaration body causes VerifyError
AspectJ Compiler 1.1beta4 This program: aspect Foo { void A.foo() { } void B.foo() { super.foo(); } } class A { } class B extends A { } class Main { public static void main(String[] args) { new B(); } } causes this error at runtime: Exception in thread "main" java.lang.VerifyError: (class: B, method: ajc$superDispatch$B$foo signature: ()V) Illegal use of nonvirtual function call at Main.main(Foo.java:11) Note that foo is never even called; the error happens at load time when the new B() expression causes class B to be loaded. There's no error if either one of the foo methods is declared in its class directly. This is kind of a showstopper... --Doug
resolved fixed
3e2801a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-02-13T21:00:35Z
2003-01-22T12:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/ast/SuperFixerVisitor.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.ast; import java.util.*; import java.util.Arrays; import org.aspectj.ajdt.internal.compiler.lookup.EclipseWorld; import org.aspectj.weaver.*; import org.aspectj.weaver.ShadowMunger; import org.eclipse.jdt.internal.compiler.AbstractSyntaxTreeVisitorAdapter; import org.eclipse.jdt.internal.compiler.ast.*; import org.eclipse.jdt.internal.compiler.lookup.*; /** * Takes a method that already has the three extra parameters * thisJoinPointStaticPart, thisJoinPoint and thisEnclosingJoinPointStaticPart */ public class SuperFixerVisitor extends AbstractSyntaxTreeVisitorAdapter { Set superMethodsCalled = new HashSet(); AbstractMethodDeclaration method; ReferenceBinding targetClass; SuperFixerVisitor(AbstractMethodDeclaration method, ReferenceBinding targetClass) { this.method = method; this.targetClass = targetClass; } //XXX does this walk into inners public void endVisit(MessageSend call, BlockScope scope) { //System.out.println("endVisit: " + call); // an error has already occurred if (call.codegenBinding == null) return; MethodBinding superBinding = call.codegenBinding; if (superBinding instanceof ProblemMethodBinding) { return; } char[] accessName; if (call.isSuperAccess() && !call.binding.isStatic()) { call.receiver = new ThisReference(); accessName = NameMangler.superDispatchMethod(EclipseWorld.fromBinding(targetClass), new String(superBinding.selector)).toCharArray(); } else if (call.receiver.isThis() && call.binding.isProtected() && !call.binding.isStatic()) { //XXX this is a hack that violates some binary compatibility rules if (superBinding.declaringClass.equals(targetClass)) { accessName = NameMangler.protectedDispatchMethod(EclipseWorld.fromBinding(targetClass), new String(superBinding.selector)).toCharArray(); } else { accessName = NameMangler.superDispatchMethod(EclipseWorld.fromBinding(targetClass), new String(superBinding.selector)).toCharArray(); } } else { return; } //??? do we want these to be unique MethodBinding superAccessBinding = new MethodBinding(AstNode.AccPublic, accessName, superBinding.returnType, superBinding.parameters, superBinding.thrownExceptions, targetClass); call.codegenBinding = superAccessBinding; ResolvedMember targetMember = EclipseWorld.makeResolvedMember(superBinding); superMethodsCalled.add(targetMember); } }
29,959
Bug 29959 super call in intertype method declaration body causes VerifyError
AspectJ Compiler 1.1beta4 This program: aspect Foo { void A.foo() { } void B.foo() { super.foo(); } } class A { } class B extends A { } class Main { public static void main(String[] args) { new B(); } } causes this error at runtime: Exception in thread "main" java.lang.VerifyError: (class: B, method: ajc$superDispatch$B$foo signature: ()V) Illegal use of nonvirtual function call at Main.main(Foo.java:11) Note that foo is never even called; the error happens at load time when the new B() expression causes class B to be loaded. There's no error if either one of the foo methods is declared in its class directly. This is kind of a showstopper... --Doug
resolved fixed
3e2801a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-02-13T21:00:35Z
2003-01-22T12:53:20Z
org.aspectj.ajdt.core/src/org/aspectj/ajdt/internal/compiler/lookup/InterTypeMethodBinding.java
/* ******************************************************************* * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC). * All rights reserved. * This program and the accompanying materials are made available * under the terms of the Common Public License v1.0 * which accompanies this distribution and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * PARC initial implementation * ******************************************************************/ package org.aspectj.ajdt.internal.compiler.lookup; import org.aspectj.weaver.*; import org.eclipse.jdt.internal.compiler.ast.AbstractMethodDeclaration; import org.eclipse.jdt.internal.compiler.lookup.*; public class InterTypeMethodBinding extends MethodBinding { //private ReferenceBinding withinType; private ReferenceBinding targetType; private MethodBinding syntheticMethod; //public MethodBinding introducedMethod; public AbstractMethodDeclaration sourceMethod; public InterTypeMethodBinding(EclipseWorld world, ResolvedMember signature, TypeX withinType, AbstractMethodDeclaration sourceMethod) { super(world.makeMethodBinding(signature), null); this.sourceMethod = sourceMethod; targetType = (ReferenceBinding)world.makeTypeBinding(signature.getDeclaringType()); this.declaringClass = (ReferenceBinding)world.makeTypeBinding(withinType); if (signature.getKind() == Member.METHOD) { syntheticMethod = world.makeMethodBinding(AjcMemberMaker.interMethodDispatcher(signature, withinType)); } else { syntheticMethod = world.makeMethodBinding( AjcMemberMaker.interConstructor(world.resolve(signature.getDeclaringType()), signature, withinType)); } } // // this.declaringClass = // // // // char[] dispatch2Name; // if (Modifier.isPublic(modifiers)) { // dispatch2Name = name; // } else if (Modifier.isPrivate(modifiers)) { // dispatch2Name = // AstUtil.makeAjcMangledName("dispatch2".toCharArray(), withinType, selector); // } else { // // package visible // //??? optimize both in same package // dispatch2Name = // AstUtil.makeAjcMangledName("dispatch2".toCharArray(), // withinType.qualifiedPackageName(), selector); // } // // introducedMethod = // new MethodBinding(AstUtil.makePublic(modifiers), dispatch2Name, // type, args, exceptions, declaringClass); // // this.dispatchMethod = // new DispatchMethodBinding(introducedMethod, withinType, mangledParams); // } //XXX this is identical to InterTypeFieldBinding public boolean canBeSeenBy(TypeBinding receiverType, InvocationSite invocationSite, Scope scope) { if (isPublic()) return true; SourceTypeBinding invocationType = scope.invocationType(); //System.out.println("receiver: " + receiverType + ", " + invocationType); if (invocationType == declaringClass) return true; // if (invocationType.isPrivileged) { // System.out.println("privileged access to: " + this); // return true; // } if (isProtected()) { throw new RuntimeException("unimplemented"); } //XXX make sure this walks correctly if (isPrivate()) { // answer true if the receiverType is the declaringClass // AND the invocationType and the declaringClass have a common enclosingType //if (receiverType != declaringClass) return false; if (invocationType != declaringClass) { ReferenceBinding outerInvocationType = invocationType; ReferenceBinding temp = outerInvocationType.enclosingType(); while (temp != null) { outerInvocationType = temp; temp = temp.enclosingType(); } ReferenceBinding outerDeclaringClass = declaringClass; temp = outerDeclaringClass.enclosingType(); while (temp != null) { outerDeclaringClass = temp; temp = temp.enclosingType(); } //System.err.println("outer dec: " + if (outerInvocationType != outerDeclaringClass) return false; } return true; } // isDefault() if (invocationType.fPackage == declaringClass.fPackage) return true; return false; } public MethodBinding getAccessMethod() { return syntheticMethod; } public boolean alwaysNeedsAccessMethod() { return true; } public AbstractMethodDeclaration sourceMethod() { return sourceMethod; } public ReferenceBinding getTargetType() { return targetType; } public String toString() { return "InterTypeMethodBinding(" + super.toString() + ", " + getTargetType() +")"; } }
29,959
Bug 29959 super call in intertype method declaration body causes VerifyError
AspectJ Compiler 1.1beta4 This program: aspect Foo { void A.foo() { } void B.foo() { super.foo(); } } class A { } class B extends A { } class Main { public static void main(String[] args) { new B(); } } causes this error at runtime: Exception in thread "main" java.lang.VerifyError: (class: B, method: ajc$superDispatch$B$foo signature: ()V) Illegal use of nonvirtual function call at Main.main(Foo.java:11) Note that foo is never even called; the error happens at load time when the new B() expression causes class B to be loaded. There's no error if either one of the foo methods is declared in its class directly. This is kind of a showstopper... --Doug
resolved fixed
3e2801a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-02-13T21:00:35Z
2003-01-22T12:53:20Z
org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/AllocationExpression.java
/******************************************************************************* * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.compiler.ast; import org.eclipse.jdt.internal.compiler.IAbstractSyntaxTreeVisitor; import org.eclipse.jdt.internal.compiler.codegen.*; import org.eclipse.jdt.internal.compiler.flow.*; import org.eclipse.jdt.internal.compiler.lookup.*; public class AllocationExpression extends Expression implements InvocationSite { public TypeReference type; public Expression[] arguments; public MethodBinding binding; MethodBinding syntheticAccessor; public AllocationExpression() { super(); } public FlowInfo analyseCode( BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { // must verify that exceptions potentially thrown by this expression are caught in the method // process arguments if (arguments != null) { for (int i = 0, count = arguments.length; i < count; i++) { flowInfo = arguments[i] .analyseCode(currentScope, flowContext, flowInfo) .unconditionalInits(); } } // record some dependency information for exception types ReferenceBinding[] thrownExceptions; if (((thrownExceptions = binding.thrownExceptions).length) != 0) { // check exception handling flowContext.checkExceptionHandlers( thrownExceptions, this, flowInfo, currentScope); } manageEnclosingInstanceAccessIfNecessary(currentScope); manageSyntheticAccessIfNecessary(currentScope); return flowInfo; } public Expression enclosingInstance() { return null; } public void generateCode( BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; ReferenceBinding allocatedType; if (syntheticAccessor != null) { allocatedType = syntheticAccessor.declaringClass; } else { allocatedType = binding.declaringClass; } codeStream.new_(allocatedType); if (valueRequired) { codeStream.dup(); } // better highlight for allocation: display the type individually codeStream.recordPositionsFrom(pc, type.sourceStart); // handling innerclass instance allocation if (allocatedType.isNestedType()) { codeStream.generateSyntheticArgumentValues( currentScope, allocatedType, enclosingInstance(), this); } // generate the arguments for constructor if (arguments != null) { for (int i = 0, count = arguments.length; i < count; i++) { arguments[i].generateCode(currentScope, codeStream, true); } } // invoke constructor if (syntheticAccessor == null) { codeStream.invokespecial(binding); } else { // synthetic accessor got some extra arguments appended to its signature, which need values for (int i = 0, max = syntheticAccessor.parameters.length - binding.parameters.length; i < max; i++) { codeStream.aconst_null(); } codeStream.invokespecial(syntheticAccessor); } codeStream.recordPositionsFrom(pc, this.sourceStart); } public boolean isSuperAccess() { return false; } public boolean isTypeAccess() { return true; } /* Inner emulation consists in either recording a dependency * link only, or performing one level of propagation. * * Dependency mechanism is used whenever dealing with source target * types, since by the time we reach them, we might not yet know their * exact need. */ public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { ReferenceBinding allocatedType; // perform some emulation work in case there is some and we are inside a local type only if ((allocatedType = binding.declaringClass).isNestedType() && currentScope.enclosingSourceType().isLocalType()) { if (allocatedType.isLocalType()) { ((LocalTypeBinding) allocatedType).addInnerEmulationDependent( currentScope, false, false); // request cascade of accesses } else { // locally propagate, since we already now the desired shape for sure currentScope.propagateInnerEmulation(allocatedType, false, false); // request cascade of accesses } } } public void manageSyntheticAccessIfNecessary(BlockScope currentScope) { if (binding.alwaysNeedsAccessMethod()) { syntheticAccessor = binding.getAccessMethod(); return; } if (binding.isPrivate() && (currentScope.enclosingSourceType() != binding.declaringClass)) { if (currentScope .environment() .options .isPrivateConstructorAccessChangingVisibility) { binding.tagForClearingPrivateModifier(); // constructor will not be dumped as private, no emulation required thus } else { syntheticAccessor = ((SourceTypeBinding) binding.declaringClass).addSyntheticMethod(binding); currentScope.problemReporter().needToEmulateMethodAccess(binding, this); } } } public TypeBinding resolveType(BlockScope scope) { // Propagate the type checking to the arguments, and check if the constructor is defined. constant = NotAConstant; TypeBinding typeBinding = type.resolveType(scope); // will check for null after args are resolved // buffering the arguments' types TypeBinding[] argumentTypes = NoParameters; if (arguments != null) { boolean argHasError = false; int length = arguments.length; argumentTypes = new TypeBinding[length]; for (int i = 0; i < length; i++) if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null) argHasError = true; if (argHasError) return typeBinding; } if (typeBinding == null) return null; if (!typeBinding.canBeInstantiated()) { scope.problemReporter().cannotInstantiate(type, typeBinding); return typeBinding; } ReferenceBinding allocatedType = (ReferenceBinding) typeBinding; if (!(binding = scope.getConstructor(allocatedType, argumentTypes, this)) .isValidBinding()) { if (binding.declaringClass == null) binding.declaringClass = allocatedType; scope.problemReporter().invalidConstructor(this, binding); return typeBinding; } if (isMethodUseDeprecated(binding, scope)) scope.problemReporter().deprecatedMethod(binding, this); if (arguments != null) for (int i = 0; i < arguments.length; i++) arguments[i].implicitWidening(binding.parameters[i], argumentTypes[i]); return allocatedType; } public void setActualReceiverType(ReferenceBinding receiverType) { // ignored } public void setDepth(int i) { // ignored } public void setFieldIndex(int i) { // ignored } public String toStringExpression() { String s = "new " + type.toString(0); //$NON-NLS-1$ if (arguments == null) s = s + "()"; //$NON-NLS-1$ else { s = s + "("; //$NON-NLS-1$ for (int i = 0; i < arguments.length; i++) { s = s + arguments[i].toStringExpression(); if (i == (arguments.length - 1)) s = s + ")"; //$NON-NLS-1$ else s = s + ", "; //$NON-NLS-1$ } } return s; } public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { int argumentsLength; type.traverse(visitor, scope); if (arguments != null) { argumentsLength = arguments.length; for (int i = 0; i < argumentsLength; i++) arguments[i].traverse(visitor, scope); } } visitor.endVisit(this, scope); } }
29,959
Bug 29959 super call in intertype method declaration body causes VerifyError
AspectJ Compiler 1.1beta4 This program: aspect Foo { void A.foo() { } void B.foo() { super.foo(); } } class A { } class B extends A { } class Main { public static void main(String[] args) { new B(); } } causes this error at runtime: Exception in thread "main" java.lang.VerifyError: (class: B, method: ajc$superDispatch$B$foo signature: ()V) Illegal use of nonvirtual function call at Main.main(Foo.java:11) Note that foo is never even called; the error happens at load time when the new B() expression causes class B to be loaded. There's no error if either one of the foo methods is declared in its class directly. This is kind of a showstopper... --Doug
resolved fixed
3e2801a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-02-13T21:00:35Z
2003-01-22T12:53:20Z
org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/ExplicitConstructorCall.java
/******************************************************************************* * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation ******************************************************************************/ package org.eclipse.jdt.internal.compiler.ast; import org.eclipse.jdt.internal.compiler.IAbstractSyntaxTreeVisitor; import org.eclipse.jdt.internal.compiler.codegen.*; import org.eclipse.jdt.internal.compiler.flow.*; import org.eclipse.jdt.internal.compiler.lookup.*; public class ExplicitConstructorCall extends Statement implements InvocationSite { public Expression[] arguments; public Expression qualification; public MethodBinding binding; public int accessMode; public final static int ImplicitSuper = 1; public final static int Super = 2; public final static int This = 3; public VariableBinding[][] implicitArguments; boolean discardEnclosingInstance; MethodBinding syntheticAccessor; public ExplicitConstructorCall(int accessMode) { this.accessMode = accessMode; } public FlowInfo analyseCode( BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { // must verify that exceptions potentially thrown by this expression are caught in the method. try { ((MethodScope) currentScope).isConstructorCall = true; // process enclosing instance if (qualification != null) { flowInfo = qualification .analyseCode(currentScope, flowContext, flowInfo) .unconditionalInits(); } // process arguments if (arguments != null) { for (int i = 0, max = arguments.length; i < max; i++) { flowInfo = arguments[i] .analyseCode(currentScope, flowContext, flowInfo) .unconditionalInits(); } } ReferenceBinding[] thrownExceptions; if ((thrownExceptions = binding.thrownExceptions) != NoExceptions) { // check exceptions flowContext.checkExceptionHandlers( thrownExceptions, (accessMode == ImplicitSuper) ? (AstNode) currentScope.methodScope().referenceContext : (AstNode) this, flowInfo, currentScope); } manageEnclosingInstanceAccessIfNecessary(currentScope); manageSyntheticAccessIfNecessary(currentScope); return flowInfo; } finally { ((MethodScope) currentScope).isConstructorCall = false; } } /** * Constructor call code generation * * @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope * @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream */ public void generateCode(BlockScope currentScope, CodeStream codeStream) { if ((bits & IsReachableMASK) == 0) { return; } try { ((MethodScope) currentScope).isConstructorCall = true; int pc = codeStream.position; codeStream.aload_0(); // handling innerclass constructor invocation ReferenceBinding targetType; if ((targetType = binding.declaringClass).isNestedType()) { codeStream.generateSyntheticArgumentValues( currentScope, targetType, discardEnclosingInstance ? null : qualification, this); } // regular code gen if (arguments != null) { for (int i = 0, max = arguments.length; i < max; i++) { arguments[i].generateCode(currentScope, codeStream, true); } } if (syntheticAccessor != null) { // synthetic accessor got some extra arguments appended to its signature, which need values for (int i = 0, max = syntheticAccessor.parameters.length - binding.parameters.length; i < max; i++) { codeStream.aconst_null(); } codeStream.invokespecial(syntheticAccessor); } else { codeStream.invokespecial(binding); } codeStream.recordPositionsFrom(pc, this.sourceStart); } finally { ((MethodScope) currentScope).isConstructorCall = false; } } public boolean isImplicitSuper() { //return true if I'm of these compiler added statement super(); return (accessMode == ImplicitSuper); } public boolean isSuperAccess() { return accessMode != This; } public boolean isTypeAccess() { return true; } /* Inner emulation consists in either recording a dependency * link only, or performing one level of propagation. * * Dependency mechanism is used whenever dealing with source target * types, since by the time we reach them, we might not yet know their * exact need. */ void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { ReferenceBinding superType; // perform some emulation work in case there is some and we are inside a local type only if ((superType = binding.declaringClass).isNestedType() && currentScope.enclosingSourceType().isLocalType()) { if (superType.isLocalType()) { ((LocalTypeBinding) superType).addInnerEmulationDependent( currentScope, qualification != null, true); // request direct access } else { // locally propagate, since we already now the desired shape for sure currentScope.propagateInnerEmulation(superType, qualification != null, true); // request direct access } } } public void manageSyntheticAccessIfNecessary(BlockScope currentScope) { if (binding.alwaysNeedsAccessMethod()) { syntheticAccessor = binding.getAccessMethod(); return; } // perform some emulation work in case there is some and we are inside a local type only if (binding.isPrivate() && (accessMode != This)) { if (currentScope .environment() .options .isPrivateConstructorAccessChangingVisibility) { binding.tagForClearingPrivateModifier(); // constructor will not be dumped as private, no emulation required thus } else { syntheticAccessor = ((SourceTypeBinding) binding.declaringClass).addSyntheticMethod(binding); currentScope.problemReporter().needToEmulateMethodAccess(binding, this); } } } public void resolve(BlockScope scope) { // the return type should be void for a constructor. // the test is made into getConstructor // mark the fact that we are in a constructor call..... // unmark at all returns try { ((MethodScope) scope).isConstructorCall = true; ReferenceBinding receiverType = scope.enclosingSourceType(); //System.err.println("rT: " + receiverType + " scope " + scope); if (accessMode != This) receiverType = receiverType.superclass(); if (receiverType == null) { return; } // qualification should be from the type of the enclosingType if (qualification != null) { if (accessMode != Super) { scope.problemReporter().unnecessaryEnclosingInstanceSpecification( qualification, receiverType); } ReferenceBinding enclosingType = receiverType.enclosingType(); if (enclosingType == null) { scope.problemReporter().unnecessaryEnclosingInstanceSpecification( qualification, receiverType); discardEnclosingInstance = true; } else { TypeBinding qTb = qualification.resolveTypeExpecting(scope, enclosingType); qualification.implicitWidening(qTb, qTb); } } // arguments buffering for the method lookup TypeBinding[] argTypes = NoParameters; if (arguments != null) { boolean argHasError = false; // typeChecks all arguments int length = arguments.length; argTypes = new TypeBinding[length]; for (int i = 0; i < length; i++) if ((argTypes[i] = arguments[i].resolveType(scope)) == null) argHasError = true; if (argHasError) return; } if ((binding = scope.getConstructor(receiverType, argTypes, this)) .isValidBinding()) { if (isMethodUseDeprecated(binding, scope)) scope.problemReporter().deprecatedMethod(binding, this); // see for user-implicit widening conversion if (arguments != null) { int length = arguments.length; TypeBinding[] paramTypes = binding.parameters; for (int i = 0; i < length; i++) arguments[i].implicitWidening(paramTypes[i], argTypes[i]); } } else { if (binding.declaringClass == null) binding.declaringClass = receiverType; scope.problemReporter().invalidConstructor(this, binding); } } finally { ((MethodScope) scope).isConstructorCall = false; } } public void setActualReceiverType(ReferenceBinding receiverType) { // ignored } public void setDepth(int depth) { // ignore for here } public void setFieldIndex(int depth) { // ignore for here } public String toString(int tab) { String s = tabString(tab); if (qualification != null) s = s + qualification.toStringExpression() + "."; //$NON-NLS-1$ if (accessMode == This) { s = s + "this("; //$NON-NLS-1$ } else { s = s + "super("; //$NON-NLS-1$ } if (arguments != null) for (int i = 0; i < arguments.length; i++) { s = s + arguments[i].toStringExpression(); if (i != arguments.length - 1) s = s + ", "; //$NON-NLS-1$ } s = s + ")"; //$NON-NLS-1$ return s; } public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope scope) { if (visitor.visit(this, scope)) { if (qualification != null) { qualification.traverse(visitor, scope); } if (arguments != null) { int argumentLength = arguments.length; for (int i = 0; i < argumentLength; i++) arguments[i].traverse(visitor, scope); } } visitor.endVisit(this, scope); } }
29,959
Bug 29959 super call in intertype method declaration body causes VerifyError
AspectJ Compiler 1.1beta4 This program: aspect Foo { void A.foo() { } void B.foo() { super.foo(); } } class A { } class B extends A { } class Main { public static void main(String[] args) { new B(); } } causes this error at runtime: Exception in thread "main" java.lang.VerifyError: (class: B, method: ajc$superDispatch$B$foo signature: ()V) Illegal use of nonvirtual function call at Main.main(Foo.java:11) Note that foo is never even called; the error happens at load time when the new B() expression causes class B to be loaded. There's no error if either one of the foo methods is declared in its class directly. This is kind of a showstopper... --Doug
resolved fixed
3e2801a
AspectJ
https://github.com/eclipse/org.aspectj
eclipse/org.aspectj
java
null
null
null
2003-02-13T21:00:35Z
2003-01-22T12:53:20Z
org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/ast/MessageSend.java
/******************************************************************************* * Copyright (c) 2000, 2001, 2002 International Business Machines Corp. and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v0.5 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v05.html * * Contributors: * IBM Corporation - initial API and implementation * Palo Alto Research Center, Incorporated - AspectJ adaptation ******************************************************************************/ package org.eclipse.jdt.internal.compiler.ast; import org.eclipse.jdt.internal.compiler.IAbstractSyntaxTreeVisitor; import org.eclipse.jdt.internal.compiler.impl.*; import org.eclipse.jdt.internal.compiler.flow.*; import org.eclipse.jdt.internal.compiler.codegen.*; import org.eclipse.jdt.internal.compiler.lookup.*; /** * AspectJ - support for MethodBinding.alwaysNeedsAccessMethod */ public class MessageSend extends Expression implements InvocationSite { public Expression receiver ; public char[] selector ; public Expression[] arguments ; public MethodBinding binding, codegenBinding; public long nameSourcePosition ; //(start<<32)+end public MethodBinding syntheticAccessor; public TypeBinding receiverType, qualifyingType; public MessageSend() { } public FlowInfo analyseCode(BlockScope currentScope, FlowContext flowContext, FlowInfo flowInfo) { flowInfo = receiver.analyseCode(currentScope, flowContext, flowInfo, !binding.isStatic()).unconditionalInits(); if (arguments != null) { int length = arguments.length; for (int i = 0; i < length; i++) { flowInfo = arguments[i].analyseCode(currentScope, flowContext, flowInfo).unconditionalInits(); } } ReferenceBinding[] thrownExceptions; if ((thrownExceptions = binding.thrownExceptions) != NoExceptions) { // must verify that exceptions potentially thrown by this expression are caught in the method flowContext.checkExceptionHandlers(thrownExceptions, this, flowInfo, currentScope); } // if invoking through an enclosing instance, then must perform the field generation -- only if reachable manageEnclosingInstanceAccessIfNecessary(currentScope); manageSyntheticAccessIfNecessary(currentScope); return flowInfo; } /** * MessageSend code generation * * @param currentScope org.eclipse.jdt.internal.compiler.lookup.BlockScope * @param codeStream org.eclipse.jdt.internal.compiler.codegen.CodeStream * @param valueRequired boolean */ public void generateCode(BlockScope currentScope, CodeStream codeStream, boolean valueRequired) { int pc = codeStream.position; // generate receiver/enclosing instance access boolean isStatic = codegenBinding.isStatic(); // outer access ? if (!isStatic && ((bits & DepthMASK) != 0) && (receiver == ThisReference.ThisImplicit)){ // outer method can be reached through emulation if implicit access Object[] path = currentScope.getExactEmulationPath(currentScope.enclosingSourceType().enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT)); if (path == null) { // emulation was not possible (should not happen per construction) currentScope.problemReporter().needImplementation(); } else { codeStream.generateOuterAccess(path, this, currentScope); } } else { receiver.generateCode(currentScope, codeStream, !isStatic); } // generate arguments if (arguments != null){ for (int i = 0, max = arguments.length; i < max; i++){ arguments[i].generateCode(currentScope, codeStream, true); } } // actual message invocation if (syntheticAccessor == null){ if (isStatic){ codeStream.invokestatic(codegenBinding); } else { if( (receiver.isSuper()) || codegenBinding.isPrivate()){ codeStream.invokespecial(codegenBinding); } else { if (codegenBinding.declaringClass.isInterface()){ codeStream.invokeinterface(codegenBinding); } else { codeStream.invokevirtual(codegenBinding); } } } } else { codeStream.invokestatic(syntheticAccessor); } // operation on the returned value if (valueRequired){ // implicit conversion if necessary codeStream.generateImplicitConversion(implicitConversion); } else { // pop return value if any switch(binding.returnType.id){ case T_long : case T_double : codeStream.pop2(); break; case T_void : break; default: codeStream.pop(); } } codeStream.recordPositionsFrom(pc, (int)(this.nameSourcePosition >>> 32)); // highlight selector } public boolean isSuperAccess() { return receiver.isSuper(); } public boolean isTypeAccess() { return receiver != null && receiver.isTypeReference(); } public void manageEnclosingInstanceAccessIfNecessary(BlockScope currentScope) { if (((bits & DepthMASK) != 0) && !binding.isStatic() && (receiver == ThisReference.ThisImplicit)) { ReferenceBinding compatibleType = currentScope.enclosingSourceType(); // the declaringClass of the target binding must be compatible with the enclosing // type at <depth> levels outside for (int i = 0, depth = (bits & DepthMASK) >> DepthSHIFT; i < depth; i++) { compatibleType = compatibleType.enclosingType(); } currentScope.emulateOuterAccess((SourceTypeBinding) compatibleType, false); // request cascade of accesses } } public void manageSyntheticAccessIfNecessary(BlockScope currentScope){ if (binding.alwaysNeedsAccessMethod()) { syntheticAccessor = binding.getAccessMethod(); return; } if (binding.isPrivate()){ // depth is set for both implicit and explicit access (see MethodBinding#canBeSeenBy) if (currentScope.enclosingSourceType() != binding.declaringClass){ syntheticAccessor = ((SourceTypeBinding)binding.declaringClass).addSyntheticMethod(binding); currentScope.problemReporter().needToEmulateMethodAccess(binding, this); return; } } else if (receiver instanceof QualifiedSuperReference){ // qualified super // qualified super need emulation always SourceTypeBinding destinationType = (SourceTypeBinding)(((QualifiedSuperReference)receiver).currentCompatibleType); syntheticAccessor = destinationType.addSyntheticMethod(binding); currentScope.problemReporter().needToEmulateMethodAccess(binding, this); return; } else if (binding.isProtected()){ SourceTypeBinding enclosingSourceType; if (((bits & DepthMASK) != 0) && binding.declaringClass.getPackage() != (enclosingSourceType = currentScope.enclosingSourceType()).getPackage()){ SourceTypeBinding currentCompatibleType = (SourceTypeBinding)enclosingSourceType.enclosingTypeAt((bits & DepthMASK) >> DepthSHIFT); syntheticAccessor = currentCompatibleType.addSyntheticMethod(binding); currentScope.problemReporter().needToEmulateMethodAccess(binding, this); return; } } // if the binding declaring class is not visible, need special action // for runtime compatibility on 1.2 VMs : change the declaring class of the binding // NOTE: from 1.4 on, method's declaring class is touched if any different from receiver type // and not from Object or implicit static method call. if (binding.declaringClass != this.qualifyingType && !this.qualifyingType.isArrayType() && ((currentScope.environment().options.complianceLevel >= CompilerOptions.JDK1_4 && (receiver != ThisReference.ThisImplicit || !binding.isStatic()) && binding.declaringClass.id != T_Object) // no change for Object methods || !binding.declaringClass.canBeSeenBy(currentScope))) { this.codegenBinding = currentScope.enclosingSourceType().getUpdatedMethodBinding(binding, (ReferenceBinding) this.qualifyingType); } } public TypeBinding resolveType(BlockScope scope) { // Answer the signature return type // Base type promotion constant = NotAConstant; this.qualifyingType = this.receiverType = receiver.resolveType(scope); // will check for null after args are resolved TypeBinding[] argumentTypes = NoParameters; if (arguments != null) { boolean argHasError = false; // typeChecks all arguments int length = arguments.length; argumentTypes = new TypeBinding[length]; for (int i = 0; i < length; i++){ if ((argumentTypes[i] = arguments[i].resolveType(scope)) == null){ argHasError = true; } } if (argHasError){ MethodBinding closestMethod = null; if(receiverType instanceof ReferenceBinding) { // record any selector match, for clients who may still need hint about possible method match this.codegenBinding = this.binding = scope.findMethod((ReferenceBinding)receiverType, selector, new TypeBinding[]{}, this); } return null; } } if (this.receiverType == null) return null; // base type cannot receive any message if (this.receiverType.isBaseType()) { scope.problemReporter().errorNoMethodFor(this, this.receiverType, argumentTypes); return null; } resolveMethodBinding(scope, argumentTypes); if (!binding.isValidBinding()) { if (binding.declaringClass == null) { if (this.receiverType instanceof ReferenceBinding) { binding.declaringClass = (ReferenceBinding) this.receiverType; } else { // really bad error .... scope.problemReporter().errorNoMethodFor(this, this.receiverType, argumentTypes); return null; } } scope.problemReporter().invalidMethod(this, binding); // record the closest match, for clients who may still need hint about possible method match if (binding.problemId() == ProblemReasons.NotFound){ this.codegenBinding = this.binding = ((ProblemMethodBinding)binding).closestMatch; } return null; } if (!binding.isStatic()) { // the "receiver" must not be a type, i.e. a NameReference that the TC has bound to a Type if (receiver instanceof NameReference) { if ((((NameReference) receiver).bits & BindingIds.TYPE) != 0) { scope.problemReporter().mustUseAStaticMethod(this, binding); return null; } } } if (arguments != null) for (int i = 0; i < arguments.length; i++) arguments[i].implicitWidening(binding.parameters[i], argumentTypes[i]); //-------message send that are known to fail at compile time----------- if (binding.isAbstract()) { if (receiver.isSuper()) { scope.problemReporter().cannotDireclyInvokeAbstractMethod(this, binding); return null; } // abstract private methods cannot occur nor abstract static............ } if (isMethodUseDeprecated(binding, scope)) scope.problemReporter().deprecatedMethod(binding, this); return binding.returnType; } protected void resolveMethodBinding( BlockScope scope, TypeBinding[] argumentTypes) { this.codegenBinding = this.binding = receiver == ThisReference.ThisImplicit ? scope.getImplicitMethod(selector, argumentTypes, this) : scope.getMethod(this.receiverType, selector, argumentTypes, this); } public void setActualReceiverType(ReferenceBinding receiverType) { this.qualifyingType = receiverType; } public void setDepth(int depth) { if (depth > 0) { bits &= ~DepthMASK; // flush previous depth if any bits |= (depth & 0xFF) << DepthSHIFT; // encoded on 8 bits } } public void setFieldIndex(int depth) { // ignore for here } public String toStringExpression(){ String s = ""; //$NON-NLS-1$ if (receiver != ThisReference.ThisImplicit) s = s + receiver.toStringExpression()+"."; //$NON-NLS-1$ s = s + new String(selector) + "(" ; //$NON-NLS-1$ if (arguments != null) for (int i = 0; i < arguments.length ; i ++) { s = s + arguments[i].toStringExpression(); if ( i != arguments.length -1 ) s = s + " , " ;};; //$NON-NLS-1$ s =s + ")" ; //$NON-NLS-1$ return s; } public void traverse(IAbstractSyntaxTreeVisitor visitor, BlockScope blockScope) { if (visitor.visit(this, blockScope)) { receiver.traverse(visitor, blockScope); if (arguments != null) { int argumentsLength = arguments.length; for (int i = 0; i < argumentsLength; i++) arguments[i].traverse(visitor, blockScope); } } visitor.endVisit(this, blockScope); } }