/java/org/apache/tomcat/util/net/AprEndpoint.java
Java | 2293 lines | 1464 code | 286 blank | 543 comment | 374 complexity | 37ef9eb7b4ac3790e1788f20421a3290 MD5 | raw file
Possible License(s): Apache-2.0
Large files files are truncated, but you can click here to view the full file
- /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- package org.apache.tomcat.util.net;
- import java.security.AccessController;
- import java.security.PrivilegedAction;
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import java.util.concurrent.ConcurrentLinkedQueue;
- import java.util.concurrent.Executor;
- import java.util.concurrent.RejectedExecutionException;
- import org.apache.juli.logging.Log;
- import org.apache.juli.logging.LogFactory;
- import org.apache.tomcat.jni.Address;
- import org.apache.tomcat.jni.Error;
- import org.apache.tomcat.jni.File;
- import org.apache.tomcat.jni.Library;
- import org.apache.tomcat.jni.OS;
- import org.apache.tomcat.jni.Poll;
- import org.apache.tomcat.jni.Pool;
- import org.apache.tomcat.jni.SSL;
- import org.apache.tomcat.jni.SSLContext;
- import org.apache.tomcat.jni.SSLSocket;
- import org.apache.tomcat.jni.Sockaddr;
- import org.apache.tomcat.jni.Socket;
- import org.apache.tomcat.jni.Status;
- import org.apache.tomcat.util.ExceptionUtils;
- import org.apache.tomcat.util.net.AbstractEndpoint.Acceptor.AcceptorState;
- import org.apache.tomcat.util.net.AbstractEndpoint.Handler.SocketState;
- /**
- * APR tailored thread pool, providing the following services:
- * <ul>
- * <li>Socket acceptor thread</li>
- * <li>Socket poller thread</li>
- * <li>Sendfile thread</li>
- * <li>Worker threads pool</li>
- * </ul>
- *
- * When switching to Java 5, there's an opportunity to use the virtual
- * machine's thread pool.
- *
- * @author Mladen Turk
- * @author Remy Maucherat
- */
- public class AprEndpoint extends AbstractEndpoint {
- // -------------------------------------------------------------- Constants
- private static final Log log = LogFactory.getLog(AprEndpoint.class);
- // ----------------------------------------------------------------- Fields
- /**
- * Root APR memory pool.
- */
- protected long rootPool = 0;
- /**
- * Server socket "pointer".
- */
- protected long serverSock = 0;
- /**
- * APR memory pool for the server socket.
- */
- protected long serverSockPool = 0;
- /**
- * SSL context.
- */
- protected long sslContext = 0;
- protected ConcurrentLinkedQueue<SocketWrapper<Long>> waitingRequests =
- new ConcurrentLinkedQueue<>();
- private 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 = Library.APR_HAS_SENDFILE;
- public void setUseSendfile(boolean useSendfile) { this.useSendfile = useSendfile; }
- @Override
- public boolean getUseSendfile() { return useSendfile; }
- /**
- * Allow comet request handling.
- */
- protected boolean useComet = true;
- public void setUseComet(boolean useComet) { this.useComet = useComet; }
- @Override
- public boolean getUseComet() { return useComet; }
- @Override
- public boolean getUseCometTimeout() { return false; } // Not supported
- @Override
- public boolean getUsePolling() { return true; } // Always supported
- /**
- * Sendfile thread count.
- */
- protected int sendfileThreadCount = 0;
- public void setSendfileThreadCount(int sendfileThreadCount) { this.sendfileThreadCount = sendfileThreadCount; }
- public int getSendfileThreadCount() { return sendfileThreadCount; }
- /**
- * The socket poller.
- */
- protected Poller poller = null;
- public Poller getPoller() {
- return poller;
- }
- /**
- * The 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);
- }
- // Sendfile usage on systems which don't support it cause major problems
- if (useSendfile && !Library.APR_HAS_SENDFILE) {
- useSendfile = false;
- }
- // Initialize thread count default for acceptor
- if (acceptorThreadCount == 0) {
- // FIXME: Doesn't seem to work that well with multiple accept threads
- acceptorThreadCount = 1;
- }
- // Delay accepting of new connections until data is available
- // Only Linux kernels 2.4 + have that implemented
- // on other platforms this call is noop and will return APR_ENOTIMPL.
- if (deferAccept) {
- if (Socket.optSet(serverSock, Socket.APR_TCP_DEFER_ACCEPT, 1) == Status.APR_ENOTIMPL) {
- deferAccept = false;
- }
- }
- // Initialize SSL if needed
- if (isSSLEnabled()) {
- if (SSLCertificateFile == null) {
- // This is required
- throw new Exception(sm.getString("endpoint.apr.noSslCertFile"));
- }
- // SSL protocol
- int value = SSL.SSL_PROTOCOL_NONE;
- if (SSLProtocol == null || SSLProtocol.length() == 0) {
- value = SSL.SSL_PROTOCOL_ALL;
- } else {
- for (String protocol : SSLProtocol.split("\\+")) {
- protocol = protocol.trim();
- if ("SSLv2".equalsIgnoreCase(protocol)) {
- value |= SSL.SSL_PROTOCOL_SSLV2;
- } else if ("SSLv3".equalsIgnoreCase(protocol)) {
- value |= SSL.SSL_PROTOCOL_SSLV3;
- } else if ("TLSv1".equalsIgnoreCase(protocol)) {
- value |= SSL.SSL_PROTOCOL_TLSV1;
- } else if ("all".equalsIgnoreCase(protocol)) {
- value |= SSL.SSL_PROTOCOL_ALL;
- } else {
- // Protocol not recognized, fail to start as it is safer than
- // continuing with the default which might enable more than the
- // is required
- throw new Exception(sm.getString(
- "endpoint.apr.invalidSslProtocol", SSLProtocol));
- }
- }
- }
- // Create SSL Context
- sslContext = SSLContext.make(rootPool, value, SSL.SSL_MODE_SERVER);
- if (SSLInsecureRenegotiation) {
- boolean legacyRenegSupported = false;
- try {
- legacyRenegSupported = SSL.hasOp(SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
- if (legacyRenegSupported)
- SSLContext.setOptions(sslContext, SSL.SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION);
- } catch (UnsatisfiedLinkError e) {
- // Ignore
- }
- if (!legacyRenegSupported) {
- // OpenSSL does not support unsafe legacy renegotiation.
- log.warn(sm.getString("endpoint.warn.noInsecureReneg",
- SSL.versionString()));
- }
- }
- // Set cipher order: client (default) or server
- if (SSLHonorCipherOrder) {
- boolean orderCiphersSupported = false;
- try {
- orderCiphersSupported = SSL.hasOp(SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
- if (orderCiphersSupported)
- SSLContext.setOptions(sslContext, SSL.SSL_OP_CIPHER_SERVER_PREFERENCE);
- } catch (UnsatisfiedLinkError e) {
- // Ignore
- }
- if (!orderCiphersSupported) {
- // OpenSSL does not support ciphers ordering.
- log.warn(sm.getString("endpoint.warn.noHonorCipherOrder",
- SSL.versionString()));
- }
- }
- // Disable compression if requested
- if (SSLDisableCompression) {
- boolean disableCompressionSupported = false;
- try {
- disableCompressionSupported = SSL.hasOp(SSL.SSL_OP_NO_COMPRESSION);
- if (disableCompressionSupported)
- SSLContext.setOptions(sslContext, SSL.SSL_OP_NO_COMPRESSION);
- } catch (UnsatisfiedLinkError e) {
- // Ignore
- }
- if (!disableCompressionSupported) {
- // OpenSSL does not support ciphers ordering.
- log.warn(sm.getString("endpoint.warn.noDisableCompression",
- SSL.versionString()));
- }
- }
- // List the ciphers that the client is permitted to negotiate
- SSLContext.setCipherSuite(sslContext, SSLCipherSuite);
- // Load Server key and certificate
- SSLContext.setCertificate(sslContext, SSLCertificateFile, SSLCertificateKeyFile, SSLPassword, SSL.SSL_AIDX_RSA);
- // Set certificate chain file
- SSLContext.setCertificateChainFile(sslContext, SSLCertificateChainFile, false);
- // Support Client Certificates
- SSLContext.setCACertificate(sslContext, SSLCACertificateFile, SSLCACertificatePath);
- // Set revocation
- SSLContext.setCARevocation(sslContext, SSLCARevocationFile, SSLCARevocationPath);
- // Client certificate verification
- value = SSL.SSL_CVERIFY_NONE;
- if ("optional".equalsIgnoreCase(SSLVerifyClient)) {
- value = SSL.SSL_CVERIFY_OPTIONAL;
- } else if ("require".equalsIgnoreCase(SSLVerifyClient)) {
- value = SSL.SSL_CVERIFY_REQUIRE;
- } else if ("optionalNoCA".equalsIgnoreCase(SSLVerifyClient)) {
- value = SSL.SSL_CVERIFY_OPTIONAL_NO_CA;
- }
- SSLContext.setVerify(sslContext, value, SSLVerifyDepth);
- // For now, sendfile is not supported with SSL
- useSendfile = false;
- }
- }
- public long getJniSslContext() {
- return sslContext;
- }
- /**
- * Start the APR endpoint, creating acceptor, poller and sendfile threads.
- */
- @Override
- public void startInternal() throws Exception {
- if (!running) {
- running = true;
- paused = false;
- // Create worker collection
- if (getExecutor() == null) {
- createExecutor();
- }
- initializeConnectionLatch();
- // Start poller thread
- poller = new Poller();
- poller.init();
- Thread pollerThread = new Thread(poller, getName() + "-Poller");
- pollerThread.setPriority(threadPriority);
- pollerThread.setDaemon(true);
- pollerThread.start();
- // Start sendfile thread
- if (useSendfile) {
- sendfile = new Sendfile();
- sendfile.init();
- Thread sendfileThread =
- new Thread(sendfile, getName() + "-Sendfile");
- sendfileThread.setPriority(threadPriority);
- sendfileThread.setDaemon(true);
- sendfileThread.start();
- }
- startAcceptorThreads();
- // Start async timeout thread
- 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("processSocketWithOptions(long): " + socket);
- }
- AprSocketWrapper wrapper =
- new AprSocketWrapper(Long.valueOf(socket));
- wrapper.setKeepAliveLeft(getMaxKeepAliveRequests());
- connections.put(Long.valueOf(socket), wrapper);
- getExecutor().execute(new SocketWithOptionsProcessor(wrapper));
- }
- } catch (RejectedExecutionException x) {
- log.warn("Socket processing request was rejected for:"+socket,x);
- return false;
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- // This means we got an OOM or similar creating a thread, or that
- // the pool and its queue are full
- log.error(sm.getString("endpoint.process.fail"), t);
- return false;
- }
- return true;
- }
- /**
- * Process given socket. Called in non-comet mode, typically keep alive
- * or upgraded protocol.
- */
- public boolean processSocket(long socket, SocketStatus status) {
- try {
- Executor executor = getExecutor();
- if (executor == null) {
- log.warn(sm.getString("endpoint.warn.noExector",
- Long.valueOf(socket), null));
- } else {
- SocketWrapper<Long> wrapper =
- connections.get(Long.valueOf(socket));
- // 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;
- }
- public boolean processSocketAsync(SocketWrapper<Long> socket,
- SocketStatus status) {
- try {
- synchronized (socket) {
- if (waitingRequests.remove(socket)) {
- SocketProcessor proc = new SocketProcessor(socket, status);
- ClassLoader loader = Thread.currentThread().getContextClassLoader();
- try {
- //threads should not be created by the webapp classloader
- if (Constants.IS_SECURITY_ENABLED) {
- PrivilegedAction<Void> pa = new PrivilegedSetTccl(
- getClass().getClassLoader());
- AccessController.doPrivileged(pa);
- } else {
- Thread.currentThread().setContextClassLoader(
- getClass().getClassLoader());
- }
- Executor executor = getExecutor();
- if (executor == null) {
- log.warn(sm.getString("endpoint.warn.noExector",
- socket, status));
- return false;
- } else {
- executor.execute(proc);
- }
- } finally {
- if (Constants.IS_SECURITY_ENABLED) {
- PrivilegedAction<Void> pa = new PrivilegedSetTccl(loader);
- AccessController.doPrivileged(pa);
- } else {
- Thread.currentThread().setContextClassLoader(loader);
- }
- }
- }
- }
- } catch (RejectedExecutionException x) {
- log.warn("Socket processing request was rejected for: "+socket, x);
- return false;
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- // This means we got an OOM or similar creating a thread, or that
- // the pool and its queue are full
- log.error(sm.getString("endpoint.process.fail"), t);
- return false;
- }
- return true;
- }
- private void destroySocket(long socket) {
- // If not running the socket will be destroyed by
- // parent pool or acceptor socket.
- // In any case disable double free which would cause JVM core.
- // While the connector is running, destroySocket() will call
- // countDownConnection(). Once the connector is stopped, the latch is
- // removed so it does not matter that destroySocket() does not call
- // countDownConnection() in that case
- connections.remove(Long.valueOf(socket));
- destroySocket(socket, running);
- }
- private void destroySocket(long socket, boolean doIt) {
- if (log.isDebugEnabled()) {
- String msg = "destroySocket(long,boolean): " + socket + " " + doIt;
- 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 (doIt && socket != 0) {
- Socket.destroy(socket);
- countDownConnection();
- }
- }
- @Override
- protected Log getLog() {
- return log;
- }
- // --------------------------------------------------- Acceptor Inner Class
- /**
- * The background thread that listens for incoming TCP/IP connections and
- * hands them off to an appropriate processor.
- */
- protected class Acceptor extends AbstractEndpoint.Acceptor {
- private final Log log = LogFactory.getLog(AprEndpoint.Acceptor.class);
- @Override
- public void run() {
- int errorDelay = 0;
- // Loop until we receive a shutdown command
- while (running) {
- // Loop if endpoint is paused
- while (paused && running) {
- state = AcceptorState.PAUSED;
- try {
- Thread.sleep(50);
- } catch (InterruptedException e) {
- // Ignore
- }
- }
- if (!running) {
- break;
- }
- state = AcceptorState.RUNNING;
- try {
- //if we have reached max connections, wait
- countUpOrAwaitConnection();
- long socket = 0;
- try {
- // Accept the next incoming connection from the server
- // socket
- socket = Socket.accept(serverSock);
- } catch (Exception e) {
- //we didn't get a socket
- countDownConnection();
- // Introduce delay if necessary
- errorDelay = handleExceptionWithDelay(errorDelay);
- // re-throw
- throw e;
- }
- // Successful accept, reset the error delay
- errorDelay = 0;
- if (running && !paused) {
- // Hand this socket off to an appropriate processor
- if (!processSocketWithOptions(socket)) {
- // Close socket and pool right away
- destroySocket(socket);
- }
- } else {
- // Close socket and pool right away
- destroySocket(socket);
- }
- } catch (Throwable t) {
- ExceptionUtils.handleThrowable(t);
- if (running) {
- String msg = sm.getString("endpoint.accept.fail");
- if (t instanceof Error) {
- Error e = (Error) t;
- if (e.getError() == 233) {
- // Not an error on HP-UX so log as a warning
- // so it can be filtered out on that platform
- // See bug 50273
- log.warn(msg, t);
- } else {
- log.error(msg, t);
- }
- } else {
- log.error(msg, t);
- }
- }
- }
- // The processor will recycle itself when it finishes
- }
- state = AcceptorState.ENDED;
- }
- }
- /**
- * Async timeout thread
- */
- protected class AsyncTimeout implements Runnable {
- 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.async) {
- long access = socket.getLastAccess();
- if (socket.getTimeout() > 0 &&
- (now-access)>socket.getTimeout()) {
- processSocketAsync(socket,SocketStatus.TIMEOUT);
- }
- }
- }
- // 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++;
- }
- public boolean remove(long socket) {
- for (int i = 0; i < size; i++) {
- if (sockets[i] == socket) {
- sockets[i] = sockets[size - 1];
- timeouts[i] = timeouts[size - 1];
- size--;
- return true;
- }
- }
- return false;
- }
- public long check(long date) {
- while (pos < size) {
- if (date >= timeouts[pos]) {
- long result = sockets[pos];
- sockets[pos] = sockets[size - 1];
- timeouts[pos] = timeouts[size - 1];
- size--;
- return result;
- }
- pos++;
- }
- pos = 0;
- return 0;
- }
- }
- // -------------------------------------------------- SocketList Inner Class
- public class SocketList {
- protected int size;
- protected int pos;
- protected long[] sockets;
- protected int[] timeouts;
- protected int[] flags;
- protected SocketInfo info = new SocketInfo();
- public SocketList(int size) {
- this.size = 0;
- pos = 0;
- sockets = new long[size];
- timeouts = new int[size];
- flags = new int[size];
- }
- public int size() {
- return this.size;
- }
- public SocketInfo get() {
- if (pos == size) {
- return null;
- } else {
- info.socket = sockets[pos];
- info.timeout = timeouts[pos];
- info.flags = flags[pos];
- pos++;
- return info;
- }
- }
- public void clear() {
- size = 0;
- pos = 0;
- }
- public boolean add(long socket, int timeout, int flag) {
- if (size == sockets.length) {
- return false;
- } else {
- for (int i = 0; i < size; i++) {
- if (sockets[i] == socket) {
- flags[i] = SocketInfo.merge(flags[i], flag);
- return true;
- }
- }
- sockets[size] = socket;
- timeouts[size] = timeout;
- flags[size] = flag;
- size++;
- return true;
- }
- }
- public void duplicate(SocketList copy) {
- copy.size = size;
- copy.pos = pos;
- System.arraycopy(sockets, 0, copy.sockets, 0, size);
- System.arraycopy(timeouts, 0, copy.timeouts, 0, size);
- System.arraycopy(flags, 0, copy.flags, 0, size);
- }
- }
- // ------------------------------------------------------ Poller Inner Class
- public class Poller implements Runnable {
- /**
- * Pointers to the pollers.
- */
- protected long[] pollers = null;
- /**
- * Actual poller size.
- */
- protected int actualPollerSize = 0;
- /**
- * Amount of spots left in the poller.
- */
- protected int[] pollerSpace = null;
- /**
- * Amount of low level pollers in use by this poller.
- */
- protected int pollerCount;
- /**
- * Timeout value for the poll call.
- */
- protected int pollerTime;
- /**
- * Root pool.
- */
- protected long pool = 0;
- /**
- * Socket descriptors.
- */
- protected long[] desc;
- /**
- * List of sockets to be added to the poller.
- */
- protected SocketList addList = null;
- /**
- * List of sockets to be added to the poller.
- */
- protected SocketList localAddList = null;
- /**
- * Structure used for storing timeouts.
- */
- protected SocketTimeouts timeouts = null;
- /**
- * Last run of maintain. Maintain will run usually every 5s.
- */
- protected long lastMaintain = System.currentTimeMillis();
- /**
- * Amount of connections inside this poller.
- */
- protected int connectionCount = 0;
- public int getConnectionCount() { return connectionCount; }
- 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;
- pollers = new long[pollerCount];
- pollers[0] = pollset;
- for (int i = 1; i < pollerCount; i++) {
- pollers[i] = allocatePoller(actualPollerSize, pool, -1);
- }
- pollerSpace = new int[pollerCount];
- for (int i = 0; i < pollerCount; i++) {
- pollerSpace[i] = actualPollerSize;
- }
- desc = new long[actualPollerSize * 2];
- connectionCount = 0;
- addList = new SocketList(defaultPollerSize);
- localAddList = new SocketList(defaultPollerSize);
- }
- /*
- * 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))) {
- 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], true);
- }
- }
- }
- }
- Pool.destroy(pool);
- connectionCount = 0;
- }
- /**
- * Add specified socket and associated pool to the poller. The socket
- * will be added to a temporary array, and polled first after a maximum
- * amount of time equal to pollTime (in most cases, latency will be much
- * lower, however). 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 = "Poller.add(long,int,int) " + socket + " " +
- timeout + " " + 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…
Large files files are truncated, but you can click here to view the full file