Turn on/off SSL.
 This flag must be set before starting session.
 If you change use_ssl value after session started,
 a Net::HTTP object raises IOError.
500684
def use_ssl=(flag)
      flag = (flag ? true : false)
      raise IOError, "use_ssl value changed, but session already started" \
          if started? and @use_ssl != flag
      if flag and not @ssl_context
        @ssl_context = OpenSSL::SSL::SSLContext.new
      end
      @use_ssl = flag
    end
1297296
def shutdown(self) -> None:
        
        self._is_handshake_completed = False
        try:
            self._flush_ssl_engine()
        except IOError:
            # Ensure shutting down the connection never raises an exception
            pass

        try:
            self._ssl.shutdown()
        except OpenSSLError as e:
            # Ignore "uninitialized" exception
            if 'SSL_shutdown:uninitialized' not in str(e) and 'shutdown while in init' not in str(e):
                raise
        if self._sock:
            self._sock.close()
258412
def request_error!(exception)
      case exception
      when HTTP::Request::UnsupportedSchemeError, Addressable::URI::InvalidURIError
        raise Down::InvalidUrl, exception.message
      when HTTP::ConnectionError
        raise Down::ConnectionError, exception.message
      when HTTP::TimeoutError
        raise Down::TimeoutError, exception.message
      when HTTP::Redirector::TooManyRedirectsError
        raise Down::TooManyRedirects, exception.message
      when OpenSSL::SSL::SSLError
        raise Down::SSLError, exception.message
      else
        raise exception
      end
    end
59316
def __enableProxy(self):
        
        os.environ[
            "HTTP_PROXY"] = self.httpProxy()
        os.environ[
            "HTTPS_PROXY"] = self.httpsProxy()

        os.environ["REQUESTS_CA_BUNDLE"] = os.path.join(
            os.path.dirname(
                os.path.abspath(__file__)),
            "cert.pem")
986398
def on_error(exc)
      case exc
      when Kontena::Websocket::SSLVerifyError
        if exc.cert
          error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc} (subject #{exc.subject}, issuer #{exc.issuer})"
        else
          error "unable to connect to SSL server with KONTENA_SSL_VERIFY=true: #{exc}"
        end

      when Kontena::Websocket::SSLConnectError
        error "unable to connect to SSL server: #{exc}"

      when Kontena::Websocket::ConnectError
        error "unable to connect to server: #{exc}"

      when Kontena::Websocket::ProtocolError
        error "unexpected response from server, check url: #{exc}"

      else
        error "websocket error: #{exc}"
      end
    end
391013
def process_reset_session(session, connection_initialize = false)
      # set active command sequence info
      session[:cmd_sequence] = connection_initialize ? :CMD_HELO : :CMD_RSET
      # drop any auth challenge
      session[:auth_challenge] = {}
      # test existing of :ctx hash
      session[:ctx] || session[:ctx] = {}
      # reset server values (only on connection start)
      if connection_initialize
        # create or rebuild :ctx hash
        session[:ctx].merge!(
          server: {
            local_host: '',
            local_ip: '',
            local_port: '',
            local_response: '',
            remote_host: '',
            remote_ip: '',
            remote_port: '',
            helo: '',
            helo_response: '',
            connected: '',
            exceptions: 0,
            authorization_id: '',
            authentication_id: '',
            authenticated: '',
            encrypted: ''
          }
        )
      end
      # reset envelope values
      session[:ctx].merge!(
        envelope: {
          from: '',
          to: [],
          encoding_body: '',
          encoding_utf8: ''
        }
      )
      # reset message data
      session[:ctx].merge!(
        message: {
          received: -1,
          delivered: -1,
          bytesize: -1,
          headers: '',
          crlf: "\r\n",
          data: ''
        }
      )
    end
1024258
def set_ssl_logging(self, enable=False, func=_ssl_logging_cb):
        
        '''
        if enable:
            SSL_CTX_set_info_callback(self._ctx, func)
        else:
            SSL_CTX_set_info_callback(self._ctx, 0)
696686
def https_app
      ssl_options  = OpenSSL::SSL::SSLContext::DEFAULT_PARAMS[:options]
      ssl_options |= OpenSSL::SSL::OP_CIPHER_SERVER_PREFERENCE if defined?(OpenSSL::SSL::OP_CIPHER_SERVER_PREFERENCE)
      # This is required to disable SSLv3 on Ruby 1.8.7
      ssl_options |= OpenSSL::SSL::OP_NO_SSLv2 if defined?(OpenSSL::SSL::OP_NO_SSLv2)
      ssl_options |= OpenSSL::SSL::OP_NO_SSLv3 if defined?(OpenSSL::SSL::OP_NO_SSLv3)
      ssl_options |= OpenSSL::SSL::OP_NO_TLSv1 if defined?(OpenSSL::SSL::OP_NO_TLSv1)

      if Settings.instance.tls_disabled_versions
        Settings.instance.tls_disabled_versions.each do |version|
          constant = OpenSSL::SSL.const_get("OP_NO_TLSv#{version.to_s.tr('.', '_')}") rescue nil

          if constant
            Log.instance.info "TLSv#{version} will be disabled."
            ssl_options |= constant
          else
            Log.instance.warn "TLSv#{version} was not found."
          end
        end
      end

      {
        :SSLEnable => true,
        :SSLVerifyClient => OpenSSL::SSL::VERIFY_PEER,
        :SSLPrivateKey => ssl_private_key,
        :SSLCertificate => ssl_certificate,
        :SSLCACertificateFile => Settings.instance.ssl_ca_file,
        :SSLOptions => ssl_options
      }
    end
24245
def _setup_transport(self):
        
        if HAVE_PY26_SSL:
            if hasattr(self, 'sslopts'):
                self.sslobj = ssl.wrap_socket(self.sock, **self.sslopts)
            else:
                self.sslobj = ssl.wrap_socket(self.sock)
            self.sslobj.do_handshake()
        else:
            self.sslobj = socket.ssl(self.sock)
614832
def retry_request(is_read_only = false)
      attempts = 0
      begin
        yield
      rescue OpenSSL::SSL::SSLError => e
        raise e unless @enable_retry
        # These errors pertain to the SSL handshake.  Since no data has been
        # exchanged its always safe to retry
        raise e if attempts >= @max_attempts
        attempts += 1
        retry
      rescue Errno::ECONNRESET, RestClient::ServerBrokeConnection, RestClient::RequestTimeout => e
        raise e unless @enable_retry
        #   Packetloss related.
        #   There are two timeouts on the ssl negotiation and data read with different
        #   times. Unfortunately the standard timeout class is used for both and the
        #   exceptions are caught and reraised so you can't distinguish between them.
        #   Unfortunate since ssl negotiation timeouts should always be retryable
        #   whereas data may not.
        if is_read_only
          raise e if attempts >= @max_attempts
          attempts += 1
          retry
        else
          raise e
        end
      rescue ApiError => e
        if re_login?(e)
          # Session is expired or invalid
          login()
          retry
        else
          raise e
        end
      end
    end
797195
def http(&block)
      http = Net::HTTP.new(@uri.host, @uri.port)
      if @uri.port == 443
        http.use_ssl = true
        http.verify_mode = OpenSSL::SSL::VERIFY_NONE
      end
      return http.start(&block) if block_given?
      http
    end
1334120
private void initializeHTTPClient() {

    if (_config.isHTTPSConfigured()) {
      try {
        KeyStore trustKeystore = getClientTruststore();
        SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(trustKeystore, new TrustSelfSignedStrategy())
            .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        // Allow both HTTP and HTTPS connections
        Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory> create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf)
            .build();

        HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

        httpClient = HttpClients.custom()
            .setConnectionManager(cm)
            .build();

      } catch (Exception e) {
        LOGGER.error( "Issue creating HTTP client using supplied configuration. Proceeding with default non-SSL client.", e);
        httpClient = HttpClients.createDefault();
      }
    } else {

      httpClient = HttpClients.createDefault();
    }
  }
1220323
@Nullable
    protected final SSLSession sslSession() {
        checkState(!sessionProtocol.isTls() || sslSession != null,
                   "sslSession must be set for a TLS-enabled protocol: %s", sessionProtocol);
        return sessionProtocol.isTls() ? sslSession : null;
    }
541130
def http_request
      if http_proxy
        http_request = http_proxy.new(url.host, url.port)
      else
        http_request = Net::HTTP.new(url.host, url.port)
      end
      
      # enable SSL/TLS
      if url.scheme == 'https'
        require 'net/https'
        require 'openssl'
        Error::Connection.extend_classes!
        
        http_request.use_ssl = true
        
        if options[:tls_verify] or options[:verify_ssl]
          if http_request.respond_to?(:enable_post_connection_check=)
            http_request.enable_post_connection_check = true
          end
          # from http://curl.haxx.se/ca/cacert.pem
          http_request.ca_file = options[:tls_ca_file] || File.expand_path('../../../support/cacert.pem', __FILE__)
          http_request.verify_mode = OpenSSL::SSL::VERIFY_PEER
        else
          http_request.verify_mode = OpenSSL::SSL::VERIFY_NONE
        end
        
        if options[:tls_key_and_certificate_file]
          key_and_certificate       = File.read(options[:tls_key_and_certificate_file])
          options[:tls_key]         = OpenSSL::PKey::RSA.new(key_and_certificate)
          options[:tls_certificate] = OpenSSL::X509::Certificate.new(key_and_certificate)
        end
        
        if options[:tls_key] and options[:tls_certificate]
          http_request.key  = options[:tls_key]
          http_request.cert = options[:tls_certificate]
        elsif options[:tls_key] || options[:tls_certificate]
          raise ArgumentError, "Please specify both the certificate and private key (:tls_key and :tls_certificate)"
        end
      end
      
      if @configure_block
        @configure_block.call(http_request)
      end
      
      http_request
    end
1267579
def after_start_check(self):
        
        try:
            if self.url.scheme == 'http':
                conn = HTTPConnection(self.host, self.port)
            elif self.url.scheme == 'https':
                ssl_context = None
                if not self.verify_tls:
                    ssl_context = ssl._create_unverified_context()
                conn = HTTPSConnection(
                    self.host,
                    self.port,
                    context=ssl_context,
                )
            else:
                raise ValueError(f'Unsupported URL scheme: "{self.url.scheme}"')

            self._send_request(conn)
            response = conn.getresponse()
            status = str(response.status)

            if not self._validate_response(response):
                return False

            if status == self.status or self.status_re.match(status):
                conn.close()
                return True

        except (HTTPException, socket.timeout, socket.error) as ex:
            log.debug('Executor process not healthy yet', command=self.command, error=ex)
            time.sleep(.05)
            return False

        return False
1094418
def start(io)
      # start SSL negotiation
      ssl = OpenSSL::SSL::SSLSocket.new(io, @ctx)
      # connect to server socket
      ssl.accept
      # make sure to close also the underlying io
      ssl.sync_close = true
      # return as new io socket
      return ssl
    end
1322372
def setServer(self, server):
        
        if server == 'live':
            self.__server__ = server
            self.__server_url__ = 'api.sense-os.nl'
            self.setUseHTTPS()
            return True
        elif server == 'dev':
            self.__server__ = server
            self.__server_url__ = 'api.dev.sense-os.nl'
            # the dev server doesn't support https
            self.setUseHTTPS(False)
            return True
        elif server == 'rc':
            self.__server__ = server
            self.__server_url__ = 'api.rc.dev.sense-os.nl'
            self.setUseHTTPS(False)
        else:
            return False