/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License, Version 1.0 only
* (the "License"). You may not use this file except in compliance
* with the License.
*
* You can obtain a copy of the license at legal-notices/CDDLv1_0.txt
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at legal-notices/CDDLv1_0.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information:
* Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*
*
* Copyright 2013-2015 ForgeRock AS
*/
import static org.opends.server.util.ServerConstants.ALERT_DESCRIPTION_HTTP_CONNECTION_HANDLER_CONSECUTIVE_FAILURES;
import static org.opends.server.util.ServerConstants.ALERT_TYPE_HTTP_CONNECTION_HANDLER_CONSECUTIVE_FAILURES;
/**
* This class defines a connection handler that will be used for communicating
* with clients over HTTP. The connection handler is responsible for
*/
implements ConfigurationChangeListener<HTTPConnectionHandlerCfg>,
{
/** The tracer object for the debug logger. */
/** Default friendly name for this connection handler. */
/** SSL instance name used in context creation. */
/** The initialization configuration. */
/** The current configuration. */
/** Indicates whether the Directory Server is in the process of shutting down. */
private volatile boolean shutdownRequested;
/** Indicates whether this connection handler is enabled. */
private boolean enabled;
/** The set of listeners for this connection handler. */
/** The HTTP server embedded in OpenDJ. */
/** The HTTP probe that collects stats. */
/**
* Holds the current client connections. Using {@link ConcurrentHashMap} to
* only use the keys, so it does not matter what value is put there.
*/
/** The set of statistics collected for this connection handler. */
/** The client connection monitor provider associated with this connection handler. */
/** The unique name assigned to this connection handler. */
/** The protocol used by this connection handler. */
/**
* The condition variable that will be used by the start method to wait for
* the socket port to be opened and ready to process requests before returning.
*/
/** The friendly name of this connection handler. */
/** The SSL engine configurator is used for obtaining default SSL parameters. */
/** Default constructor. It is invoked by reflection to create this {@link ConnectionHandler}. */
public HTTPConnectionHandler()
{
super(DEFAULT_FRIENDLY_NAME);
}
/**
* Returns whether unauthenticated HTTP requests are allowed. The server
* checks whether unauthenticated requests are allowed server-wide first then
* for the HTTP Connection Handler second.
*
* @return true if unauthenticated requests are allowed, false otherwise.
*/
public boolean acceptUnauthenticatedRequests()
{
// The global setting overrides the more specific setting here.
return !DirectoryServer.rejectUnauthenticatedRequests() && !this.currentConfig.isAuthenticationRequired();
}
/**
* Registers a client connection to track it.
*
* @param clientConnection
* the client connection to register
*/
{
}
{
{
ccr.setAdminActionRequired(true);
}
// Reconfigure SSL if needed.
try
{
}
catch (DirectoryException e)
{
logger.traceException(e);
return ccr;
}
{
// Server was running and will still be running if the "enabled" was flipped,
// leave it to the stop / start server to handle it.
{
// It must now keep stats while it was not previously.
setHttpStatsProbe(this.httpServer);
}
{
// It must NOT keep stats anymore.
}
}
this.initConfig = config;
this.currentConfig = config;
return ccr;
}
{
}
{
}
{
}
throws DirectoryException
{
{
}
else
{
}
}
{
shutdownRequested = true;
// Unregister this as a change listener.
if (connMonitor != null)
{
}
if (statTracker != null)
{
}
}
{
return alerts;
}
{
return HTTPConnectionHandler.class.getName();
}
{
return clientConnections.keySet();
}
{
return currentConfig.dn();
}
{
return handlerName;
}
/**
* Returns the current config of this connection handler.
*
* @return the current config of this connection handler
*/
{
return this.currentConfig;
}
{
if (configurator != null)
{
}
return super.getEnabledSSLCipherSuites();
}
{
if (configurator != null)
{
}
return super.getEnabledSSLProtocols();
}
{
return listeners;
}
/**
* Returns the listen port for this connection handler.
*
* @return the listen port for this connection handler.
*/
int getListenPort()
{
return this.initConfig.getListenPort();
}
{
return protocol;
}
/**
* Returns the SSL engine configured for this connection handler if SSL is
* enabled, null otherwise.
*
* @return the SSL engine if SSL is enabled, null otherwise
*/
{
return sslEngineConfigurator.createSSLEngine();
}
{
return handlerName;
}
/**
* Retrieves the set of statistics maintained by this connection handler.
*
* @return The set of statistics maintained by this connection handler.
*/
{
return statTracker;
}
public void initializeConnectionHandler(ServerContext serverContext, HTTPConnectionHandlerCfg config)
{
this.serverContext = serverContext;
if (friendlyName == null)
{
}
{
}
// Configure SSL if needed.
try
{
// This call may disable the connector if wrong SSL settings
}
catch (DirectoryException e)
{
logger.traceException(e);
throw new InitializationException(e.getMessageObject());
}
// Create and register monitors.
connMonitor = new ClientConnectionMonitorProvider(this);
// Register this as a change listener.
config.addHTTPChangeListener(this);
this.initConfig = config;
this.currentConfig = config;
}
{
{
}
return nameBuffer.toString();
}
public boolean isConfigurationAcceptable(
{
{
// Attempt to bind to the listen port on all configured addresses to
// verify whether the connection handler will be able to start.
if (errorMessage != null)
{
return false;
}
}
{
try
{
}
catch (DirectoryException e)
{
logger.traceException(e);
return false;
}
}
return true;
}
/**
* Checks whether any listen address is in use for the given port. The check
* is performed by binding to each address and port.
*
* @param listenAddresses
* the listen {@link InetAddress} to test
* @param listenPort
* the listen port to test
* @param allowReuseAddress
* whether addresses can be reused
* @param configEntryDN
* the configuration entry DN
* @return an error message if at least one of the address is already in use,
* null otherwise.
*/
Collection<InetAddress> listenAddresses, int listenPort, boolean allowReuseAddress, DN configEntryDN)
{
for (InetAddress a : listenAddresses)
{
try
{
{
}
}
catch (IOException e)
{
logger.traceException(e);
return ERR_CONNHANDLER_CANNOT_BIND.get(
}
}
return null;
}
public boolean isConfigurationChangeAcceptable(
{
}
/**
* Indicates whether this connection handler should maintain usage statistics.
*
* @return <CODE>true</CODE> if this connection handler should maintain usage
* statistics, or <CODE>false</CODE> if not.
*/
public boolean keepStats()
{
return currentConfig.isKeepStats();
}
{
shutdownRequested = true;
}
private boolean isListening()
{
return httpServer != null;
}
public void start()
{
// The Directory Server start process should only return when the connection handlers port
// are fully opened and working.
// The start method therefore needs to wait for the created thread too.
synchronized (waitListen)
{
super.start();
try
{
waitListen.wait();
}
catch (InterruptedException e)
{
// If something interrupted the start its probably better to return ASAP
}
}
}
/**
* Unregisters a client connection to stop tracking it.
*
* @param clientConnection
* the client connection to unregister
*/
{
}
public void run()
{
boolean lastIterationFailed = false;
boolean starting = true;
while (!shutdownRequested)
{
// If this connection handler is not enabled, then just sleep for a bit and check again.
if (!this.enabled)
{
if (isListening())
{
}
if (starting)
{
// This may happen if there was an initialisation error which led to disable the connector.
// The main thread is waiting for the connector to listen on its port, which will not occur yet,
// so notify here to allow the server startup to complete.
synchronized (waitListen)
{
starting = false;
waitListen.notify();
}
}
continue;
}
if (isListening())
{
// If already listening, then sleep for a bit and check again.
continue;
}
try
{
// At this point, the connection Handler either started correctly or failed
// to start but the start process should be notified and resume its work in any cases.
synchronized (waitListen)
{
waitListen.notify();
}
// If we have gotten here, then we are about to start listening
// for the first time since startup or since we were previously disabled.
// Start the embedded HTTP server
lastIterationFailed = false;
}
catch (Exception e)
{
// Clean up the messed up HTTP server
// Error + alert about the horked config
logger.traceException(e);
ERR_CONNHANDLER_CANNOT_ACCEPT_CONNECTION, friendlyName, currentConfig.dn(), getExceptionMessage(e));
if (lastIterationFailed)
{
// The last time through the accept loop we also encountered a failure.
// Rather than enter a potential infinite loop of failures,
// disable this acceptor and log an error.
DirectoryServer.sendAlertNotification(this, ALERT_TYPE_HTTP_CONNECTION_HANDLER_CONSECUTIVE_FAILURES, message);
this.enabled = false;
}
else
{
lastIterationFailed = true;
}
}
}
// Initiate shutdown
}
{
// Silence Grizzly's own logging
{
}
this.httpServer = createHttpServer();
// Register servlet as default servlet and also able to serve REST requests
this.httpServer.start();
}
{
if (keepStats())
{
}
// Configure the network listener
// Configure the network transport
final int numRequestHandlers = getNumRequestHandlers(currentConfig.getNumRequestHandlers(), friendlyName);
// Configure SSL
if (sslEngineConfigurator != null)
{
}
return server;
}
{
}
{
}
private void createAndRegisterServlet(final String servletName, final String... urlPatterns) throws Exception
{
// Create and deploy the Web app context
}
private void stopHttpServer()
{
if (this.httpServer != null)
{
this.httpServer.shutdownNow();
}
}
private void cleanUpHttpServer()
{
this.httpServer = null;
}
{
}
private SSLEngineConfigurator createSSLEngineConfigurator(HTTPConnectionHandlerCfg config) throws DirectoryException
{
{
return null;
}
try
{
configurator.setClientMode(false);
// configure with defaults from the JVM
{
}
{
}
switch (config.getSSLClientAuthPolicy())
{
case DISABLED:
configurator.setNeedClientAuth(false);
configurator.setWantClientAuth(false);
break;
case REQUIRED:
configurator.setNeedClientAuth(true);
configurator.setWantClientAuth(true);
break;
case OPTIONAL:
default:
configurator.setNeedClientAuth(false);
configurator.setWantClientAuth(true);
break;
}
return configurator;
}
catch (Exception e)
{
logger.traceException(e);
throw new DirectoryException(resCode, ERR_CONNHANDLER_SSL_CANNOT_INITIALIZE.get(getExceptionMessage(e)), e);
}
}
{
{
return null;
}
if (keyManagerProvider == null)
{
keyManagerProvider = new NullKeyManagerProvider();
enabled = false;
}
else if (!keyManagerProvider.containsAtLeastOneKey())
{
enabled = false;
}
final KeyManager[] keyManagers;
{
}
else
{
{
{
}
}
{
enabled = false;
}
}
if (trustManagerProvider == null)
{
}
return sslContext;
}
}