Handle the handshake with the server.

@return handshake future for connection.
764005
public ClientHandshakeFuture handshake() {
        final DefaultClientHandshakeFuture handshakeFuture = new DefaultClientHandshakeFuture();
        try {
            URI uri = new URI(url);

            String scheme = uri.getScheme();
            if (!Constants.WS_SCHEME.equalsIgnoreCase(scheme) && !Constants.WSS_SCHEME.equalsIgnoreCase(scheme)) {
                LOG.error("Only WS(S) is supported.");
                throw new URISyntaxException(url, "WebSocket client supports only WS(S) scheme");
            }

            final String host = uri.getHost() == null ? "127.0.0.1" : uri.getHost();
            final int port = getPort(uri);
            final boolean ssl = Constants.WSS_SCHEME.equalsIgnoreCase(scheme);
            WebSocketClientHandshaker webSocketHandshaker = WebSocketClientHandshakerFactory.newHandshaker(
                    uri, WebSocketVersion.V13, subProtocols, true, headers, maxFrameSize);
            MessageQueueHandler messageQueueHandler = new MessageQueueHandler();
            clientHandshakeHandler = new WebSocketClientHandshakeHandler(webSocketHandshaker, handshakeFuture,
                                                                         messageQueueHandler, ssl, autoRead, url,
                                                                         handshakeFuture);
            Bootstrap clientBootstrap = initClientBootstrap(host, port, handshakeFuture);
            clientBootstrap.connect(uri.getHost(), port).sync();
        } catch (Exception throwable) {
            handleHandshakeError(handshakeFuture, throwable);
        }
        return handshakeFuture;
    }
851702
public function ping()
    {
        if (!$this->key || $this->operationInProgress || (time() - $this->lastPing) < $this->pingInterval) {
            // Attempt a new handshake.
            if (is_null($this->key) && (time() - $this->lastPing) > $this->retryInterval) {
                $this->lastPing = time();
                $this->handshake();
            }

            return;
        }

        $data = $this->getBasePingData();
        $query = http_build_query(
            $data
        );
        $url = $this->pingUrl . '?' . $query;

        $this->operationInProgress = true;
        $this->lastPing = time();
        $operationInProgress = &$this->operationInProgress;
        $key = &$this->key;
        $logger = $this->logger;

        $logger->debug('[eXpansion analytics]Starting ping');
        $this->http->put(
            $url,
            [],
            function (HttpResult $result) use (&$operationInProgress, &$key, $logger) {
                if ($result->getHttpCode() == '200') {
                    $operationInProgress = false;
                    $logger->debug('[eXpansion analytics]Ping successfull');
                } else {
                    $logger->debug('[eXpansion analytics]Ping failed', ['http_code' => $result->getHttpCode(), 'result' => $result->getResponse()]);
                    $key = null;
                }
            }
        );
    }
1165125
async def handler(self) -> None:
        
        try:

            try:
                path = await self.handshake(
                    origins=self.origins,
                    available_extensions=self.available_extensions,
                    available_subprotocols=self.available_subprotocols,
                    extra_headers=self.extra_headers,
                )
            except ConnectionError:
                logger.debug("Connection error in opening handshake", exc_info=True)
                raise
            except Exception as exc:
                if isinstance(exc, AbortHandshake):
                    status, headers, body = exc.status, exc.headers, exc.body
                elif isinstance(exc, InvalidOrigin):
                    logger.debug("Invalid origin", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.FORBIDDEN,
                        Headers(),
                        (str(exc) + "\n").encode(),
                    )
                elif isinstance(exc, InvalidUpgrade):
                    logger.debug("Invalid upgrade", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.UPGRADE_REQUIRED,
                        Headers([("Upgrade", "websocket")]),
                        (str(exc) + "\n").encode(),
                    )
                elif isinstance(exc, InvalidHandshake):
                    logger.debug("Invalid handshake", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.BAD_REQUEST,
                        Headers(),
                        (str(exc) + "\n").encode(),
                    )
                else:
                    logger.warning("Error in opening handshake", exc_info=True)
                    status, headers, body = (
                        http.HTTPStatus.INTERNAL_SERVER_ERROR,
                        Headers(),
                        b"See server log for more information.\n",
                    )

                headers.setdefault("Date", email.utils.formatdate(usegmt=True))
                headers.setdefault("Server", USER_AGENT)
                headers.setdefault("Content-Length", str(len(body)))
                headers.setdefault("Content-Type", "text/plain")
                headers.setdefault("Connection", "close")

                self.write_http_response(status, headers, body)
                self.fail_connection()
                await self.wait_closed()
                return

            try:
                await self.ws_handler(self, path)
            except Exception:
                logger.error("Error in connection handler", exc_info=True)
                if not self.closed:
                    self.fail_connection(1011)
                raise

            try:
                await self.close()
            except ConnectionError:
                logger.debug("Connection error in closing handshake", exc_info=True)
                raise
            except Exception:
                logger.warning("Error in closing handshake", exc_info=True)
                raise

        except Exception:
            # Last-ditch attempt to avoid leaking connections on errors.
            try:
                self.writer.close()
            except Exception:  # pragma: no cover
                pass

        finally:
            # Unregister the connection with the server when the handler task
            # terminates. Registration is tied to the lifecycle of the handler
            # task because the server waits for tasks attached to registered
            # connections before terminating.
            self.ws_server.unregister(self)
370290
private void handshake() throws WebSocketException
    {
        try
        {
            // Perform handshake with the proxy server.
            mProxyHandshaker.perform();
        }
        catch (IOException e)
        {
            // Handshake with the proxy server failed.
            String message = String.format(
                "Handshake with the proxy server (%s) failed: %s", mAddress, e.getMessage());

            // Raise an exception with PROXY_HANDSHAKE_ERROR.
            throw new WebSocketException(WebSocketError.PROXY_HANDSHAKE_ERROR, message, e);
        }

        if (mSSLSocketFactory == null)
        {
            // SSL handshake with the WebSocket endpoint is not needed.
            return;
        }

        try
        {
            // Overlay the existing socket.
            mSocket = mSSLSocketFactory.createSocket(mSocket, mHost, mPort, true);
        }
        catch (IOException e)
        {
            // Failed to overlay an existing socket.
            String message = "Failed to overlay an existing socket: " + e.getMessage();

            // Raise an exception with SOCKET_OVERLAY_ERROR.
            throw new WebSocketException(WebSocketError.SOCKET_OVERLAY_ERROR, message, e);
        }

        try
        {
            // Start the SSL handshake manually. As for the reason, see
            // http://docs.oracle.com/javase/7/docs/technotes/guides/security/jsse/samples/sockets/client/SSLSocketClient.java
            ((SSLSocket)mSocket).startHandshake();

            if (mSocket instanceof SSLSocket)
            {
                // Verify that the proxied hostname matches the certificate here since
                // this is not automatically done by the SSLSocket.
                verifyHostname((SSLSocket)mSocket, mProxyHandshaker.getProxiedHostname());
            }
        }
        catch (IOException e)
        {
            // SSL handshake with the WebSocket endpoint failed.
            String message = String.format(
                "SSL handshake with the WebSocket endpoint (%s) failed: %s", mAddress, e.getMessage());

            // Raise an exception with SSL_HANDSHAKE_ERROR.
            throw new WebSocketException(WebSocketError.SSL_HANDSHAKE_ERROR, message, e);
        }
    }
1372791
protected function handshake()
    {
        if (null !== $this->session) {
            return;
        }

        $context = $this->context;
        $protocol = $this->url['secured'] ? 'ssl' : 'http';

        if (!isset($context[$protocol])) {
            $context[$protocol] = [];
        }

        $context[$protocol]['timeout'] = (float) $this->options['timeout'];

        // add custom headers
        if (!empty($this->options['headers'])) {
            $headers = !empty($context[$protocol]['header']) ? $context[$protocol]['header'] : [];
            $context[$protocol]['header'] = \array_merge($headers, $this->options['headers']);
        }

        $url = \sprintf(
            '%s://%s:%d/%s/%d',
            $this->url['scheme'],
            $this->url['host'],
            $this->url['port'],
            \trim($this->url['path'], '/'),
            $this->options['protocol']
        );

        if (isset($this->url['query'])) {
            $url .= '/?' . \http_build_query($this->url['query']);
        }

        $result = @\file_get_contents($url, false, \stream_context_create($context));

        if (false === $result) {
            $message = null;
            $error = \error_get_last();

            if (null !== $error && false !== \strpos($error['message'], 'file_get_contents()')) {
                $message = $error['message'];
            }

            throw new ServerConnectionFailureException($message);
        }

        $sess = \explode(':', $result);
        $decoded['sid'] = $sess[0];
        $decoded['pingInterval'] = $sess[1];
        $decoded['pingTimeout'] = $sess[2];
        $decoded['upgrades'] = \array_flip(\explode(',', $sess[3]));

        if (!\in_array('websocket', $decoded['upgrades'])) {
            throw new UnsupportedTransportException('websocket');
        }

        $cookies = [];
        foreach ($http_response_header as $header) {
            if (\preg_match('/^Set-Cookie:\s*([^;]*)/i', $header, $matches)) {
                $cookies[] = $matches[1];
            }
        }
        $this->cookies = $cookies;

        $this->session = new Session(
            $decoded['sid'],
            $decoded['pingInterval'],
            $decoded['pingTimeout'],
            $decoded['upgrades']
        );
    }
763930
protected function handlePATCH()
    {
        $content = $this->getPayloadData();
        if (empty($this->folderPath)) {
            // update container properties
            $this->driver->updateContainerProperties($this->container, $content);
        } else {
            if (empty($this->filePath)) {
                // update folder properties
                $this->driver->updateFolderProperties($this->container, $this->folderPath, $content);
            } else {
                // update file properties?
                $this->driver->updateFileProperties($this->container, $this->filePath, $content);
            }
        }

        return ResponseFactory::create(['success' => true]);
    }
62039
public function execute()
    {
        $this->initialiseHandle();

        $this->applyOptionsToHandle();

        $content = curl_exec($this->handle);

        $this->info = $this->getInfoFromHandle();
        $this->errorCode = $this->getErrorCodeFromHandle();
        $this->errorMessage = $this->getErrorMessageFromHandle();

        $this->closeHandle();

        return $content;
    }
971973
public ApiResponse<Void> getHandshakeWithHttpInfo() throws ApiException {
        com.squareup.okhttp.Call call = getHandshakeValidateBeforeCall(null, null);
        return apiClient.execute(call);
    }
1357942
public Future<Channel> renegotiate() {
        ChannelHandlerContext ctx = this.ctx;
        if (ctx == null) {
            throw new IllegalStateException();
        }

        return renegotiate(ctx.executor().<Channel>newPromise());
    }
925913
public function handleRequest(): self
    {
        if ($this->params->getBotParam('webhook.url')) {
            return $this->handleWebhook();
        }

        if ($loop_time = $this->getLoopTime()) {
            return $this->handleGetUpdatesLoop($loop_time, $this->getLoopInterval());
        }

        return $this->handleGetUpdates();
    }
1077096
protected function handleUpdates()
    {
        $config = $this->app->make('config');
        if (!$config->get('concrete.maintenance_mode')) {
            try {
                $this->app->handleAutomaticUpdates();
            } catch (MutexBusyException $x) {
                if ($x->getMutexKey() !== Update::MUTEX_KEY) {
                    throw $x;
                }
                $config->set('concrete.maintenance_mode', true);
            }
            catch (MigrationIncompleteException $x) {
                $request = Request::getInstance();
                $requestUri = $request->getUri();
                $rf = $this->app->make(ResponseFactoryInterface::class);
                return $rf->redirect($requestUri, Response::HTTP_FOUND);
            }
        }
    }
214148
public function execute() {

		// Register all handles and monitor that
		// all requests are executed
		$handleExecutionCounter = array();

		foreach( $this->httpRequests as $httpRequest ) {
			$httpRequest->setOption( CURLOPT_RETURNTRANSFER, true );
			$handleExecutionCounter[(int)  $httpRequest() ] = true;
			curl_multi_add_handle( $this->handle, $httpRequest() );
		}

		$response = $this->doMakeMultiRequest( $handleExecutionCounter );

		return $response;
	}
987786
public function handleWorkerHandlerQueue()
    {
        if (!$this->workerHandlerReady || count($this->workerHandlerQueue) == 0) {
            return;
        }
        $requestId = array_shift($this->workerHandlerQueue);
        $request   = $this->getRequest($requestId);

        if ($request === null) {
            return;
        }

        $this->getLogger()->debug('Sending request: '.$requestId.' to worker-handler.');

        $this->workerHandlerReady = false;

        $this->getStream('workerHandler')->send(
            new ClientHandlerJobRequest(
                $requestId,
                $request->getActionName(),
                $request->getParams()
            )
        );
    }
395785
public function handle()
    {
        $browser = $this->createBrowser();

        try {
            $method = $this->proxy_query->getMethod();
            $headers = Utils::prepareHeadersForRequest($this->proxy_query->getHeaders(), $this->headerBlackList,
                $this->headerWhiteList);
            $headers['User-Agent'] = $this->userAgent;
            $url = $this->proxy_query->getGetUrl();

            $this->logger->debug("{$this->logMessagePrefix}->handle {$method}:" . $url);
            $this->logger->debug("{$this->logMessagePrefix}->handle Headers: " . print_r($headers, true));

            if ($method === Utils::$METHOD_POST) {
                if ($this->proxy_query->getContent() !== null) {
                    $content = $this->proxy_query->getContent();
                } else {
                    $content = $this->proxy_query->getPostQueryString();
                }
                $browserResponse = $browser->post($url, $headers, $content);
            } else if ($method === Utils::$METHOD_GET) {
                $browserResponse = $browser->get($url, $headers);
            }
            /** @var Response $browserResponse */
        } catch (\Exception $e) {
            $this->logger->error("{$this->logMessagePrefix}->handle :" . $e->getMessage());
            throw new HTTPStatus502Exception($e->getMessage(), 502);
        }
        return $browserResponse;
    }
1152232
protected function handshake()
    {
        $key =        &$this->key;
        $lastPing =   &$this->lastPing;
        $that = $this;
        $logger = $this->logger;

        $query = http_build_query(
            ['login' => $this->gameData->getSystemInfo()->serverLogin]
        );
        $url = $this->handshakeUrl . '?' . $query;

        $lastPing = time();
        $this->logger->debug("[eXpansion analytics]Starting handshake");


        $this->http->put(
            $url,
            [],
            function (HttpResult $result) use (&$key, &$lastPing, $logger, $that) {
                $key = null;
                if ($result->getHttpCode() != '200') {
                    $logger->debug('[eXpansion analytics]Handshake failed', ['http_code' => $result->getHttpCode()]);
                    return;
                }

                $json = json_decode($result->getResponse());
                if (isset($json->key) && !empty($json->key)) {
                    $logger->debug('[eXpansion analytics]Handshake successfull', ['key' => $json->key]);

                    $key = $json->key;
                    $that->ping();

                    // allow ping just after handshake.
                    $lastPing = 0;
                }
            }
        );
    }
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
198790
public function handle()
    {
        return $this->dbTransaction(function () {
            $lastAction = $this->block->restore();

            event('block.restored', [$this->block]);

            return $lastAction;
        });
    }