Create a Jetty ServerConnector configured to use TLS/SSL.
481448
private ServerConnector createSSLConnector() {
        SslContextFactory sslContextFactory = new SslContextFactory();
        sslContextFactory.setKeyStorePath(m_keystore);
        sslContextFactory.setKeyStorePassword(m_keystorepassword);
        sslContextFactory.setTrustStorePath(m_truststore);
        sslContextFactory.setTrustStorePassword(m_truststorepassword);
        sslContextFactory.setNeedClientAuth(m_clientauthentication);
        sslContextFactory.setIncludeCipherSuites(m_tls_cipher_suites);

        HttpConfiguration http_config = new HttpConfiguration();
        http_config.setSecureScheme("https");
        HttpConfiguration https_config = new HttpConfiguration(http_config);
        https_config.addCustomizer(new SecureRequestCustomizer());
        SslConnectionFactory sslConnFactory = new SslConnectionFactory(sslContextFactory, "http/1.1");
        HttpConnectionFactory httpConnFactory = new HttpConnectionFactory(https_config);
        ServerConnector sslConnector = new ServerConnector(m_jettyServer, sslConnFactory, httpConnFactory);
        return sslConnector;
    }
619583
public SSLConnectionSocketFactory prepareClientSSL() {
        try {
        	String path = Config.getProperty(Config.PROXY_KEYSTORE_PATH);
			String pass = Config.getProperty(Config.PROXY_KEYSTORE_PASSWORD);
			KeyStore trustStore = null;
			if (path != null && pass != null) {

				trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
				FileInputStream	instream = new FileInputStream(new File(path));
				try {
		            trustStore.load(instream, pass.toCharArray());
		        } finally {
		            instream.close();
		        }
			}
			SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
	        String tlsVersion = Config.getProperty(Config.TLS_VERSION);
	        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext, new String[]{tlsVersion}, null, new NoopHostnameVerifier());
            return sslConnectionFactory;
        } catch (Exception ex) {
            LOG.error("couldn't create httpClient!! {}", ex.getMessage(), ex);
            return null;
        }
    }
1158712
function(server, opts) {
  EventEmitter.call(this);
  this.server = server;
  this.wsprocessor = new WSProcessor();
  this.tcpprocessor = new TCPProcessor(opts.closeMethod);
  this.id = 1;
  this.timeout = (opts.timeout || DEFAULT_TIMEOUT) * 1000;
  this.setNoDelay = opts.setNoDelay;

  if (!opts.ssl) {
    this.server.on('connection', this.newSocket.bind(this));
  } else {
    this.server.on('secureConnection', this.newSocket.bind(this));
    this.server.on('clientError', function(e, tlsSo) {
      logger.warn('an ssl error occured before handshake established: ', e);
      tlsSo.destroy();
    });
  }

  this.wsprocessor.on('connection', this.emit.bind(this, 'connection'));
  this.tcpprocessor.on('connection', this.emit.bind(this, 'connection'));

  this.state = ST_STARTED;
}
795228
def _helper(
        self,
        host=None,
        port=None,
        debug=False,
        ssl=None,
        sock=None,
        workers=1,
        loop=None,
        protocol=HttpProtocol,
        backlog=100,
        stop_event=None,
        register_sys_signals=True,
        run_async=False,
        auto_reload=False,
    ):
        """"""
        if isinstance(ssl, dict):
            # try common aliaseses
            cert = ssl.get("cert") or ssl.get("certificate")
            key = ssl.get("key") or ssl.get("keyfile")
            if cert is None or key is None:
                raise ValueError("SSLContext or certificate and key required.")
            context = create_default_context(purpose=Purpose.CLIENT_AUTH)
            context.load_cert_chain(cert, keyfile=key)
            ssl = context
        if stop_event is not None:
            if debug:
                warnings.simplefilter("default")
            warnings.warn(
                "stop_event will be removed from future versions.",
                DeprecationWarning,
            )

        self.error_handler.debug = debug
        self.debug = debug

        server_settings = {
            "protocol": protocol,
            "request_class": self.request_class,
            "is_request_stream": self.is_request_stream,
            "router": self.router,
            "host": host,
            "port": port,
            "sock": sock,
            "ssl": ssl,
            "app": self,
            "signal": Signal(),
            "debug": debug,
            "request_handler": self.handle_request,
            "error_handler": self.error_handler,
            "request_timeout": self.config.REQUEST_TIMEOUT,
            "response_timeout": self.config.RESPONSE_TIMEOUT,
            "keep_alive_timeout": self.config.KEEP_ALIVE_TIMEOUT,
            "request_max_size": self.config.REQUEST_MAX_SIZE,
            "request_buffer_queue_size": self.config.REQUEST_BUFFER_QUEUE_SIZE,
            "keep_alive": self.config.KEEP_ALIVE,
            "loop": loop,
            "register_sys_signals": register_sys_signals,
            "backlog": backlog,
            "access_log": self.config.ACCESS_LOG,
            "websocket_max_size": self.config.WEBSOCKET_MAX_SIZE,
            "websocket_max_queue": self.config.WEBSOCKET_MAX_QUEUE,
            "websocket_read_limit": self.config.WEBSOCKET_READ_LIMIT,
            "websocket_write_limit": self.config.WEBSOCKET_WRITE_LIMIT,
            "graceful_shutdown_timeout": self.config.GRACEFUL_SHUTDOWN_TIMEOUT,
        }

        # -------------------------------------------- #
        # Register start/stop events
        # -------------------------------------------- #

        for event_name, settings_name, reverse in (
            ("before_server_start", "before_start", False),
            ("after_server_start", "after_start", False),
            ("before_server_stop", "before_stop", True),
            ("after_server_stop", "after_stop", True),
        ):
            listeners = self.listeners[event_name].copy()
            if reverse:
                listeners.reverse()
            # Prepend sanic to the arguments when listeners are triggered
            listeners = [partial(listener, self) for listener in listeners]
            server_settings[settings_name] = listeners

        if self.configure_logging and debug:
            logger.setLevel(logging.DEBUG)

        if (
            self.config.LOGO
            and os.environ.get("SANIC_SERVER_RUNNING") != "true"
        ):
            logger.debug(
                self.config.LOGO
                if isinstance(self.config.LOGO, str)
                else BASE_LOGO
            )

        if run_async:
            server_settings["run_async"] = True

        # Serve
        if host and port and os.environ.get("SANIC_SERVER_RUNNING") != "true":
            proto = "http"
            if ssl is not None:
                proto = "https"
            logger.info("Goin' Fast @ {}://{}:{}".format(proto, host, port))

        return server_settings
608672
public static ProtocolNegotiator serverTls(final SslContext sslContext) {
    Preconditions.checkNotNull(sslContext, "sslContext");
    return new ProtocolNegotiator() {
      @Override
      public ChannelHandler newHandler(GrpcHttp2ConnectionHandler handler) {
        return new ServerTlsHandler(sslContext, handler);
      }

      @Override
      public void close() {}


      @Override
      public AsciiString scheme() {
        return Utils.HTTPS;
      }
    };
  }
509739
def setHTTPConnection( useSSL, org = "www", domain = "quickbase", proxy_options = nil )
      @useSSL = useSSL
      @org = org
      @domain = domain
      if USING_HTTPCLIENT
        if proxy_options
           @httpConnection = HTTPClient.new( "#{proxy_options["proxy_server"]}:#{proxy_options["proxy_port"] || useSSL ? "443" : "80"}" )
           @httpConnection.set_auth(proxy_options["proxy_server"], proxy_options["proxy_user"], proxy_options["proxy_password"])
        else  
           @httpConnection = HTTPClient.new 
        end
      else  
        if proxy_options
           @httpProxy = Net::HTTP::Proxy(proxy_options["proxy_server"], proxy_options["proxy_port"], proxy_options["proxy_user"], proxy_options["proxy_password"])
           @httpConnection = @httpProxy.new( "#{@org}.#{@domain}.com", useSSL ? 443 : 80)
        else
           @httpConnection = Net::HTTP.new( "#{@org}.#{@domain}.com", useSSL ? 443 : 80 )
        end  
        @httpConnection.use_ssl = useSSL
        @httpConnection.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
   end
412078
function createServer (options, callback) {
  typeforce({
    keeper: 'Object',
    port: 'Number',
    readonly: '?Boolean'
  }, options)

  var keeper = options.keeper
  var port = options.port
  var app = express()
  if (options.readonly) {
    app.set('readonly', true)
  }

  // var mapping

  app.set('keeper', keeper)
  app.use(function (req, res, next) {
    var requestDomain = domain.create()
    requestDomain.add(req)
    requestDomain.add(res)
    requestDomain.on('error', function (err) {
      debug('Uncaught error, processing in domain error handler: ' + err.message)
      errorHandler(err, req, res)
    })

    res.on('close', requestDomain.dispose.bind(requestDomain))
    requestDomain.run(next)
  })

  app.use(function (req, res, next) {
    if (req.hostname !== 'localhost' && req.hostname !== '127.0.0.1') {
      throw utils.httpError(400, 'Only local requests permitted')
    }

    next()
  })

  /**
   * Routes
   */
  router(app)

  /**
   * Error Handling
   */
  app.use(errorHandler)

  // client.externalIp(function(err, ip) {
  //   console.log('External ip', ip)
  //   keeper.externalIp(ip)
  // })

  // var ttl = 144000

  process.on('exit', cleanup)
  process.on('SIGINT', cleanup)
  process.on('SIGTERM', cleanup)
  process.on('uncaughtException', function (err) {
    console.log('Uncaught exception, caught in process catch-all: ' + err.message)
    console.log(err.stack)
  })

  // if (require.main === global.module) {
  // run directly, not as sub-app

  // var mappingIntervalId = setInterval(createPortMapping, ttl)
  // var pubPort = port
  var privPort = port
  var serverIsUp
  // var portPromise = createPortMapping()
  // portPromise.done(checkReady)

  var server = app.listen(privPort, function () {
    serverIsUp = true
    checkReady()
  })

  function checkReady () {
    if (serverIsUp
      // && portPromise.inspect().state === 'fulfilled'
      && callback) {
      callback(null, server)
    }
  }

  function errorHandler (err, req, res, next) {
    if (res.finished) return

    var code = err.code || 500
    var msg = 'code' in err ? err.message : 'There was an error with your request. Please contact support@tradle.io'

    // log('Error:' + err.message)
    res.status(code).json({
      code: code,
      message: msg
    }, null, 2)
  }

  // function createPortMapping () {
  //   return ports.mapPort({
  //       public: pubPort,
  //       private: privPort,
  //       hijack: true
  //     })
  //     .then(function () {
  //       mapping = {
  //         public: pubPort,
  //         private: privPort
  //       }
  //     })
  //     .catch(function (err) {
  //       console.error('Failed to create port mapping, but continuing', err)
  //       clearInterval(mappingIntervalId)
  //     // process.exit()
  //     })
  // }

  function cleanup () {
    if (!server) return

    debug('CLEANUP')
    if (server) {
      try {
        server.close()
      } catch (err) {}
      server = null
    }

    // if (mapping) {
    //   clearInterval(mappingIntervalId)
    //   ports.unmapPort(mapping['public'])
    //   mapping = null
    // }

    setTimeout(process.exit.bind(process), 1000)
  }

  return server
}
638704
public SSLSocket getSSLSocket() throws KeystoreException, CommunicationException {
		SSLSocketFactory socketFactory = getSSLSocketFactory();
		logger.debug("Creating SSLSocket to " + getServerHost() + ":" + getServerPort());

		try {
			if (ProxyManager.isUsingProxy(server)) {
				return tunnelThroughProxy(socketFactory);
			} else {
				return (SSLSocket) socketFactory.createSocket(getServerHost(), getServerPort());
			}
		} catch (Exception e) {
			throw new CommunicationException("Communication exception: " + e, e);
		}
	}
33066
def create_tls_context(self):
        
        # Create context manually, as we're going to set our own options.
        tls_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)

        # Load client/server certificate.
        if self.tls_certificate_file:
            tls_context.load_cert_chain(self.tls_certificate_file, self.tls_certificate_keyfile,
                                        password=self.tls_certificate_password)

        # Set some relevant options:
        # - No server should use SSLv2 or SSLv3 any more, they are outdated and full of security holes. (RFC6176, RFC7568)
        # - Disable compression in order to counter the CRIME attack. (https://en.wikipedia.org/wiki/CRIME_%28security_exploit%29)
        # - Disable session resumption to maintain perfect forward secrecy. (https://timtaubert.de/blog/2014/11/the-sad-state-of-server-side-tls-session-resumption-implementations/)
        for opt in ['NO_SSLv2', 'NO_SSLv3', 'NO_COMPRESSION', 'NO_TICKET']:
            if hasattr(ssl, 'OP_' + opt):
                tls_context.options |= getattr(ssl, 'OP_' + opt)

        # Set TLS verification options.
        if self.tls_verify:
            # Set our custom verification callback, if the library supports it.
            tls_context.set_servername_callback(self.verify_tls)

            # Load certificate verification paths.
            tls_context.set_default_verify_paths()
            if sys.platform in DEFAULT_CA_PATHS and path.isdir(DEFAULT_CA_PATHS[sys.platform]):
                tls_context.load_verify_locations(capath=DEFAULT_CA_PATHS[sys.platform])

            # If we want to verify the TLS connection, we first need a certicate.
            # Check this certificate and its entire chain, if possible, against revocation lists.
            tls_context.verify_mode = ssl.CERT_REQUIRED
            tls_context.verify_flags = ssl.VERIFY_CRL_CHECK_CHAIN

        return tls_context
733459
private static SslHandler configureSslHandler(SslHandler sslHandler) {
        // Set endpoint identification algorithm so that JDK's default X509TrustManager implementation
        // performs host name checks. Without this, the X509TrustManager implementation will never raise
        // a CertificateException even if the domain name or IP address mismatches.
        final SSLEngine engine = sslHandler.engine();
        final SSLParameters params = engine.getSSLParameters();
        params.setEndpointIdentificationAlgorithm("HTTPS");
        engine.setSSLParameters(params);
        return sslHandler;
    }
887487
private Server __buildServer() {
        Server mServer = new Server();

        // Connectors...
        Connector[] connectors = getConnectors(mServer);
        if (connectors == null || connectors.length == 0)
            throw new RuntimeException("Missing connectors");

        for (Connector connector : connectors) {
            mServer.addConnector(connector);
        }

        ServletContextHandler handler = new ServletContextHandler(ServletContextHandler.SESSIONS);
        handler.setContextPath("/");
        handler.setResourceBase(System.getProperty("java.io.tmpdir"));

        // Filters...
        for (Map.Entry<String, List<Class<? extends Filter>>> filterEntry : filterMap.entrySet()) {
            for (Class<? extends Filter> filterClass : filterEntry.getValue()) {
                handler.addFilter(filterClass, filterEntry.getKey(), EnumSet.of(DispatcherType.REQUEST));
            }
        }

        // Servlets...
        for (Map.Entry<String, Class<? extends HttpServlet>> servletEntry : servletMap.entrySet()) {
            handler.addServlet(servletEntry.getValue(), servletEntry.getKey());
        }

        // Event listeners...
        for (Class<? extends EventListener> eventListenerClass : servletContextListenerSet) {
            try {
                EventListener eventListener = eventListenerClass.newInstance();
                handler.addEventListener(eventListener);
            } catch (IllegalAccessException | InstantiationException ex) {
                throw new RuntimeException(ex);
            }
        }

        // Error handler...
        if (errorHandler != null)
            handler.setErrorHandler(errorHandler);

        mServer.setHandler(handler);
        return mServer;
    }
725737
public static ServerConnector createServerConnectorAndAddToServer(Server server) {
		ServerConnector connector = new ServerConnector(server, JettySetting.createHttpConnectionFactory());

		connector.setHost(setting.getStr("host", "http", "0.0.0.0"));
		connector.setPort(setting.getInt("port", "http", 8090));
		connector.setIdleTimeout(setting.getLong("idle-timeout", "http", 30000L));
		server.addConnector(connector);

		return connector;
	}
26566
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
    public static SSLConnectionSocketFactory createUnsafeSSLConnectionSocketFactory() {
        try {
            final SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            return new SSLConnectionSocketFactory(builder.build(), new NaiveHostnameVerifier());
        } catch (final Exception e) {
            throw new IllegalStateException(e);
        }
    }
598537
private MBeanServerConnection createServerConnection(String host, int port) throws IOException {
            jmxServiceURL = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi");
            JMXConnector jmxc = JMXConnectorFactory.connect(jmxServiceURL, null);
            return jmxc.getMBeanServerConnection();            
    }
459600
def connect_ssl(cls, user, password, endpoints,
                    ca_certs=None, validate=None):
        
        if isinstance(endpoints, basestring):
            endpoints = [endpoints]
        transport = SingleEndpointTransport(
            SocketTransport.connect_ssl, endpoints, ca_certs=ca_certs,
            validate=validate)
        return cls(transport, user, password)
1202437
function HTTPServer(options) {
  if (!(this instanceof HTTPServer))
    return new HTTPServer(options);

  options = new HTTPOptions(options);

  HTTPBase.call(this, options);

  this.options = options;
  this.network = this.options.network;
  this.logger = this.options.logger.context('http');
  this.walletdb = this.options.walletdb;

  this.server = new HTTPBase(this.options);
  this.rpc = this.walletdb.rpc;

  this.init();
}
210212
def CreateServer(frontend=None):
  """"""
  max_port = config.CONFIG.Get("Frontend.port_max",
                               config.CONFIG["Frontend.bind_port"])

  for port in range(config.CONFIG["Frontend.bind_port"], max_port + 1):

    server_address = (config.CONFIG["Frontend.bind_address"], port)
    try:
      httpd = GRRHTTPServer(
          server_address, GRRHTTPServerHandler, frontend=frontend)
      break
    except socket.error as e:
      if e.errno == socket.errno.EADDRINUSE and port < max_port:
        logging.info("Port %s in use, trying %s", port, port + 1)
      else:
        raise

  sa = httpd.socket.getsockname()
  logging.info("Serving HTTP on %s port %d ...", sa[0], sa[1])
  return httpd