Setup the socket and SSL_CTX objects.
193757
def _init_base_objects(self, ssl_version: OpenSslVersionEnum, underlying_socket: Optional[socket.socket]) -> None:
        
        self._is_handshake_completed = False
        self._ssl_version = ssl_version
        self._ssl_ctx = self._NASSL_MODULE.SSL_CTX(ssl_version.value)

        # A Python socket handles transmission of the data
        self._sock = underlying_socket
696362
private void configureSsl(SocketChannel ch) {
        ch.pipeline().addLast(sslCtx.newHandler(ch.alloc()), new Http2OrHttpHandler());
    }
984946
def start_tls(self, ssl_context: Union[bool, dict, ssl.SSLContext]=True) \
            -> 'SSLConnection':
        '''
        '''
        sock = self.writer.get_extra_info('socket')
        ssl_conn = SSLConnection(
            self._address,
            ssl_context=ssl_context,
            hostname=self._hostname, timeout=self._timeout,
            connect_timeout=self._connect_timeout, bind_host=self._bind_host,
            bandwidth_limiter=self._bandwidth_limiter, sock=sock
        )

        yield from ssl_conn.connect()

        return ssl_conn
306632
def _ssl_wrap_socket(self, sock):
        
        context = self._parameters['ssl_options'].get('context')
        if context is not None:
            hostname = self._parameters['ssl_options'].get('server_hostname')
            return context.wrap_socket(
                sock, do_handshake_on_connect=True,
                server_hostname=hostname
            )
        if 'ssl_version' not in self._parameters['ssl_options']:
            self._parameters['ssl_options']['ssl_version'] = (
                compatibility.DEFAULT_SSL_VERSION
            )
        return ssl.wrap_socket(
            sock, do_handshake_on_connect=True,
            **self._parameters['ssl_options']
        )
785890
def connect(self):
        """"""
        self.sock = socket_create_connection((self.host,self.port),
                                             self.timeout, self.source_address)
        if self._tunnel_host:
            self._tunnel()
308824
def setup_zmq(self):
        """"""
        self.context = zmq.Context()
        self.push = self.context.socket(zmq.PUSH)
        self.push_port = self.push.bind_to_random_port("tcp://%s" % self.host)
        # start a listener for the pull socket
        eventlet.spawn(self.zmq_pull)
        eventlet.sleep(0)
703359
def connect
      credentials.clear
      @sock = if !!options[:ssl]
        Socket::SSL.connect(host, port, timeout)
      else
        Socket::TCP.connect(host, port, timeout)
      end
    end
1172315
async def setup(self):
        """"""
        while True:
            fut = self.loop.create_connection(
                lambda: SW16Protocol(
                    self,
                    disconnect_callback=self.handle_disconnect_callback,
                    loop=self.loop, logger=self.logger),
                host=self.host,
                port=self.port)
            try:
                self.transport, self.protocol = \
                    await asyncio.wait_for(fut, timeout=self.timeout)
            except asyncio.TimeoutError:
                self.logger.warning("Could not connect due to timeout error.")
            except OSError as exc:
                self.logger.warning("Could not connect due to error: %s",
                                    str(exc))
            else:
                self.is_connected = True
                if self.reconnect_callback:
                    self.reconnect_callback()
                break
            await asyncio.sleep(self.reconnect_interval)
917283
def handshake(self,
                  server_hostname,
                  verify,
                  trust_bundle,
                  min_version,
                  max_version,
                  client_cert,
                  client_key,
                  client_key_passphrase):
        
        # First, we do the initial bits of connection setup. We need to create
        # a context, set its I/O funcs, and set the connection reference.
        self.context = Security.SSLCreateContext(
            None, SecurityConst.kSSLClientSide, SecurityConst.kSSLStreamType
        )
        result = Security.SSLSetIOFuncs(
            self.context, _read_callback_pointer, _write_callback_pointer
        )
        _assert_no_error(result)

        # Here we need to compute the handle to use. We do this by taking the
        # id of self modulo 2**31 - 1. If this is already in the dictionary, we
        # just keep incrementing by one until we find a free space.
        with _connection_ref_lock:
            handle = id(self) % 2147483647
            while handle in _connection_refs:
                handle = (handle + 1) % 2147483647
            _connection_refs[handle] = self

        result = Security.SSLSetConnection(self.context, handle)
        _assert_no_error(result)

        # If we have a server hostname, we should set that too.
        if server_hostname:
            if not isinstance(server_hostname, bytes):
                server_hostname = server_hostname.encode('utf-8')

            result = Security.SSLSetPeerDomainName(
                self.context, server_hostname, len(server_hostname)
            )
            _assert_no_error(result)

        # Setup the ciphers.
        self._set_ciphers()

        # Set the minimum and maximum TLS versions.
        result = Security.SSLSetProtocolVersionMin(self.context, min_version)
        _assert_no_error(result)
        result = Security.SSLSetProtocolVersionMax(self.context, max_version)
        _assert_no_error(result)

        # If there's a trust DB, we need to use it. We do that by telling
        # SecureTransport to break on server auth. We also do that if we don't
        # want to validate the certs at all: we just won't actually do any
        # authing in that case.
        if not verify or trust_bundle is not None:
            result = Security.SSLSetSessionOption(
                self.context,
                SecurityConst.kSSLSessionOptionBreakOnServerAuth,
                True
            )
            _assert_no_error(result)

        # If there's a client cert, we need to use it.
        if client_cert:
            self._keychain, self._keychain_dir = _temporary_keychain()
            self._client_cert_chain = _load_client_cert_chain(
                self._keychain, client_cert, client_key
            )
            result = Security.SSLSetCertificate(
                self.context, self._client_cert_chain
            )
            _assert_no_error(result)

        while True:
            with self._raise_on_error():
                result = Security.SSLHandshake(self.context)

                if result == SecurityConst.errSSLWouldBlock:
                    raise socket.timeout("handshake timed out")
                elif result == SecurityConst.errSSLServerAuthCompleted:
                    self._custom_validate(verify, trust_bundle)
                    continue
                else:
                    _assert_no_error(result)
                    break
513530
def _setup_transport(self):
        
        self._write = self.sock.sendall
        self._read_buffer = bytes()
340339
protected function configureSocket()
    {
        $class = $this->options['socket_class'];
        $options = $this->options['socket_options'];
        $this->socket = new $class($this->uri, $options);
    }
938447
def _setup(self):
        """"""
        super(HyperVNeutronAgent, self)._setup()

        self._sg_plugin_rpc = sg_rpc.SecurityGroupServerRpcApi(topics.PLUGIN)
        self._sec_groups_agent = HyperVSecurityAgent(self._context,
                                                     self._sg_plugin_rpc)
        self._vlan_driver = trunk_driver.HyperVTrunkDriver(self._context)
        if CONF.NVGRE.enable_support:
            self._consumers.append([h_constant.TUNNEL, topics.UPDATE])
            self._consumers.append([h_constant.LOOKUP, h_constant.UPDATE])
509606
def _configured_socket(address, options):
    
    sock = _create_connection(address, options)
    ssl_context = options.ssl_context

    if ssl_context is not None:
        host = address[0]
        try:
            # According to RFC6066, section 3, IPv4 and IPv6 literals are
            # not permitted for SNI hostname.
            if _HAVE_SNI and not is_ip_address(host):
                sock = ssl_context.wrap_socket(sock, server_hostname=host)
            else:
                sock = ssl_context.wrap_socket(sock)
        except IOError as exc:
            sock.close()
            raise ConnectionFailure("SSL handshake failed: %s" % (str(exc),))
        if ssl_context.verify_mode and options.ssl_match_hostname:
            try:
                match_hostname(sock.getpeercert(), hostname=host)
            except CertificateError:
                sock.close()
                raise

    sock.settimeout(options.socket_timeout)
    return sock
1267837
def connect(self):
        
        sock = socket.create_connection((self.host, self.port), self.timeout)
        if not USE_STDLIB_SSL:
            ssl_ctx = configure_pyopenssl_context(self.credentials)

            # attempt to upgrade the socket to TLS
            cxn = OpenSSL.SSL.Connection(ssl_ctx, sock)
            cxn.set_connect_state()
            while True:
                try:
                    cxn.do_handshake()
                except OpenSSL.SSL.WantReadError:
                    select.select([sock], [], [])
                    continue
                except OpenSSL.SSL.Error as e:
                    raise SecurityError('bad handshake - ' + str(e))
                break

            self.sock = RiakWrappedSocket(cxn, sock)
            self.credentials._check_revoked_cert(self.sock)
        else:
            ssl_ctx = configure_ssl_context(self.credentials)
            if self.timeout is not None:
                sock.settimeout(self.timeout)
            self.sock = ssl.SSLSocket(sock=sock,
                                      keyfile=self.credentials.pkey_file,
                                      certfile=self.credentials.cert_file,
                                      cert_reqs=ssl.CERT_REQUIRED,
                                      ca_certs=self.credentials.cacert_file,
                                      ciphers=self.credentials.ciphers,
                                      server_hostname=self.host)
            self.sock.context = ssl_ctx
198488
def build_socket(self):
        
        try:
            self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.sock.settimeout(self.SOCKET_TIMEOUT)
            self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            # Check if TLS
            if self.request_object.protocol == 'https':
                self.sock = ssl.wrap_socket(self.sock, ciphers=self.CIPHERS)
            self.sock.connect(
                (self.request_object.dest_addr, self.request_object.port))
        except socket.error as msg:
            raise errors.TestError(
                'Failed to connect to server',
                {
                    'host': self.request_object.dest_addr,
                    'port': self.request_object.port,
                    'proto': self.request_object.protocol,
                    'message': msg,
                    'function': 'http.HttpUA.build_socket'
                })
1372921
def _init_security(self):
        
        if not self._starttls():
            raise SecurityError("Could not start TLS connection")
        # _ssh_handshake() will throw an exception upon failure
        self._ssl_handshake()
        if not self._auth():
            raise SecurityError("Could not authorize connection")
11503
protected function makeSocket(): void
    {
        if ($this->useSSL) {
            if (!file_exists($this->cert)) {
                throw new \Exception('Cert file not found');
            }

            $context = stream_context_create([
                'ssl' => [
                    'local_cert'        => $this->cert,
                    'passphrase'        => $this->passPhrase,
                    'verify_peer'       => false,
                    'verify_peer_name'  => false,
                    'allow_self_signed' => true,
                    'verify_depth'      => 0
                ]
            ]);

            $protocol = 'ssl';
        } else {
            $context = stream_context_create();
            $protocol = 'tcp';
        }

        $this->socket = stream_socket_server("$protocol://{$this->host}:{$this->port}", $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, $context);

        if ($this->useConnector) {
            if (file_exists(static::$connector)) {
                unlink(static::$connector);
            }

            $this->unixConnector = stream_socket_server('unix://' . static::$connector, $errorNumber, $errorString, STREAM_SERVER_BIND | STREAM_SERVER_LISTEN);
            chmod(static::$connector, 0777);
        }

        if (!$this->socket) {
            throw new SocketException($errorString, $errorNumber);
        }
    }