Establish an HTTP tunnel to the specified authority over this socket.

@param ClientSocket $socket
@param string       $authority

@return Promise
436598
public function tunnel(ClientSocket $socket, string $authority): Promise {
        return call(function () use ($socket, $authority) {
            $parser = new Parser(null);
            $parser->enqueueResponseMethodMatch("CONNECT");

            try {
                yield $socket->write("CONNECT {$authority} HTTP/1.1\r\n\r\n");
            } catch (StreamException $e) {
                new SocketException(
                    'Proxy CONNECT failed: Socket went away while writing tunneling request',
                    0,
                    $e
                );
            }

            try {
                while (null !== $chunk = yield $socket->read()) {
                    if (!$response = $parser->parse($chunk)) {
                        continue;
                    }

                    if ($response["status"] === 200) {
                        // Tunnel connected! We're finished \o/ #WinningAtLife #DealWithIt
                        \stream_context_set_option($socket->getResource(), 'artax*', 'is_tunneled', true);
                        return $socket->getResource();
                    }

                    throw new HttpException(\sprintf(
                        'Proxy CONNECT failed: Unexpected response status received from proxy: %d',
                        $response["status"]
                    ));
                }
            } catch (ParseException $e) {
                throw new HttpException(
                    'Proxy CONNECT failed: Malformed HTTP response received from proxy while establishing tunnel',
                    0,
                    $e
                );
            } catch (StreamException $e) {
                // fall through
            }

            throw new SocketException(
                'Proxy CONNECT failed: Socket went away while awaiting tunneling response',
                0,
                $e ?? null
            );
        });
    }
1055797
public function setHttpClient($client,
        $applicationId = 'MyCompany-MyApp-1.0')
    {
        if ($client === null) {
            $client = new Zend_Http_Client();
        }
        if (!$client instanceof Zend_Http_Client) {
            require_once 'Zend/Gdata/App/HttpException.php';
            throw new Zend_Gdata_App_HttpException(
                'Argument is not an instance of Zend_Http_Client.');
        }
        $userAgent = $applicationId . ' Zend_Framework_Gdata/' .
            Zend_Version::VERSION;
        $client->setHeaders('User-Agent', $userAgent);
        $client->setConfig(array(
            'strictredirects' => true
            )
        );
        $this->_httpClient = $client;
        self::setStaticHttpClient($client);
        return $this;
    }
385171
public function socket($request = null)
    {
        if (! $request && ! $this->container->bound('request')) {
            return null;
        }

        $request = $request ?: $this->container['request'];

        return $request->header('X-Socket-ID');
    }
1002878
public static function assumeSocket($address, $port = 0): void
    {
        $socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

        assumeThat($socket, is(not(false)), self::$SOCK_ERR_MSG . socket_last_error($socket));
        assumeThat(
            @socket_connect($socket, $address, $port),
            is(not(false)),
            'Unable to connect: ' . $address . ':' . $port
        );
    }
1202404
protected function getStream($socket)
    {
        if (class_exists(DuplexResourceStream::class)) {
            return new DuplexResourceStream($socket, $this->getLoop());
        }

        return new Stream($socket, $this->getLoop());
    }
138881
public function socket($request = null)
    {
        if (is_null($request) && ! $this->app->bound('request')) {
            return;
        }

        $request = $request ?: $this->app['request'];

        if ($request->hasHeader('X-Socket-ID')) {
            return $request->header('X-Socket-ID');
        }
    }
514260
public function handleConnection($socket)
    {
        stream_set_blocking($socket, 0);
        $client = $this->createConnection($socket);

        $timer = $this->loop->addTimer(5, function() use ($client) {
            $client->removeAllListeners('init');
            $client->end('Timeout waiting for PROXY header.');
            $this->emit('proxytimeout', [new Connection($client->stream, $this->loop)]);
        });

        $client->on('init', function($connection) use ($client, $timer) {
            $timer->cancel();
            $this->emit('connection', [$connection]);
        });
    }
915954
public long getSocketChannelHandle(SocketChannel socketChannel) {
        StartPrivilegedThread privThread = new StartPrivilegedThread(socketChannel);
        return AccessController.doPrivileged(privThread);
    }
1041040
public function getOAuthClient($client_id, $client_secret, $redirect_uri)
    {
        $options = [
            'clientId' => $client_id,
            'clientSecret' => $client_secret,
            'redirectUri' => $redirect_uri
        ];
        $OAuthClient = new OAuth($options);

        return $OAuthClient;
    }
373187
public static function authorize($clientID, $clientSecret)
    {
        return json_decode(
            (new AuthorizationRequest($clientID, $clientSecret))->execute()->getBody(), true
        );
    }
700528
public function handleConnect($server, $socket)
    {
        $socket->conn = new NetworkConnection($socket);

        try
        {
            $this->component->handleConnect($socket->conn);

            $socket->on('data',  [ $this, 'handleData' ]);
            $socket->on('error', [ $this, 'handleError' ]);
            $socket->on('close', [ $this, 'handleDisconnect' ]);
        }
        catch (Error $ex)
        {
            $this->close($socket);
        }
        catch (Exception $ex)
        {
            $this->close($socket);
        }
    }
202861
protected function _initRequest($socket, $response)
    {
        $stream = $this->_classes['stream'];

        $curlOptions = $socket->options();
        $curlOptions[CURLOPT_INFILESIZE] = $socket->outgoing()->length();

        if (isset($curlOptions[CURLOPT_FILE])) {
            $response->body(fopen($curlOptions[CURLOPT_FILE], 'w+'));
        }
        $socket->incoming($response->stream());

        if (!$handle = curl_init()) {
            throw new ClientException('Unable to create a new cURL handle');
        }
        curl_setopt_array($handle, $curlOptions);
        return $handle;
    }
541506
public static function listen(
        string $uri,
        Socket\ServerListenContext $listenContext = null,
        Socket\ServerTlsContext $tlsContext = null
    ): Promise {
        return call(function () use ($uri, $listenContext, $tlsContext) {
            if (!self::isWorker()) {
                return Socket\listen($uri, $listenContext, $tlsContext);
            }

            $listenContext = $listenContext ?? new Socket\ServerListenContext;

            if (canReusePort()) {
                $position = \strrpos($uri, ":");
                $port = $position ? (int) \substr($uri, $position) : 0;

                if ($port === 0) {
                    $uri = yield self::$client->selectPort($uri);
                }

                $listenContext = $listenContext->withReusePort();
                return Socket\listen($uri, $listenContext, $tlsContext);
            }

            $socket = yield self::$client->importSocket($uri);
            return self::listenOnBoundSocket($socket, $listenContext, $tlsContext);
        });
    }
623168
protected function writeRequest($socket, RequestInterface $request, int $bufferSize = 8192)
    {
        if (false === $this->fwrite($socket, $this->transformRequestHeadersToString($request))) {
            throw new BrokenPipeException('Failed to send request, underlying socket not accessible, (BROKEN EPIPE)', $request);
        }

        if ($request->getBody()->isReadable()) {
            $this->writeBody($socket, $request, $bufferSize);
        }
    }
696462
function granted(data, socket) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            logger.debug(`i grant access to ${util.format(data.id)}`);
            broadcast('available');
            let socketNamespace = data.id;
            let newData = {
                script: ss.createStream(),
                inputs: {}
            };
            for (let inputSymbol in data.inputs) {
                //let filePath = data.inputs[inputSymbol];
                //logger.debug(`-->${filePath}`);
                newData.inputs[inputSymbol] = ss.createStream();
                logger.debug(`ssStream emission for input symbol '${inputSymbol}'`);
                ss(socket).emit(socketNamespace + "/" + inputSymbol, newData.inputs[inputSymbol]);
                //logger.warn('IeDump from' +  socketNamespace + "/" + inputSymbol);
                //newData.inputs[inputSymbol].pipe(process.stdout)
            }
            ss(socket).emit(socketNamespace + "/script", newData.script);
            //logger.error(`TOTOT2\n${util.format(newData)}`);
            for (let k in data) {
                if (k !== 'inputs' && k !== 'script')
                    newData[k] = data[k];
            }
            newData.socket = socket;
            socket.emit('granted', { jobID: data.id });
            resolve(newData);
        }, 250);
    });
}
261724
final public function multicastBinary(string $data, array $clientIds): Promise
    {
        return $this->multicastData($data, true, $clientIds);
    }
186380
public function pollForChallenge(string $location): Promise {
        return call(function () use ($location) {
            do {
                /** @var Response $response */
                $response = yield $this->acmeClient->get($location);
                $body = yield $response->getBody();
                $data = json_decode($body);

                if ($data->status === 'pending') {
                    if (!$response->hasHeader('retry-after')) {
                        // throw new AcmeException("Protocol Violation: No Retry-After Header!");

                        yield new Delayed(1000);
                        continue;
                    }

                    $waitTime = $this->parseRetryAfter($response->getHeader('retry-after'));
                    $waitTime = max($waitTime, 1);

                    yield new Delayed($waitTime * 1000);

                    continue;
                }

                if ($data->status === 'invalid') {
                    $errors = [];

                    foreach ($data->errors ?? [] as $error) {
                        $message = $error->title ?? '???';

                        if ($error->detail ?? '') {
                            $message .= ' (' . $error->detail . ')';
                        }

                        $errors[] = $message;
                    }

                    throw new AcmeException('Challenge marked as invalid: ' . ($errors ? \implode(', ', $errors) : ('Unknown error: ' . $body)));
                }

                if ($data->status === 'valid') {
                    break;
                }

                throw new AcmeException("Invalid challenge status: {$data->status}.");
            } while (1);
        });
    }