Search in sources :

Example 31 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project dropwizard by dropwizard.

the class HttpsConnectorFactory method buildHttpConfiguration.

@Override
protected HttpConfiguration buildHttpConfiguration() {
    final HttpConfiguration config = super.buildHttpConfiguration();
    config.setSecureScheme("https");
    config.setSecurePort(getPort());
    config.addCustomizer(new SecureRequestCustomizer());
    return config;
}
Also used : SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration)

Example 32 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project gerrit by GerritCodeReview.

the class JettyServer method listen.

private Connector[] listen(Server server, Config cfg) {
    // OpenID and certain web-based single-sign-on products can cause
    // some very long headers, especially in the Referer header. We
    // need to use a larger default header size to ensure we have
    // the space required.
    // 
    final int requestHeaderSize = cfg.getInt("httpd", "requestheadersize", 16386);
    final URI[] listenUrls = listenURLs(cfg);
    final boolean reuseAddress = cfg.getBoolean("httpd", "reuseaddress", true);
    final int acceptors = cfg.getInt("httpd", "acceptorThreads", 2);
    final AuthType authType = cfg.getEnum("auth", null, "type", AuthType.OPENID);
    reverseProxy = isReverseProxied(listenUrls);
    final Connector[] connectors = new Connector[listenUrls.length];
    for (int idx = 0; idx < listenUrls.length; idx++) {
        final URI u = listenUrls[idx];
        final int defaultPort;
        final ServerConnector c;
        HttpConfiguration config = defaultConfig(requestHeaderSize);
        if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType) && !"https".equals(u.getScheme())) {
            throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' " + " not supported in httpd.listenurl '" + u + "' when auth.type = '" + AuthType.CLIENT_SSL_CERT_LDAP.name() + "'; only 'https' is supported");
        }
        if ("http".equals(u.getScheme())) {
            defaultPort = 80;
            c = newServerConnector(server, acceptors, config);
        } else if ("https".equals(u.getScheme())) {
            SslContextFactory.Server ssl = new SslContextFactory.Server();
            final Path keystore = getFile(cfg, "sslkeystore", "etc/keystore");
            String password = cfg.getString("httpd", null, "sslkeypassword");
            if (password == null) {
                password = "gerrit";
            }
            ssl.setKeyStorePath(keystore.toAbsolutePath().toString());
            ssl.setTrustStorePath(keystore.toAbsolutePath().toString());
            ssl.setKeyStorePassword(password);
            ssl.setTrustStorePassword(password);
            if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType)) {
                ssl.setNeedClientAuth(true);
                Path crl = getFile(cfg, "sslCrl", "etc/crl.pem");
                if (Files.exists(crl)) {
                    ssl.setCrlPath(crl.toAbsolutePath().toString());
                    ssl.setValidatePeerCerts(true);
                }
            }
            defaultPort = 443;
            config.addCustomizer(new SecureRequestCustomizer());
            c = new ServerConnector(server, null, null, null, 0, acceptors, new SslConnectionFactory(ssl, "http/1.1"), new HttpConnectionFactory(config));
        } else if ("proxy-http".equals(u.getScheme())) {
            defaultPort = 8080;
            config.addCustomizer(new ForwardedRequestCustomizer());
            c = newServerConnector(server, acceptors, config);
        } else if ("proxy-https".equals(u.getScheme())) {
            defaultPort = 8080;
            config.addCustomizer(new ForwardedRequestCustomizer());
            config.addCustomizer((connector, channelConfig, request) -> {
                request.setScheme(HttpScheme.HTTPS.asString());
                request.setSecure(true);
            });
            c = newServerConnector(server, acceptors, config);
        } else {
            throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' " + " not supported in httpd.listenurl '" + u + "';" + " only 'http', 'https', 'proxy-http, 'proxy-https'" + " are supported");
        }
        try {
            if (u.getHost() == null && (// 
            u.getAuthority().equals("*") || u.getAuthority().startsWith("*:"))) {
                // Bind to all local addresses. Port wasn't parsed right by URI
                // due to the illegal host of "*" so replace with a legal name
                // and parse the URI.
                // 
                final URI r = new URI(u.toString().replace('*', 'A')).parseServerAuthority();
                c.setHost(null);
                c.setPort(0 < r.getPort() ? r.getPort() : defaultPort);
            } else {
                final URI r = u.parseServerAuthority();
                c.setHost(r.getHost());
                c.setPort(0 <= r.getPort() ? r.getPort() : defaultPort);
            }
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Invalid httpd.listenurl " + u, e);
        }
        c.setInheritChannel(cfg.getBoolean("httpd", "inheritChannel", false));
        c.setReuseAddress(reuseAddress);
        c.setIdleTimeout(cfg.getTimeUnit("httpd", null, "idleTimeout", 30000L, MILLISECONDS));
        connectors[idx] = c;
    }
    return connectors;
}
Also used : Path(java.nio.file.Path) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) LifecycleListener(com.google.gerrit.extensions.events.LifecycleListener) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) Inject(com.google.inject.Inject) URISyntaxException(java.net.URISyntaxException) DefaultServlet(org.eclipse.jetty.servlet.DefaultServlet) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) Config(org.eclipse.jgit.lib.Config) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Map(java.util.Map) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) Filter(javax.servlet.Filter) URI(java.net.URI) GuiceServletContextListener(com.google.inject.servlet.GuiceServletContextListener) Path(java.nio.file.Path) Server(org.eclipse.jetty.server.Server) BlockingArrayQueue(org.eclipse.jetty.util.BlockingArrayQueue) EnumSet(java.util.EnumSet) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) HttpSessionListener(javax.servlet.http.HttpSessionListener) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) GuiceFilter(com.google.inject.servlet.GuiceFilter) Set(java.util.Set) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) List(java.util.List) Singleton(com.google.inject.Singleton) AuthType(com.google.gerrit.extensions.client.AuthType) Handler(org.eclipse.jetty.server.Handler) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ThreadSettingsConfig(com.google.gerrit.server.config.ThreadSettingsConfig) HttpScheme(org.eclipse.jetty.http.HttpScheme) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HashMap(java.util.HashMap) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) HttpLogFactory(com.google.gerrit.pgm.http.jetty.HttpLog.HttpLogFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) ManagementFactory(java.lang.management.ManagementFactory) Files(java.nio.file.Files) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) Log(org.eclipse.jetty.util.log.Log) SitePaths(com.google.gerrit.server.config.SitePaths) DispatcherType(javax.servlet.DispatcherType) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Connector(org.eclipse.jetty.server.Connector) SECONDS(java.util.concurrent.TimeUnit.SECONDS) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) URISyntaxException(java.net.URISyntaxException) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) URI(java.net.URI) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) AuthType(com.google.gerrit.extensions.client.AuthType)

Example 33 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project mysql_perf_analyzer by yahoo.

the class App method sslConnector.

/**
 * Create ssl connector if https is used
 * @return
 */
private ServerConnector sslConnector() {
    HttpConfiguration http_config = new HttpConfiguration();
    http_config.setSecureScheme("https");
    http_config.setSecurePort(this.getPort());
    HttpConfiguration https_config = new HttpConfiguration(http_config);
    https_config.addCustomizer(new SecureRequestCustomizer());
    SslContextFactory sslContextFactory = new SslContextFactory(this.getCertKeyStorePath());
    sslContextFactory.setKeyStorePassword(this.getCertKeyStorePassword());
    // exclude weak ciphers
    sslContextFactory.setExcludeCipherSuites("^.*_(MD5|SHA|SHA1)$");
    // only support tlsv1.2
    sslContextFactory.addExcludeProtocols("SSL", "SSLv2", "SSLv2Hello", "SSLv3", "TLSv1", "TLSv1.1");
    ServerConnector connector = new ServerConnector(jettyServer, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https_config));
    connector.setPort(this.getPort());
    connector.setIdleTimeout(50000);
    return connector;
}
Also used : ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory)

Example 34 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project druid by druid-io.

the class JettyServerModule method makeAndInitializeServer.

static Server makeAndInitializeServer(Injector injector, Lifecycle lifecycle, DruidNode node, ServerConfig config, TLSServerConfig tlsServerConfig, Binding<SslContextFactory.Server> sslContextFactoryBinding, TLSCertificateChecker certificateChecker) {
    // adjusting to make config.getNumThreads() mean, "number of threads
    // that concurrently handle the requests".
    int numServerThreads = config.getNumThreads() + getMaxJettyAcceptorsSelectorsNum(node);
    final QueuedThreadPool threadPool;
    if (config.getQueueSize() == Integer.MAX_VALUE) {
        threadPool = new QueuedThreadPool();
        threadPool.setMinThreads(numServerThreads);
        threadPool.setMaxThreads(numServerThreads);
    } else {
        threadPool = new QueuedThreadPool(numServerThreads, numServerThreads, // same default is used in other case when threadPool = new QueuedThreadPool()
        60000, new LinkedBlockingQueue<>(config.getQueueSize()));
    }
    threadPool.setDaemon(true);
    jettyServerThreadPool = threadPool;
    final Server server = new Server(threadPool);
    // Without this bean set, the default ScheduledExecutorScheduler runs as non-daemon, causing lifecycle hooks to fail
    // to fire on main exit. Related bug: https://github.com/apache/druid/pull/1627
    server.addBean(new ScheduledExecutorScheduler("JettyScheduler", true), true);
    final List<ServerConnector> serverConnectors = new ArrayList<>();
    if (node.isEnablePlaintextPort()) {
        log.info("Creating http connector with port [%d]", node.getPlaintextPort());
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        if (config.isEnableForwardedRequestCustomizer()) {
            httpConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpConfiguration.setRequestHeaderSize(config.getMaxRequestHeaderSize());
        httpConfiguration.setSendServerVersion(false);
        final ServerConnector connector = new ServerConnector(server, new HttpConnectionFactory(httpConfiguration));
        if (node.isBindOnHost()) {
            connector.setHost(node.getHost());
        }
        connector.setPort(node.getPlaintextPort());
        serverConnectors.add(connector);
    }
    final SslContextFactory.Server sslContextFactory;
    if (node.isEnableTlsPort()) {
        log.info("Creating https connector with port [%d]", node.getTlsPort());
        if (sslContextFactoryBinding == null) {
            // Never trust all certificates by default
            sslContextFactory = new IdentityCheckOverrideSslContextFactory(tlsServerConfig, certificateChecker);
            sslContextFactory.setKeyStorePath(tlsServerConfig.getKeyStorePath());
            sslContextFactory.setKeyStoreType(tlsServerConfig.getKeyStoreType());
            sslContextFactory.setKeyStorePassword(tlsServerConfig.getKeyStorePasswordProvider().getPassword());
            sslContextFactory.setCertAlias(tlsServerConfig.getCertAlias());
            sslContextFactory.setKeyManagerFactoryAlgorithm(tlsServerConfig.getKeyManagerFactoryAlgorithm() == null ? KeyManagerFactory.getDefaultAlgorithm() : tlsServerConfig.getKeyManagerFactoryAlgorithm());
            sslContextFactory.setKeyManagerPassword(tlsServerConfig.getKeyManagerPasswordProvider() == null ? null : tlsServerConfig.getKeyManagerPasswordProvider().getPassword());
            if (tlsServerConfig.getIncludeCipherSuites() != null) {
                sslContextFactory.setIncludeCipherSuites(tlsServerConfig.getIncludeCipherSuites().toArray(new String[0]));
            }
            if (tlsServerConfig.getExcludeCipherSuites() != null) {
                sslContextFactory.setExcludeCipherSuites(tlsServerConfig.getExcludeCipherSuites().toArray(new String[0]));
            }
            if (tlsServerConfig.getIncludeProtocols() != null) {
                sslContextFactory.setIncludeProtocols(tlsServerConfig.getIncludeProtocols().toArray(new String[0]));
            }
            if (tlsServerConfig.getExcludeProtocols() != null) {
                sslContextFactory.setExcludeProtocols(tlsServerConfig.getExcludeProtocols().toArray(new String[0]));
            }
            sslContextFactory.setNeedClientAuth(tlsServerConfig.isRequireClientCertificate());
            sslContextFactory.setWantClientAuth(tlsServerConfig.isRequestClientCertificate());
            if (tlsServerConfig.isRequireClientCertificate() || tlsServerConfig.isRequestClientCertificate()) {
                if (tlsServerConfig.getCrlPath() != null) {
                    // setValidatePeerCerts is used just to enable revocation checking using a static CRL file.
                    // Certificate validation is always performed when client certificates are required.
                    sslContextFactory.setValidatePeerCerts(true);
                    sslContextFactory.setCrlPath(tlsServerConfig.getCrlPath());
                }
                if (tlsServerConfig.isValidateHostnames()) {
                    sslContextFactory.setEndpointIdentificationAlgorithm("HTTPS");
                }
                if (tlsServerConfig.getTrustStorePath() != null) {
                    sslContextFactory.setTrustStorePath(tlsServerConfig.getTrustStorePath());
                    sslContextFactory.setTrustStoreType(tlsServerConfig.getTrustStoreType() == null ? KeyStore.getDefaultType() : tlsServerConfig.getTrustStoreType());
                    sslContextFactory.setTrustManagerFactoryAlgorithm(tlsServerConfig.getTrustStoreAlgorithm() == null ? TrustManagerFactory.getDefaultAlgorithm() : tlsServerConfig.getTrustStoreAlgorithm());
                    sslContextFactory.setTrustStorePassword(tlsServerConfig.getTrustStorePasswordProvider() == null ? null : tlsServerConfig.getTrustStorePasswordProvider().getPassword());
                }
            }
        } else {
            sslContextFactory = sslContextFactoryBinding.getProvider().get();
        }
        final HttpConfiguration httpsConfiguration = new HttpConfiguration();
        if (config.isEnableForwardedRequestCustomizer()) {
            httpsConfiguration.addCustomizer(new ForwardedRequestCustomizer());
        }
        httpsConfiguration.setSecureScheme("https");
        httpsConfiguration.setSecurePort(node.getTlsPort());
        httpsConfiguration.addCustomizer(new SecureRequestCustomizer());
        httpsConfiguration.setRequestHeaderSize(config.getMaxRequestHeaderSize());
        httpsConfiguration.setSendServerVersion(false);
        final ServerConnector connector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, HTTP_1_1_STRING), new HttpConnectionFactory(httpsConfiguration));
        if (node.isBindOnHost()) {
            connector.setHost(node.getHost());
        }
        connector.setPort(node.getTlsPort());
        serverConnectors.add(connector);
    } else {
        sslContextFactory = null;
    }
    final ServerConnector[] connectors = new ServerConnector[serverConnectors.size()];
    int index = 0;
    for (ServerConnector connector : serverConnectors) {
        connectors[index++] = connector;
        connector.setIdleTimeout(Ints.checkedCast(config.getMaxIdleTime().toStandardDuration().getMillis()));
        // workaround suggested in -
        // https://bugs.eclipse.org/bugs/show_bug.cgi?id=435322#c66 for jetty half open connection issues during failovers
        connector.setAcceptorPriorityDelta(-1);
        List<ConnectionFactory> monitoredConnFactories = new ArrayList<>();
        for (ConnectionFactory cf : connector.getConnectionFactories()) {
            // connection factories (in this case HTTP/1.1 after the connection is unencrypted for SSL)
            if (cf.getProtocol().equals(connector.getDefaultProtocol())) {
                monitoredConnFactories.add(new JettyMonitoringConnectionFactory(cf, ACTIVE_CONNECTIONS));
            } else {
                monitoredConnFactories.add(cf);
            }
        }
        connector.setConnectionFactories(monitoredConnFactories);
    }
    server.setConnectors(connectors);
    final long gracefulStop = config.getGracefulShutdownTimeout().toStandardDuration().getMillis();
    if (gracefulStop > 0) {
        server.setStopTimeout(gracefulStop);
    }
    server.addLifeCycleListener(new LifeCycle.Listener() {

        @Override
        public void lifeCycleStarting(LifeCycle event) {
            log.debug("Jetty lifecycle starting [%s]", event.getClass());
        }

        @Override
        public void lifeCycleStarted(LifeCycle event) {
            log.debug("Jetty lifeycle started [%s]", event.getClass());
        }

        @Override
        public void lifeCycleFailure(LifeCycle event, Throwable cause) {
            log.error(cause, "Jetty lifecycle event failed [%s]", event.getClass());
        }

        @Override
        public void lifeCycleStopping(LifeCycle event) {
            log.debug("Jetty lifecycle stopping [%s]", event.getClass());
        }

        @Override
        public void lifeCycleStopped(LifeCycle event) {
            log.debug("Jetty lifecycle stopped [%s]", event.getClass());
        }
    });
    // initialize server
    JettyServerInitializer initializer = injector.getInstance(JettyServerInitializer.class);
    try {
        initializer.initialize(server, injector);
    } catch (Exception e) {
        throw new RE(e, "server initialization exception");
    }
    lifecycle.addHandler(new Lifecycle.Handler() {

        @Override
        public void start() throws Exception {
            log.debug("Starting Jetty Server...");
            server.start();
            if (node.isEnableTlsPort()) {
                // Perform validation
                Preconditions.checkNotNull(sslContextFactory);
                final SSLEngine sslEngine = sslContextFactory.newSSLEngine();
                if (sslEngine.getEnabledCipherSuites() == null || sslEngine.getEnabledCipherSuites().length == 0) {
                    throw new ISE("No supported cipher suites found, supported suites [%s], configured suites include list: [%s] exclude list: [%s]", Arrays.toString(sslEngine.getSupportedCipherSuites()), tlsServerConfig.getIncludeCipherSuites(), tlsServerConfig.getExcludeCipherSuites());
                }
                if (sslEngine.getEnabledProtocols() == null || sslEngine.getEnabledProtocols().length == 0) {
                    throw new ISE("No supported protocols found, supported protocols [%s], configured protocols include list: [%s] exclude list: [%s]", Arrays.toString(sslEngine.getSupportedProtocols()), tlsServerConfig.getIncludeProtocols(), tlsServerConfig.getExcludeProtocols());
                }
            }
        }

        @Override
        public void stop() {
            try {
                final long unannounceDelay = config.getUnannouncePropagationDelay().toStandardDuration().getMillis();
                if (unannounceDelay > 0) {
                    log.info("Sleeping %s ms for unannouncement to propagate.", unannounceDelay);
                    Thread.sleep(unannounceDelay);
                } else {
                    log.debug("Skipping unannounce wait.");
                }
                log.debug("Stopping Jetty Server...");
                server.stop();
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RE(e, "Interrupted waiting for jetty shutdown.");
            } catch (Exception e) {
                log.warn(e, "Unable to stop Jetty server.");
            }
        }
    }, Lifecycle.Stage.SERVER);
    if (!config.isShowDetailedJettyErrors()) {
        server.setErrorHandler(new ErrorHandler() {

            @Override
            public boolean isShowServlet() {
                return false;
            }

            @Override
            public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
                request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, null);
                super.handle(target, baseRequest, request, response);
            }
        });
    }
    return server;
}
Also used : LifeCycle(org.eclipse.jetty.util.component.LifeCycle) Server(org.eclipse.jetty.server.Server) SSLEngine(javax.net.ssl.SSLEngine) ScheduledExecutorScheduler(org.eclipse.jetty.util.thread.ScheduledExecutorScheduler) ArrayList(java.util.ArrayList) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) ServerConnector(org.eclipse.jetty.server.ServerConnector) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ConnectionFactory(org.eclipse.jetty.server.ConnectionFactory) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) ISE(org.apache.druid.java.util.common.ISE) ErrorHandler(org.eclipse.jetty.server.handler.ErrorHandler) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) Lifecycle(org.apache.druid.java.util.common.lifecycle.Lifecycle) Request(org.eclipse.jetty.server.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) RE(org.apache.druid.java.util.common.RE)

Example 35 with SecureRequestCustomizer

use of org.eclipse.jetty.server.SecureRequestCustomizer in project XRTB by benmfaul.

the class AddShutdownHook method run.

/**
 * Establishes the HTTP Handler, creates the Jetty server and attaches the
 * handler and then joins the server. This method does not return, but it is
 * interruptable by calling the halt() method.
 */
@Override
public void run() {
    SSL ssl = Configuration.getInstance().ssl;
    if (Configuration.getInstance().port == 0 && ssl == null) {
        try {
            logger.error("Neither HTTP or HTTPS configured, error, stop");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return;
    }
    QueuedThreadPool threadPool = new QueuedThreadPool(threads, 50);
    server = new Server(threadPool);
    ServerConnector connector = null;
    if (Configuration.getInstance().port != 0) {
        connector = new ServerConnector(server);
        connector.setPort(Configuration.getInstance().port);
        connector.setIdleTimeout(60000);
    }
    if (config.getInstance().ssl != null) {
        HttpConfiguration https = new HttpConfiguration();
        https.addCustomizer(new SecureRequestCustomizer());
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(ssl.setKeyStorePath);
        sslContextFactory.setKeyStorePassword(ssl.setKeyStorePassword);
        sslContextFactory.setKeyManagerPassword(ssl.setKeyManagerPassword);
        ServerConnector sslConnector = new ServerConnector(server, new SslConnectionFactory(sslContextFactory, "http/1.1"), new HttpConnectionFactory(https));
        sslConnector.setPort(Configuration.getInstance().sslPort);
        if (connector != null)
            server.setConnectors(new Connector[] { connector, sslConnector });
        else
            server.setConnectors(new Connector[] { sslConnector });
        try {
            logger.info("SSL configured on port {}", Configuration.getInstance().sslPort);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else
        server.setConnectors(new Connector[] { connector });
    Handler handler = new Handler();
    node = null;
    try {
        new WebMQ(7379, null);
        BidRequest.compile();
        // org.eclipse.jetty.server.session.SessionHandler
        SessionHandler sh = new SessionHandler();
        sh.setHandler(handler);
        // set session handle
        server.setHandler(sh);
        startPeridocLogger();
        /**
         * Override the start state if the deadmanswitch object is not null
         * and the key doesn't exist
         */
        if (Configuration.getInstance().deadmanSwitch != null) {
            if (Configuration.getInstance().deadmanSwitch.canRun() == false) {
                RTBServer.stopped = true;
            }
        }
        server.start();
        Thread.sleep(500);
        ready = true;
        // qps timer
        deltaTime = System.currentTimeMillis();
        if (Controller.getInstance().responseQueue != null)
            Controller.getInstance().responseQueue.add(getStatus());
        logger.info("********************* System start on port: {}/{}", Performance.getInternalAddress(), Configuration.getInstance().port);
        startSeparateAdminServer();
        startedLatch.countDown();
        server.join();
    } catch (Exception error) {
        if (error.toString().contains("Interrupt"))
            try {
                logger.error("HALT: : {}", error.toString());
                if (node != null)
                    node.halt();
            } catch (Exception e) {
                e.printStackTrace();
            }
        else
            error.printStackTrace();
    } finally {
        if (node != null)
            node.stop();
    }
}
Also used : SessionHandler(org.eclipse.jetty.server.session.SessionHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) WebMQ(com.xrtb.jmq.WebMQ) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) AerospikeHandler(com.aerospike.redisson.AerospikeHandler) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) SSL(com.xrtb.common.SSL) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool)

Aggregations

SecureRequestCustomizer (org.eclipse.jetty.server.SecureRequestCustomizer)91 HttpConfiguration (org.eclipse.jetty.server.HttpConfiguration)89 ServerConnector (org.eclipse.jetty.server.ServerConnector)87 HttpConnectionFactory (org.eclipse.jetty.server.HttpConnectionFactory)85 SslConnectionFactory (org.eclipse.jetty.server.SslConnectionFactory)82 SslContextFactory (org.eclipse.jetty.util.ssl.SslContextFactory)74 Server (org.eclipse.jetty.server.Server)50 ServletContextHandler (org.eclipse.jetty.servlet.ServletContextHandler)16 QueuedThreadPool (org.eclipse.jetty.util.thread.QueuedThreadPool)16 ServletHolder (org.eclipse.jetty.servlet.ServletHolder)13 File (java.io.File)12 IOException (java.io.IOException)12 MBeanContainer (org.eclipse.jetty.jmx.MBeanContainer)10 Connector (org.eclipse.jetty.server.Connector)10 WebAppContext (org.eclipse.jetty.webapp.WebAppContext)10 ServletException (javax.servlet.ServletException)9 HTTP2ServerConnectionFactory (org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory)8 ContextHandlerCollection (org.eclipse.jetty.server.handler.ContextHandlerCollection)8 DefaultHandler (org.eclipse.jetty.server.handler.DefaultHandler)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)6