Sends a handshake message reply
@param string Received data (no use in this class)
@return boolean OK?
346136
public function sendHandshakeReply($extraHeaders = '')
    {
        if (!isset($this->server['HTTP_SEC_WEBSOCKET_KEY1']) || !isset($this->server['HTTP_SEC_WEBSOCKET_KEY2'])) {
            return false;
        }

        $final_key = $this->_computeFinalKey(
            $this->server['HTTP_SEC_WEBSOCKET_KEY1'],
            $this->server['HTTP_SEC_WEBSOCKET_KEY2'],
            $this->key
        );
        $this->key = null;

        if (!$final_key) {
            return false;
        }

        if (!isset($this->server['HTTP_SEC_WEBSOCKET_ORIGIN'])) {
            $this->server['HTTP_SEC_WEBSOCKET_ORIGIN'] = '';
        }

        $this->write("HTTP/1.1 101 Web Socket Protocol Handshake\r\n"
            . "Upgrade: WebSocket\r\n"
            . "Connection: Upgrade\r\n"
            . "Sec-WebSocket-Origin: " . $this->server['HTTP_ORIGIN'] . "\r\n"
            . "Sec-WebSocket-Location: ws://" . $this->server['HTTP_HOST'] . $this->server['REQUEST_URI'] . "\r\n");
        if ($this->pool->config->expose->value) {
            $this->writeln('X-Powered-By: phpDaemon/' . Daemon::$version);
        }
        if (isset($this->server['HTTP_SEC_WEBSOCKET_PROTOCOL'])) {
            $this->writeln("Sec-WebSocket-Protocol: " . $this->server['HTTP_SEC_WEBSOCKET_PROTOCOL']);
        }
        $this->write($extraHeaders . "\r\n" . $final_key);
        return true;
    }
916928
public function send(
        $from_name,
        array $receivers,
        &$successfulRecipients,
        &$failedRecipients,
        $subject = '',
        $body = '',
        $content_type = 'text/html',
        $charset = 'UTF-8'
    )
    {
        $mailer = \Swift_Mailer::newInstance($this->transport);
        $message = \Swift_Message::newInstance();
        $message->setFrom([$this->_username => $from_name]);
        $message->setTo($receivers);
        $message->setSubject($subject);
        $message->setBody($body, $content_type, $charset);
        $successfulRecipients = $mailer->send($message, $failedRecipients);
        return true;
    }
125597
public function sendMessage(Message $message)
    {
        $this->currentId++;
        $messageData = $message->convertToRconData($this->currentId);
        $this->client->write($messageData);

        return $this->getResponseMessage();
    }
1146277
void handshakeAlert(byte description) throws SSLProtocolException {
        String message = Alerts.alertDescription(description);

        if (debug != null && Debug.isOn("handshake")) {
            System.out.println("SSL - handshake alert: " + message);
        }
        throw new SSLProtocolException("handshake alert:  " + message);
    }
404855
public function sendData($data)
    {
        if (is_array($data) && count($data)) {
            $class = $this->getResponseClass();

            return $this->response = new $class($this, $data);
        }

        return false;
    }
1299136
private function defaultHandShake($request, $response)
    {
        $secWebSocketKey = $request->getHeaderLine('sec-websocket-key');
        if (0 === preg_match('#^[+/0-9A-Za-z]{21}[AQgw]==$#', $secWebSocketKey) || 16 !== strlen(base64_decode($secWebSocketKey)))
        {
            return;
        }

        $key = base64_encode(sha1($secWebSocketKey . '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true));

        $headers = [
            'Upgrade'               => 'websocket',
            'Connection'            => 'Upgrade',
            'Sec-WebSocket-Accept'  => $key,
            'Sec-WebSocket-Version' => '13',
        ];

        if($request->hasHeader('Sec-WebSocket-Protocol'))
        {
            $headers['Sec-WebSocket-Protocol'] = $request->getHeaderLine('Sec-WebSocket-Protocol');
        }

        foreach ($headers as $key => $val)
        {
            $response = $response->withHeader($key, $val);
        }

        $response = $response->withStatus(StatusCode::SWITCHING_PROTOCOLS);
        
        return $response;
    }
1167560
public function onData($data)
    {
        if (!$this->handshaked) {
            return $this->handshake($data);
        }
        return $this->handle($data);
    }
941217
function send($op,$data='') {
		$server=$this->server;
		$mask=WS::Finale | $op & WS::OpCode;
		$len=strlen($data);
		$buf='';
		if ($len>0xffff)
			$buf=pack('CCNN',$mask,0x7f,$len);
		else
		if ($len>0x7d)
			$buf=pack('CCn',$mask,0x7e,$len);
		else
			$buf=pack('CC',$mask,$len);
		$buf.=$data;
		if (is_bool($server->write($this->socket,$buf)))
			return FALSE;
		if (!in_array($op,[WS::Pong,WS::Close]) &&
			isset($this->events['send']) &&
			is_callable($func=$this->events['send']))
			$func($this,$op,$data);
		return $data;
	}
1317430
public function Send ($data, $reply = FALSE)
	{
		
		// Check the stream is connected
		
		if ($this->_stream === FALSE)
		{
			
			// If not create an error
			
			$this->Error ('Cannot send data, the stream is not connected!');
			
			// return FALSE
			
			return FALSE;
			
		}
		
		// If the data is an array
		
		if (is_array ($data))
		{
			
			// Development Mode
			
			if ($this->dev)
			{
				
				// Add to log
				
				$this->log[]	= 'Send data array:';
				
			}
			
			// Foreach data value
			
			foreach ($data as $val)
			{
				
				// Development Mode
				
				if ($this->dev)
				{
					
					// Add to log
					
					$this->log[]	= $val;
					
				}
				
				// Send the data through the stream
				
				$send	= stream_socket_sendto ($this->_stream, $val . "\r\n");
				
				// If there was an error sending the data
				
				if ($send === FALSE)
				{
					
					// Set an error
					
					$this->Error ('Error sending data: #' . $this->errorCode . ' - ' . $this->errorMessage);
					
					// Close the stream
					
					$this->Close ();
					
					// return FALSE
					
					return FALSE;
					
				}
				
			}
			
		}
		
		// If the data is not an array
		
		else
		{
			
			// Development Mode
			
			if ($this->dev)
			{
				
				// Add to log
				
				$this->log[]	= 'Send: ' . $data;
				
			}
			
			// Send the data through the stream
			
			$send	= stream_socket_sendto ($this->_stream, $data . "\r\n");
			
			// If there was an error sending the data
			
		
			if ($send === FALSE)
			{
				
				// Set an error
				
				$this->Error ('Error sending data: #' . $this->errorCode . ' - ' . $this->errorMessage);
				
				// Close the stream
				
				$this->Close ();
				
				// return FALSE
				
				return FALSE;
				
			}
			
		}
		
		// If a reply is expected
		
		if ($reply !== FALSE)
		{
			
			return $this->Receive ($reply);
			
		}
		
		// Return TRUE
		
		return TRUE;
		
	}
977982
function send($mnet_peer) {
        global $CFG, $DB;


        if (!$this->permission_to_call($mnet_peer)) {
            mnet_debug("tried and wasn't allowed to call a method on $mnet_peer->wwwroot");
            return false;
        }

        $this->requesttext = xmlrpc_encode_request($this->method, $this->params, array("encoding" => "utf-8", "escaping" => "markup"));
        $this->signedrequest = mnet_sign_message($this->requesttext);
        $this->encryptedrequest = mnet_encrypt_message($this->signedrequest, $mnet_peer->public_key);

        $httprequest = $this->prepare_http_request($mnet_peer);
        curl_setopt($httprequest, CURLOPT_POSTFIELDS, $this->encryptedrequest);

        $timestamp_send    = time();
        mnet_debug("about to send the curl request");
        $this->rawresponse = curl_exec($httprequest);
        mnet_debug("managed to complete a curl request");
        $timestamp_receive = time();

        if ($this->rawresponse === false) {
            $this->error[] = curl_errno($httprequest) .':'. curl_error($httprequest);
            return false;
        }
        curl_close($httprequest);

        $this->rawresponse = trim($this->rawresponse);

        $mnet_peer->touch();

        $crypt_parser = new mnet_encxml_parser();
        $crypt_parser->parse($this->rawresponse);

        // If we couldn't parse the message, or it doesn't seem to have encrypted contents,
        // give the most specific error msg available & return
        if (!$crypt_parser->payload_encrypted) {
            if (! empty($crypt_parser->remoteerror)) {
                $this->error[] = '4: remote server error: ' . $crypt_parser->remoteerror;
            } else if (! empty($crypt_parser->error)) {
                $crypt_parser_error = $crypt_parser->error[0];

                $message = '3:XML Parse error in payload: '.$crypt_parser_error['string']."\n";
                if (array_key_exists('lineno', $crypt_parser_error)) {
                    $message .= 'At line number: '.$crypt_parser_error['lineno']."\n";
                }
                if (array_key_exists('line', $crypt_parser_error)) {
                    $message .= 'Which reads: '.$crypt_parser_error['line']."\n";
                }
                $this->error[] = $message;
            } else {
                $this->error[] = '1:Payload not encrypted ';
            }

            $crypt_parser->free_resource();
            return false;
        }

        $key  = array_pop($crypt_parser->cipher);
        $data = array_pop($crypt_parser->cipher);

        $crypt_parser->free_resource();

        // Initialize payload var
        $decryptedenvelope = '';

        //                                          &$decryptedenvelope
        $isOpen = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $this->mnet->get_private_key());

        if (!$isOpen) {
            // Decryption failed... let's try our archived keys
            $openssl_history = get_config('mnet', 'openssl_history');
            if(empty($openssl_history)) {
                $openssl_history = array();
                set_config('openssl_history', serialize($openssl_history), 'mnet');
            } else {
                $openssl_history = unserialize($openssl_history);
            }
            foreach($openssl_history as $keyset) {
                $keyresource = openssl_pkey_get_private($keyset['keypair_PEM']);
                $isOpen      = openssl_open(base64_decode($data), $decryptedenvelope, base64_decode($key), $keyresource);
                if ($isOpen) {
                    // It's an older code, sir, but it checks out
                    break;
                }
            }
        }

        if (!$isOpen) {
            trigger_error("None of our keys could open the payload from host {$mnet_peer->wwwroot} with id {$mnet_peer->id}.");
            $this->error[] = '3:No key match';
            return false;
        }

        if (strpos(substr($decryptedenvelope, 0, 100), '<signedMessage>')) {
            $sig_parser = new mnet_encxml_parser();
            $sig_parser->parse($decryptedenvelope);
        } else {
            $this->error[] = '2:Payload not signed: ' . $decryptedenvelope;
            return false;
        }

        // Margin of error is the time it took the request to complete.
        $margin_of_error  = $timestamp_receive - $timestamp_send;

        // Guess the time gap between sending the request and the remote machine
        // executing the time() function. Marginally better than nothing.
        $hysteresis       = ($margin_of_error) / 2;

        $remote_timestamp = $sig_parser->remote_timestamp - $hysteresis;
        $time_offset      = $remote_timestamp - $timestamp_send;
        if ($time_offset > 0) {
            $threshold = get_config('mnet', 'drift_threshold');
            if(empty($threshold)) {
                // We decided 15 seconds was a pretty good arbitrary threshold
                // for time-drift between servers, but you can customize this in
                // the config_plugins table. It's not advised though.
                set_config('drift_threshold', 15, 'mnet');
                $threshold = 15;
            }
            if ($time_offset > $threshold) {
                $this->error[] = '6:Time gap with '.$mnet_peer->name.' ('.$time_offset.' seconds) is greater than the permitted maximum of '.$threshold.' seconds';
                return false;
            }
        }

        $this->xmlrpcresponse = base64_decode($sig_parser->data_object);
        $this->response       = xmlrpc_decode($this->xmlrpcresponse);

        // xmlrpc errors are pushed onto the $this->error stack
        if (is_array($this->response) && array_key_exists('faultCode', $this->response)) {
            // The faultCode 7025 means we tried to connect with an old SSL key
            // The faultString is the new key - let's save it and try again
            // The re_key attribute stops us from getting into a loop
            if($this->response['faultCode'] == 7025 && empty($mnet_peer->re_key)) {
                mnet_debug('recieved an old-key fault, so trying to get the new key and update our records');
                // If the new certificate doesn't come thru clean_param() unmolested, error out
                if($this->response['faultString'] != clean_param($this->response['faultString'], PARAM_PEM)) {
                    $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
                }
                $record                     = new stdClass();
                $record->id                 = $mnet_peer->id;
                $record->public_key         = $this->response['faultString'];
                $details                    = openssl_x509_parse($record->public_key);
                if(!isset($details['validTo_time_t'])) {
                    $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'];
                }
                $record->public_key_expires = $details['validTo_time_t'];
                $DB->update_record('mnet_host', $record);

                // Create a new peer object populated with the new info & try re-sending the request
                $rekeyed_mnet_peer = new mnet_peer();
                $rekeyed_mnet_peer->set_id($record->id);
                $rekeyed_mnet_peer->re_key = true;
                return $this->send($rekeyed_mnet_peer);
            }
            if (!empty($CFG->mnet_rpcdebug)) {
                if (get_string_manager()->string_exists('error'.$this->response['faultCode'], 'mnet')) {
                    $guidance = get_string('error'.$this->response['faultCode'], 'mnet');
                } else {
                    $guidance = '';
                }
            } else {
                $guidance = '';
            }
            $this->error[] = $this->response['faultCode'] . " : " . $this->response['faultString'] ."\n".$guidance;
        }

        // ok, it's signed, but is it signed with the right certificate ?
        // do this *after* we check for an out of date key
        $verified = openssl_verify($this->xmlrpcresponse, base64_decode($sig_parser->signature), $mnet_peer->public_key);
        if ($verified != 1) {
            $this->error[] = 'Invalid signature';
        }

        return empty($this->error);
    }
1184321
function _receive()
    {
        switch ($this->mode) {
            case self::MODE_SSH2:
                return $this->ssh->_get_channel_packet(SSH2::CHANNEL_EXEC, true);
            case self::MODE_SSH1:
                if (!$this->ssh->bitmap) {
                    return false;
                }
                while (true) {
                    $response = $this->ssh->_get_binary_packet();
                    switch ($response[SSH1::RESPONSE_TYPE]) {
                        case NET_SSH1_SMSG_STDOUT_DATA:
                            if (strlen($response[SSH1::RESPONSE_DATA]) < 4) {
                                return false;
                            }
                            extract(unpack('Nlength', $response[SSH1::RESPONSE_DATA]));
                            return $this->ssh->_string_shift($response[SSH1::RESPONSE_DATA], $length);
                        case NET_SSH1_SMSG_STDERR_DATA:
                            break;
                        case NET_SSH1_SMSG_EXITSTATUS:
                            $this->ssh->_send_binary_packet(chr(NET_SSH1_CMSG_EXIT_CONFIRMATION));
                            fclose($this->ssh->fsock);
                            $this->ssh->bitmap = 0;
                            return false;
                        default:
                            user_error('Unknown packet received', E_USER_NOTICE);
                            return false;
                    }
                }
        }
    }
539364
public function sendEmail($sesMessage) {
		if(!$sesMessage->validate()) {
			$this->__triggerError('sendEmail', 'Message failed validation.');
			return false;
		}

		$rest = new SimpleEmailServiceRequest($this, 'POST');
		$rest->setParameter('Action', 'SendEmail');

		$i = 1;
		foreach($sesMessage->to as $to) {
			$rest->setParameter('Destination.ToAddresses.member.'.$i, $to);
			$i++;
		}

		if(is_array($sesMessage->cc)) {
			$i = 1;
			foreach($sesMessage->cc as $cc) {
				$rest->setParameter('Destination.CcAddresses.member.'.$i, $cc);
				$i++;
			}
		}

		if(is_array($sesMessage->bcc)) {
			$i = 1;
			foreach($sesMessage->bcc as $bcc) {
				$rest->setParameter('Destination.BccAddresses.member.'.$i, $bcc);
				$i++;
			}
		}

		if(is_array($sesMessage->replyto)) {
			$i = 1;
			foreach($sesMessage->replyto as $replyto) {
				$rest->setParameter('ReplyToAddresses.member.'.$i, $replyto);
				$i++;
			}
		}

		$rest->setParameter('Source', $sesMessage->from);

		if($sesMessage->returnpath != null) {
			$rest->setParameter('ReturnPath', $sesMessage->returnpath);
		}

		if($sesMessage->subject != null && strlen($sesMessage->subject) > 0) {
			$rest->setParameter('Message.Subject.Data', $sesMessage->subject);
			if($sesMessage->subjectCharset != null && strlen($sesMessage->subjectCharset) > 0) {
				$rest->setParameter('Message.Subject.Charset', $sesMessage->subjectCharset);
			}
		}


		if($sesMessage->messagetext != null && strlen($sesMessage->messagetext) > 0) {
			$rest->setParameter('Message.Body.Text.Data', $sesMessage->messagetext);
			if($sesMessage->messageTextCharset != null && strlen($sesMessage->messageTextCharset) > 0) {
				$rest->setParameter('Message.Body.Text.Charset', $sesMessage->messageTextCharset);
			}
		}

		if($sesMessage->messagehtml != null && strlen($sesMessage->messagehtml) > 0) {
			$rest->setParameter('Message.Body.Html.Data', $sesMessage->messagehtml);
			if($sesMessage->messageHtmlCharset != null && strlen($sesMessage->messageHtmlCharset) > 0) {
				$rest->setParameter('Message.Body.Html.Charset', $sesMessage->messageHtmlCharset);
			}
		}

		$rest = $rest->getResponse();
		if($rest->error === false && $rest->code !== 200) {
			$rest->error = array('code' => $rest->code, 'message' => 'Unexpected HTTP status');
		}
		if($rest->error !== false) {
			$this->__triggerError('sendEmail', $rest->error);
			return false;
		}

		$response['MessageId'] = (string)$rest->body->SendEmailResult->MessageId;
		$response['RequestId'] = (string)$rest->body->ResponseMetadata->RequestId;
		return $response;
	}
255865
public function doSslHandshake($socket){
        if (feof($socket)) {
            $this->destroy();
            return false;
        }
        $async = $this instanceof AsyncTcpConnection;
        
        /**
          *  We disabled ssl3 because https://blog.qualys.com/ssllabs/2014/10/15/ssl-3-is-dead-killed-by-the-poodle-attack.
          *  You can enable ssl3 by the codes below.
          */
        /*if($async){
            $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT | STREAM_CRYPTO_METHOD_SSLv3_CLIENT;
        }else{
            $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER | STREAM_CRYPTO_METHOD_SSLv3_SERVER;
        }*/
        
        if($async){
            $type = STREAM_CRYPTO_METHOD_SSLv2_CLIENT | STREAM_CRYPTO_METHOD_SSLv23_CLIENT;
        }else{
            $type = STREAM_CRYPTO_METHOD_SSLv2_SERVER | STREAM_CRYPTO_METHOD_SSLv23_SERVER;
        }
        
        // Hidden error.
        set_error_handler(function($errno, $errstr, $file){
            if (!Worker::$daemonize) {
                Worker::safeEcho("SSL handshake error: $errstr \n");
            }
        });
        $ret     = stream_socket_enable_crypto($socket, true, $type);
        restore_error_handler();
        // Negotiation has failed.
        if (false === $ret) {
            $this->destroy();
            return false;
        } elseif (0 === $ret) {
            // There isn't enough data and should try again.
            return false;
        }
        if (isset($this->onSslHandshake)) {
            try {
                call_user_func($this->onSslHandshake, $this);
            } catch (\Exception $e) {
                Worker::log($e);
                exit(250);
            } catch (\Error $e) {
                Worker::log($e);
                exit(250);
            }
        }
        return true;
    }
718837
public function send(
        array $data,
        MembershipInterface $sender,
        MembershipInterface $receiver,
        MessageParticipantModelInterface $replyTo = null // TODO: Check if this should be Message instead
    ): PodiumResponse
    {
        $sending = $this->getMessenger();

        $sending->setSender($sender);
        $sending->setReceiver($receiver);
        $sending->setReplyTo($replyTo);

        if (!$sending->loadData($data)) {
            return PodiumResponse::error();
        }

        return $sending->send();
    }
356963
protected function handleReady($data)
    {
        $this->logger->debug('ready packet received');

        // If this is a reconnect we don't want to
        // reparse the READY packet as it would remove
        // all the data cached.
        if ($this->reconnecting) {
            $this->reconnecting = false;
            $this->logger->debug('websocket reconnected to discord through identify');

            return;
        }

        $content = $data->d;
        $this->emit('trace', $data->d->_trace);
        $this->logger->debug('discord trace received', ['trace' => $content->_trace]);

        // Setup the user account
        $this->client    = $this->factory->create(Client::class, $content->user, true);
        $this->sessionId = $content->session_id;

        $this->logger->debug('client created and session id stored', ['session_id' => $content->session_id, 'user' => $this->client->user->getPublicAttributes()]);

        // Private Channels
        $private_channels = new PrivateChannelRepository(
            $this->http,
            $this->cache,
            $this->factory
        );

        if ($this->options['pmChannels']) {
            foreach ($content->private_channels as $channel) {
                $channelPart = $this->factory->create(Channel::class, $channel, true);
                $this->cache->set("pm_channels.{$channelPart->recipient->id}", $channelPart);
                $private_channels->push($channelPart);
            }

            $this->logger->info('stored private channels', ['count' => $private_channels->count()]);
        } else {
            $this->logger->info('did not parse private channels');
        }

        $this->private_channels = $private_channels;

        // Guilds
        $this->guilds = new GuildRepository(
            $this->http,
            $this->cache,
            $this->factory
        );
        $event = new GuildCreate(
            $this->http,
            $this->factory,
            $this->cache,
            $this
        );

        $unavailable = [];

        foreach ($content->guilds as $guild) {
            $deferred = new Deferred();

            $deferred->promise()->then(null, function ($d) use (&$unavailable) {
                list($status, $data) = $d;

                if ($status == 'unavailable') {
                    $unavailable[$data] = $data;
                }
            });

            $event->handle($deferred, $guild);
        }

        $this->logger->info('stored guilds', ['count' => $this->guilds->count()]);

        if (count($unavailable) < 1) {
            return $this->ready();
        }

        // Emit ready after 60 seconds
        $this->loop->addTimer(60, function () {
            $this->ready();
        });

        $function = function ($guild) use (&$function, &$unavailable) {
            if (array_key_exists($guild->id, $unavailable)) {
                unset($unavailable[$guild->id]);
            }

            // todo setup timer to continue after x amount of time
            if (count($unavailable) < 1) {
                $this->logger->info('all guilds are now available', ['count' => $this->guilds->count()]);
                $this->removeListener(Event::GUILD_CREATE, $function);

                $this->setupChunking();
            }
        };

        $this->on(Event::GUILD_CREATE, $function);
    }
74390
public function receiveMessage()
    {
        $response = $this->client->receiveMessage(['QueueUrl' => $this->queueName]);

        if (empty($response['Messages'])) {
            return false;
        }
        $data = reset($response['Messages']);
        return new Message([
            'messageId' => $data['MessageId'],
            'messageBody' => $data['Body'],
            'queue' => $this->queue,
            'receiptHandle' => $data['ReceiptHandle'],
        ]);
    }
848783
protected function handshake()
    {
        if (null !== $this->session) {
            return;
        }

        $query = ['use_b64'   => $this->options['use_b64'],
                  'EIO'       => $this->options['version'],
                  'transport' => $this->options['transport']];

        if (isset($this->url['query'])) {
            $query = \array_replace($query, $this->url['query']);
        }

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

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

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

        $url    = \sprintf(
            '%s://%s:%d/%s/?%s',
            $this->url['scheme'],
            $this->url['host'],
            $this->url['port'],
            \trim($this->url['path'], '/'),
            \http_build_query($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);
        }

        $open_curly_at = \strpos($result, '{');
        $todecode = \substr($result, $open_curly_at, \strrpos($result, '}')-$open_curly_at+1);
        $decoded = \json_decode($todecode, true);

        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'] / 1000,
            $decoded['pingTimeout'] / 1000,
            $decoded['upgrades']
        );
    }