vendor/guzzlehttp/guzzle/src/Handler/StreamHandler.php

1253 lines · 47513 bytes

   1<?php
   2
   3namespace GuzzleHttp\Handler;
   4
   5use GuzzleHttp\Exception\ConnectException;
   6use GuzzleHttp\Exception\RequestException;
   7use GuzzleHttp\Exception\TransferException;
   8use GuzzleHttp\Multiplexing;
   9use GuzzleHttp\Promise as P;
  10use GuzzleHttp\Promise\FulfilledPromise;
  11use GuzzleHttp\Promise\PromiseInterface;
  12use GuzzleHttp\Psr7;
  13use GuzzleHttp\TransferStats;
  14use GuzzleHttp\TransportSharing;
  15use GuzzleHttp\Utils;
  16use Psr\Http\Message\RequestInterface;
  17use Psr\Http\Message\ResponseInterface;
  18use Psr\Http\Message\StreamInterface;
  19use Psr\Http\Message\UriInterface;
  20
  21/**
  22 * HTTP handler that uses PHP's HTTP stream wrapper.
  23 *
  24 * @final
  25 */
  26class StreamHandler
  27{
  28    private const KNOWN_CONSTRUCTOR_OPTIONS = [
  29        'max_host_connections' => true,
  30        'max_total_connections' => true,
  31        'transport_sharing' => true,
  32    ];
  33
  34    private const CONNECTION_ERRORS = [
  35        'php_network_getaddresses:',
  36        'getaddrinfo',
  37        'gethostbyname failed',
  38        'Connection refused',
  39        'No connection could be made because the target machine actively refused it',
  40        "couldn't connect to host", // error on HHVM
  41        'connection attempt failed',
  42        'connect() failed',
  43        'Connection timed out',
  44        'Operation timed out',
  45        'Network is unreachable',
  46        'No route to host',
  47        'Host is unreachable',
  48        'Host is down',
  49        'Cannot connect to HTTPS server through proxy',
  50    ];
  51
  52    /**
  53     * @var string
  54     */
  55    private $transportSharingMode;
  56
  57    /**
  58     * @var bool
  59     */
  60    private $connectionCapsConfigured = false;
  61
  62    /**
  63     * Accepts an associative array of options:
  64     *
  65     * - max_host_connections: Optional positive integer or null. A non-null
  66     *   value marks the handler as incompatible with enabled response
  67     *   streaming; the number is not used for stream-handler admission.
  68     * - max_total_connections: Optional positive integer or null. A non-null
  69     *   value marks the handler as incompatible with enabled response
  70     *   streaming; the number is not used for stream-handler admission.
  71     * - transport_sharing: Optional transport sharing mode.
  72     *
  73     * The stream handler cannot cap streamed connections, so a configured cap
  74     * marker rejects enabled response streaming ("stream" => true). Accepted
  75     * transfers are buffered and hold at most one connection per in-flight
  76     * call, but overlapping buffered calls are not collectively limited.
  77     *
  78     * @param array{max_host_connections?: mixed, max_total_connections?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler
  79     */
  80    public function __construct(array $options = [])
  81    {
  82        foreach ($options as $name => $_) {
  83            if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) {
  84                \trigger_deprecation('guzzlehttp/guzzle', '7.14', \sprintf('The "%s" StreamHandler constructor option is unknown; guzzlehttp/guzzle 8.0 will reject unknown constructor options.', (string) $name));
  85            }
  86        }
  87
  88        $this->transportSharingMode = CurlShareHandleState::normalizeMode(
  89            $options['transport_sharing'] ?? null,
  90            'transport_sharing'
  91        );
  92
  93        foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
  94            $value = $options[$capOption] ?? null;
  95            if ($value === null) {
  96                continue;
  97            }
  98
  99            if (!\is_int($value) || $value < 1) {
 100                throw new \InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption));
 101            }
 102
 103            $this->connectionCapsConfigured = true;
 104        }
 105    }
 106
 107    /**
 108     * Sends an HTTP request.
 109     *
 110     * @param RequestInterface $request Request to send.
 111     * @param array            $options Request transfer options.
 112     */
 113    public function __invoke(RequestInterface $request, array $options): PromiseInterface
 114    {
 115        // Sleep if there is a delay specified.
 116        if (isset($options['delay'])) {
 117            \usleep($options['delay'] * 1000);
 118        }
 119
 120        $multiplex = $options['multiplex'] ?? null;
 121
 122        // Multiplexing::NONE is trivially satisfied: the stream handler sends
 123        // one HTTP/1.x request per connection and never multiplexes.
 124        if (null !== $multiplex && !\in_array($multiplex, [Multiplexing::NONE, Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
 125            throw new \InvalidArgumentException(\sprintf(
 126                'The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.',
 127                \get_debug_type($multiplex)
 128            ));
 129        }
 130
 131        if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
 132            throw new ConnectException('The stream handler cannot guarantee a multiplexed protocol; required multiplexing needs a cURL handler.', $request);
 133        }
 134
 135        if ($this->connectionCapsConfigured && !empty($options['stream'])) {
 136            throw new \InvalidArgumentException('Enabling the "stream" request option on a stream handler configured with the "max_host_connections" or "max_total_connections" option is not supported because streamed connections cannot be capped.');
 137        }
 138
 139        if (isset($options['on_trailers'])) {
 140            throw new \InvalidArgumentException('Passing the "on_trailers" request option to the stream handler is not supported because the stream handler cannot observe trailers.');
 141        }
 142
 143        $protocolVersion = $request->getProtocolVersion();
 144
 145        if ('' === $protocolVersion) {
 146            \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with an empty protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
 147
 148            $protocolVersion = '1.1';
 149            $request = Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
 150        }
 151
 152        if ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
 153            throw new ConnectException(sprintf('HTTP/%s is not supported by the stream handler.', $protocolVersion), $request);
 154        }
 155
 156        $startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
 157
 158        self::triggerUnsupportedRequestOptionDeprecations($request, $options);
 159        $this->assertTransportSharingSupported();
 160
 161        try {
 162            // Does not support the expect header.
 163            $request = $request->withoutHeader('Expect');
 164
 165            // Append a content-length header if body size is zero to match
 166            // the behavior of `CurlHandler`
 167            if (
 168                (
 169                    Psr7\Utils::caselessEquals('PUT', $request->getMethod())
 170                    || Psr7\Utils::caselessEquals('POST', $request->getMethod())
 171                )
 172                && 0 === $request->getBody()->getSize()
 173            ) {
 174                $request = $request->withHeader('Content-Length', '0');
 175            }
 176
 177            $stream = $this->createStream($request, $options);
 178            $headers = \stream_get_meta_data($stream)['wrapper_data'];
 179
 180            return $this->createResponse(
 181                $request,
 182                $options,
 183                $stream,
 184                \is_array($headers) ? $headers : [],
 185                $startTime
 186            );
 187        } catch (\InvalidArgumentException $e) {
 188            throw $e;
 189        } catch (\Exception $e) {
 190            if (!$e instanceof TransferException) {
 191                $e = self::isConnectionError($e->getMessage())
 192                    ? new ConnectException($e->getMessage(), $request, $e)
 193                    : new RequestException($e->getMessage(), $request, null, $e);
 194            }
 195            $this->invokeStats($options, $request, $startTime, null, $e);
 196
 197            return P\Create::rejectionFor($e);
 198        }
 199    }
 200
 201    private static function isConnectionError(string $message): bool
 202    {
 203        foreach (self::CONNECTION_ERRORS as $connectionError) {
 204            if (false !== \strpos($message, $connectionError)) {
 205                return true;
 206            }
 207        }
 208
 209        return false;
 210    }
 211
 212    private function invokeStats(
 213        array $options,
 214        RequestInterface $request,
 215        ?float $startTime,
 216        ?ResponseInterface $response = null,
 217        ?\Throwable $error = null
 218    ): void {
 219        if (isset($options['on_stats'])) {
 220            $stats = new TransferStats($request, $response, Utils::currentTime() - $startTime, $error, []);
 221            ($options['on_stats'])($stats);
 222        }
 223    }
 224
 225    /**
 226     * @param resource $stream
 227     */
 228    private function createResponse(RequestInterface $request, array $options, $stream, array $hdrs, ?float $startTime): PromiseInterface
 229    {
 230        try {
 231            [$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
 232        } catch (\Throwable $e) {
 233            return $this->rejectResponseCreation($options, $request, $startTime, $e);
 234        }
 235
 236        [$stream, $headers] = $this->checkDecode($options, $headers, $stream);
 237        $stream = Psr7\Utils::streamFor($stream);
 238        $sink = $stream;
 239
 240        if (!Psr7\Utils::caselessEquals('HEAD', $request->getMethod())) {
 241            $sink = $this->createSink($stream, $options);
 242        }
 243
 244        try {
 245            $response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
 246        } catch (\Throwable $e) {
 247            return $this->rejectResponseCreation($options, $request, $startTime, $e);
 248        }
 249
 250        if (isset($options['on_headers'])) {
 251            try {
 252                $options['on_headers']($response);
 253            } catch (\Throwable $e) {
 254                return P\Create::rejectionFor(
 255                    new RequestException('An error was encountered during the on_headers event', $request, $response, $e)
 256                );
 257            }
 258        }
 259
 260        // Do not drain when the request is a HEAD request because they have
 261        // no body.
 262        if ($sink !== $stream) {
 263            $this->drain($stream, $sink, $response->getHeaderLine('Content-Length'));
 264        }
 265
 266        $this->invokeStats($options, $request, $startTime, $response, null);
 267
 268        return new FulfilledPromise($response);
 269    }
 270
 271    private function rejectResponseCreation(
 272        array $options,
 273        RequestInterface $request,
 274        ?float $startTime,
 275        \Throwable $previous
 276    ): PromiseInterface {
 277        $reason = new RequestException(
 278            'An error was encountered while creating the response',
 279            $request,
 280            null,
 281            $previous
 282        );
 283
 284        $this->invokeStats($options, $request, $startTime, null, $reason);
 285
 286        return P\Create::rejectionFor($reason);
 287    }
 288
 289    private function createSink(StreamInterface $stream, array $options): StreamInterface
 290    {
 291        if (!empty($options['stream'])) {
 292            return $stream;
 293        }
 294
 295        $sink = $options['sink'] ?? Psr7\Utils::tryFopen('php://temp', 'r+');
 296
 297        return \is_string($sink) ? new Psr7\LazyOpenStream($sink, 'w+') : Psr7\Utils::streamFor($sink);
 298    }
 299
 300    /**
 301     * @param resource $stream
 302     */
 303    private function checkDecode(array $options, array $headers, $stream): array
 304    {
 305        // Automatically decode responses when instructed.
 306        if (isset($options['decode_content']) && $options['decode_content'] !== false) {
 307            $normalizedKeys = Utils::normalizeHeaderKeys($headers);
 308            if (isset($normalizedKeys['content-encoding'])) {
 309                $encoding = $headers[$normalizedKeys['content-encoding']];
 310                if ($encoding[0] === 'gzip' || $encoding[0] === 'deflate') {
 311                    $stream = new Psr7\InflateStream(Psr7\Utils::streamFor($stream));
 312                    $headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
 313
 314                    // Remove content-encoding header
 315                    unset($headers[$normalizedKeys['content-encoding']]);
 316
 317                    // The decoded length cannot be known without inflating the
 318                    // stream, so keep the original length for inspection and
 319                    // drop the now-unknown Content-Length header.
 320                    if (isset($normalizedKeys['content-length'])) {
 321                        $headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
 322                        unset($headers[$normalizedKeys['content-length']]);
 323                    }
 324                }
 325            }
 326        }
 327
 328        return [$stream, $headers];
 329    }
 330
 331    /**
 332     * Drains the source stream into the "sink" client option.
 333     *
 334     * @param string $contentLength Header specifying the amount of
 335     *                              data to read.
 336     *
 337     * @throws \RuntimeException when the sink option is invalid.
 338     */
 339    private function drain(StreamInterface $source, StreamInterface $sink, string $contentLength): StreamInterface
 340    {
 341        // If a content-length header is provided, then stop reading once
 342        // that number of bytes has been read. This can prevent infinitely
 343        // reading from a stream when dealing with servers that do not honor
 344        // Connection: Close headers.
 345        Psr7\Utils::copyToStream(
 346            $source,
 347            $sink,
 348            (\strlen($contentLength) > 0 && (int) $contentLength > 0) ? (int) $contentLength : -1
 349        );
 350
 351        $sink->seek(0);
 352        $source->close();
 353
 354        return $sink;
 355    }
 356
 357    /**
 358     * Create a resource and check to ensure it was created successfully
 359     *
 360     * @param callable $callback Callable that returns stream resource
 361     *
 362     * @return resource
 363     *
 364     * @throws \RuntimeException on error
 365     */
 366    private function createResource(callable $callback)
 367    {
 368        $errors = [];
 369        \set_error_handler(static function ($_, $msg, $file, $line) use (&$errors): bool {
 370            $errors[] = [
 371                'message' => $msg,
 372                'file' => $file,
 373                'line' => $line,
 374            ];
 375
 376            return true;
 377        });
 378
 379        try {
 380            $resource = $callback();
 381        } finally {
 382            \restore_error_handler();
 383        }
 384
 385        if (!$resource) {
 386            $message = 'Error creating resource: ';
 387            foreach ($errors as $err) {
 388                foreach ($err as $key => $value) {
 389                    $message .= "[$key] $value".\PHP_EOL;
 390                }
 391            }
 392            throw new \RuntimeException(\trim($message, " \n\r\t\0\x0B"));
 393        }
 394
 395        return $resource;
 396    }
 397
 398    /**
 399     * @return resource
 400     */
 401    private function createStream(RequestInterface $request, array $options)
 402    {
 403        static $methods;
 404        if (!$methods) {
 405            $methods = \array_flip(\get_class_methods(__CLASS__));
 406        }
 407
 408        $uri = $request->getUri();
 409        $scheme = $uri->getScheme();
 410        if ($scheme === '') {
 411            throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
 412        }
 413
 414        if (!\in_array($scheme, ['http', 'https'], true)) {
 415            throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
 416        }
 417
 418        $protocols = Utils::normalizeProtocols($options['protocols'] ?? ['http', 'https']);
 419        if (!\in_array($scheme, $protocols, true)) {
 420            throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $request);
 421        }
 422
 423        if ($uri->getHost() === '') {
 424            throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
 425        }
 426
 427        HostValidator::assertRequestHost($request);
 428
 429        // HTTP/1.1 streams using the PHP stream wrapper require a
 430        // Connection: close header
 431        if ($request->getProtocolVersion() === '1.1'
 432            && !$request->hasHeader('Connection')
 433        ) {
 434            $request = $request->withHeader('Connection', 'close');
 435        }
 436
 437        // Ensure SSL is verified by default
 438        if (!isset($options['verify'])) {
 439            $options['verify'] = true;
 440        }
 441
 442        $params = [];
 443        $context = $this->getDefaultContext($request);
 444
 445        if (isset($options['on_headers']) && !\is_callable($options['on_headers'])) {
 446            throw new \InvalidArgumentException('on_headers must be callable');
 447        }
 448
 449        self::assertTlsVersionRangeForOptions($options);
 450
 451        $proxyAuthorizationAdded = false;
 452        if (!empty($options)) {
 453            foreach ($options as $key => $value) {
 454                $method = "add_{$key}";
 455                if (isset($methods[$method])) {
 456                    if ($method === 'add_proxy') {
 457                        $proxyAuthorizationAdded = $this->add_proxy($request, $context, $value, $params);
 458
 459                        continue;
 460                    }
 461
 462                    $this->{$method}($request, $context, $value, $params);
 463                }
 464            }
 465        }
 466
 467        if (isset($options['stream_context'])) {
 468            if (!\is_array($options['stream_context'])) {
 469                throw new \InvalidArgumentException('stream_context must be an array');
 470            }
 471            if (
 472                $proxyAuthorizationAdded
 473                && isset($options['stream_context']['http'])
 474                && \is_array($options['stream_context']['http'])
 475                && \array_key_exists('proxy', $options['stream_context']['http'])
 476            ) {
 477                throw new \InvalidArgumentException('stream_context.http.proxy cannot override a proxy after the stream handler has generated a Proxy-Authorization header; configure the final proxy with the "proxy" request option.');
 478            }
 479            self::triggerConflictingStreamContextOptionDeprecations($options['stream_context']);
 480            self::triggerUnsupportedStreamContextOptionDeprecations($options['stream_context']);
 481            $context = \array_replace_recursive($context, $options['stream_context']);
 482        }
 483
 484        // Microsoft NTLM authentication only supported with curl handler
 485        if (isset($options['auth'][2]) && 'ntlm' === $options['auth'][2]) {
 486            throw new \InvalidArgumentException('Microsoft NTLM authentication only supported with curl handler');
 487        }
 488
 489        $uri = $this->resolveHost($request, $options);
 490
 491        $contextResource = $this->createResource(
 492            static function () use ($context, $params) {
 493                return \stream_context_create($context, $params);
 494            }
 495        );
 496
 497        return $this->createResource(
 498            function () use ($uri, $contextResource, $context, $options, $request) {
 499                $resource = @\fopen((string) $uri, 'r', false, $contextResource);
 500
 501                if (false === $resource) {
 502                    throw new ConnectException(sprintf('Connection refused for URI %s', Psr7\Utils::redactUserInfo($uri)), $request, null, $context);
 503                }
 504
 505                if (isset($options['read_timeout'])) {
 506                    $readTimeout = $options['read_timeout'];
 507                    $sec = (int) $readTimeout;
 508                    $usec = ($readTimeout - $sec) * 100000;
 509                    \stream_set_timeout($resource, $sec, $usec);
 510                }
 511
 512                return $resource;
 513            }
 514        );
 515    }
 516
 517    private function resolveHost(RequestInterface $request, array $options): UriInterface
 518    {
 519        $uri = $request->getUri();
 520
 521        $host = $uri->getHost();
 522
 523        // Fold a numeric IPv4 spelling to the dotted quad libcurl connects
 524        // to, rather than leaving it to the platform resolver: macOS reads
 525        // the zero-padded 0177 as decimal 177 where glibc, musl and FreeBSD
 526        // read octal 127. The Host header is serialized from the request and
 527        // stays as written; the TLS peer name follows the same fold.
 528        $canonicalHost = self::canonicalConnectionHost($host);
 529        if ($canonicalHost !== $host) {
 530            $uri = $uri->withHost($canonicalHost);
 531            $host = $canonicalHost;
 532        }
 533
 534        $hostForIpCheck = $host !== '' && $host[0] === '[' && \substr($host, -1) === ']'
 535            ? \substr($host, 1, -1)
 536            : $host;
 537        if (isset($options['force_ip_resolve']) && !\filter_var($hostForIpCheck, \FILTER_VALIDATE_IP)) {
 538            if ('v4' === $options['force_ip_resolve']) {
 539                $records = \dns_get_record($uri->getHost(), \DNS_A);
 540                if (false === $records || !isset($records[0]['ip'])) {
 541                    throw new ConnectException(\sprintf("Could not resolve IPv4 address for host '%s'", $uri->getHost()), $request);
 542                }
 543
 544                return $uri->withHost($records[0]['ip']);
 545            }
 546            if ('v6' === $options['force_ip_resolve']) {
 547                $records = \dns_get_record($uri->getHost(), \DNS_AAAA);
 548                if (false === $records || !isset($records[0]['ipv6'])) {
 549                    throw new ConnectException(\sprintf("Could not resolve IPv6 address for host '%s'", $uri->getHost()), $request);
 550                }
 551
 552                return $uri->withHost('['.$records[0]['ipv6'].']');
 553            }
 554        }
 555
 556        return $uri;
 557    }
 558
 559    /**
 560     * Returns a numeric IPv4 spelling folded to the dotted quad libcurl's
 561     * ipv4_normalize() produces, and every other host unchanged.
 562     */
 563    private static function canonicalConnectionHost(string $host): string
 564    {
 565        $binary = self::numericIpv4ToBinary($host);
 566        if ($binary === null) {
 567            return $host;
 568        }
 569
 570        return (string) \inet_ntop($binary);
 571    }
 572
 573    /**
 574     * Returns the four-byte binary form of a host that a transport reads as a
 575     * numeric IPv4 address, or null when it reads it as a name.
 576     *
 577     * The shape test is HostValidator::isNumericIpv4Host(); this method adds
 578     * the range checks that predicate omits: every part but the last must fit
 579     * one octet, and the last must fit the octets the earlier parts left. A
 580     * trailing root dot is not swallowed, unlike libcurl 8.21.0 and later,
 581     * because assertRequestHost() rejects that spelling first.
 582     */
 583    private static function numericIpv4ToBinary(string $host): ?string
 584    {
 585        if (!HostValidator::isNumericIpv4Host($host)) {
 586            return null;
 587        }
 588
 589        $values = [];
 590        foreach (\explode('.', $host) as $part) {
 591            $values[] = self::numericIpv4PartValue($part);
 592        }
 593
 594        // Every accepted value is a whole number no larger than 0xFFFFFFFF,
 595        // which a float holds exactly, so the arithmetic below is correct on a
 596        // 32-bit build too, where the widest part overflows an integer.
 597        $address = (float) \array_pop($values);
 598
 599        $packed = '';
 600        foreach ($values as $value) {
 601            if ($value > 255.0) {
 602                return null;
 603            }
 604
 605            $packed .= \chr((int) $value);
 606        }
 607
 608        $width = 4 - \count($values);
 609        if ($address >= 256.0 ** $width) {
 610            return null;
 611        }
 612
 613        for ($shift = $width - 1; $shift >= 0; --$shift) {
 614            $packed .= \chr((int) \fmod(\floor($address / 256.0 ** $shift), 256.0));
 615        }
 616
 617        return $packed;
 618    }
 619
 620    /**
 621     * Returns the value of one accepted part as a float, so a part filling
 622     * all four octets such as 2130706433 stays exact on every integer width.
 623     */
 624    private static function numericIpv4PartValue(string $part): float
 625    {
 626        if ($part[0] === '0' && isset($part[1]) && ($part[1] === 'x' || $part[1] === 'X')) {
 627            return self::digitsValue((string) \substr($part, 2), 16);
 628        }
 629
 630        if ($part[0] === '0') {
 631            return self::digitsValue($part, 8);
 632        }
 633
 634        return (float) $part;
 635    }
 636
 637    private static function digitsValue(string $digits, int $base): float
 638    {
 639        $value = 0.0;
 640        foreach (\str_split($digits) as $digit) {
 641            $value = $value * $base + \hexdec($digit);
 642            if ($value > 0xFFFFFFFF) {
 643                break;
 644            }
 645        }
 646
 647        return $value;
 648    }
 649
 650    private function getDefaultContext(RequestInterface $request): array
 651    {
 652        $headers = '';
 653        foreach ($request->getHeaders() as $name => $value) {
 654            // A first-class Proxy-Authorization header is proxy-scoped. Keep
 655            // it out of the origin context; add_proxy() adds one
 656            // validated canonical line only when Guzzle selects a proxy; PHP
 657            // extracts that line for CONNECT and removes it before sending the
 658            // tunneled origin request. The caselessEquals() helper is
 659            // locale-independent, unlike strcasecmp(), so a locale cannot
 660            // make this match miss and re-leak the credential.
 661            if (Psr7\Utils::caselessEquals((string) $name, 'Proxy-Authorization')) {
 662                continue;
 663            }
 664
 665            foreach ($value as $val) {
 666                $headers .= "$name: $val\r\n";
 667            }
 668        }
 669
 670        $context = [
 671            'http' => [
 672                'method' => $request->getMethod(),
 673                'header' => $headers,
 674                'protocol_version' => $request->getProtocolVersion(),
 675                'ignore_errors' => true,
 676                'follow_location' => 0,
 677            ],
 678            'ssl' => [
 679                'peer_name' => self::canonicalConnectionHost($request->getUri()->getHost()),
 680            ],
 681        ];
 682
 683        $body = (string) $request->getBody();
 684
 685        if ('' !== $body) {
 686            $context['http']['content'] = $body;
 687            // Prevent the HTTP handler from adding a Content-Type header.
 688            if (!$request->hasHeader('Content-Type')) {
 689                $context['http']['header'] .= "Content-Type:\r\n";
 690            }
 691        }
 692
 693        $context['http']['header'] = \rtrim($context['http']['header'], " \n\r\t\0\x0B");
 694
 695        return $context;
 696    }
 697
 698    private static function triggerUnsupportedRequestOptionDeprecations(RequestInterface $request, array $options): void
 699    {
 700        if (
 701            \array_key_exists('curl', $options)
 702            && $options['curl'] !== null
 703            && $options['curl'] !== []
 704            && !self::isCurlOptionGeneratedByAuth($options)
 705        ) {
 706            \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "curl" request option to the stream handler is deprecated; guzzlehttp/guzzle 8.0 will reject this option because the stream handler ignores cURL options.');
 707        }
 708
 709        if (\array_key_exists('expect', $options) && $options['expect'] !== false && $request->hasHeader('Expect')) {
 710            \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "expect" request option to the stream handler is deprecated when it adds an Expect header; guzzlehttp/guzzle 8.0 will reject this option because the stream handler does not support Expect: 100-Continue.');
 711        }
 712    }
 713
 714    private static function triggerConflictingStreamContextOptionDeprecations(array $streamContext): void
 715    {
 716        $conflictingOptions = self::conflictingStreamContextOptions();
 717
 718        foreach ($streamContext as $wrapper => $contextOptions) {
 719            if (!\is_string($wrapper) || !isset($conflictingOptions[$wrapper]) || !\is_array($contextOptions)) {
 720                continue;
 721            }
 722
 723            foreach ($contextOptions as $option => $_) {
 724                if (!\is_string($option) || !\array_key_exists($option, $conflictingOptions[$wrapper])) {
 725                    continue;
 726                }
 727
 728                \trigger_deprecation(
 729                    'guzzlehttp/guzzle',
 730                    '7.12',
 731                    \sprintf(
 732                        'Passing stream_context.%s.%s in the "stream_context" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed request handling. Use %s instead.',
 733                        $wrapper,
 734                        $option,
 735                        $conflictingOptions[$wrapper][$option]
 736                    )
 737                );
 738            }
 739        }
 740    }
 741
 742    private static function triggerUnsupportedStreamContextOptionDeprecations(array $streamContext): void
 743    {
 744        $unsupportedOptions = self::unsupportedStreamContextOptions($streamContext);
 745        if ($unsupportedOptions === []) {
 746            return;
 747        }
 748
 749        \trigger_deprecation(
 750            'guzzlehttp/guzzle',
 751            '7.12',
 752            \sprintf(
 753                'Passing PHP stream context options outside the built-in stream handler allow-list to the "stream_context" request option is deprecated; guzzlehttp/guzzle 8.0 will reject stream context options outside the allow-list. Deprecated option%s: %s.',
 754                \count($unsupportedOptions) === 1 ? '' : 's',
 755                \implode(', ', $unsupportedOptions)
 756            )
 757        );
 758    }
 759
 760    /**
 761     * @return string[]
 762     */
 763    private static function unsupportedStreamContextOptions(array $streamContext): array
 764    {
 765        $supportedOptions = self::supportedStreamContextOptions();
 766        $conflictingOptions = self::conflictingStreamContextOptions();
 767        $unsupportedOptions = [];
 768
 769        foreach ($streamContext as $wrapper => $contextOptions) {
 770            if (!\is_string($wrapper) || !isset($supportedOptions[$wrapper])) {
 771                if (\is_array($contextOptions)) {
 772                    foreach ($contextOptions as $option => $_) {
 773                        if (\is_string($wrapper) && \is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) {
 774                            continue;
 775                        }
 776
 777                        $unsupportedOptions[] = \sprintf('stream_context.%s.%s', (string) $wrapper, (string) $option);
 778                    }
 779                } else {
 780                    $unsupportedOptions[] = \sprintf('stream_context.%s', (string) $wrapper);
 781                }
 782
 783                continue;
 784            }
 785
 786            if (!\is_array($contextOptions)) {
 787                $unsupportedOptions[] = \sprintf('stream_context.%s', $wrapper);
 788
 789                continue;
 790            }
 791
 792            foreach ($contextOptions as $option => $_) {
 793                if (\is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) {
 794                    continue;
 795                }
 796
 797                if (!\is_string($option) || !\array_key_exists($option, $supportedOptions[$wrapper])) {
 798                    $unsupportedOptions[] = \sprintf('stream_context.%s.%s', $wrapper, (string) $option);
 799                }
 800            }
 801        }
 802
 803        return $unsupportedOptions;
 804    }
 805
 806    /**
 807     * @return array<string, array<string, true>>
 808     */
 809    private static function supportedStreamContextOptions(): array
 810    {
 811        return [
 812            'http' => [
 813                'request_fulluri' => true,
 814            ],
 815            'socket' => [
 816                'bindto' => true,
 817                'tcp_nodelay' => true,
 818            ],
 819            'ssl' => [
 820                'SNI_enabled' => true,
 821                'capture_peer_cert' => true,
 822                'capture_peer_cert_chain' => true,
 823                'ciphers' => true,
 824                'disable_compression' => true,
 825                'no_ticket' => true,
 826                'peer_fingerprint' => true,
 827                'security_level' => true,
 828                'verify_depth' => true,
 829            ],
 830        ];
 831    }
 832
 833    /**
 834     * @return array<string, array<string, string>>
 835     */
 836    private static function conflictingStreamContextOptions(): array
 837    {
 838        return [
 839            'http' => [
 840                'content' => 'the request body',
 841                'follow_location' => 'the "allow_redirects" request option',
 842                'header' => 'the request headers',
 843                'max_redirects' => 'the "allow_redirects" request option',
 844                'method' => 'the request method',
 845                'protocol_version' => 'the request protocol version',
 846                'proxy' => 'the "proxy" request option',
 847                'timeout' => 'the "timeout" request option',
 848            ],
 849            'ssl' => [
 850                'allow_self_signed' => 'the "verify" request option',
 851                'cafile' => 'the "verify" request option',
 852                'capath' => 'the "verify" request option',
 853                'crypto_method' => 'the "crypto_method" request option',
 854                'local_cert' => 'the "cert" request option',
 855                'local_pk' => 'the "ssl_key" request option',
 856                'max_proto_version' => 'the "crypto_method_max" request option',
 857                'min_proto_version' => 'the "crypto_method" request option',
 858                'passphrase' => 'the "cert" or "ssl_key" request option',
 859                'peer_name' => 'the request URI',
 860                'verify_peer' => 'the "verify" request option',
 861                'verify_peer_name' => 'the "verify" request option',
 862            ],
 863        ];
 864    }
 865
 866    private function assertTransportSharingSupported(): void
 867    {
 868        if ($this->transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
 869            throw new \InvalidArgumentException('The "transport_sharing" option requires transport sharing, but the stream handler does not support it.');
 870        }
 871    }
 872
 873    private static function isCurlOptionGeneratedByAuth(array $options): bool
 874    {
 875        if (!isset($options['curl']) || !\is_array($options['curl']) || !isset($options['auth'][2]) || !\is_string($options['auth'][2])) {
 876            return false;
 877        }
 878
 879        if (!\defined('CURLOPT_HTTPAUTH') || !\defined('CURLOPT_USERPWD')) {
 880            return false;
 881        }
 882
 883        $type = Psr7\Utils::asciiToLower($options['auth'][2]);
 884        if ($type === 'digest') {
 885            $httpAuth = \defined('CURLAUTH_DIGEST') ? \constant('CURLAUTH_DIGEST') : null;
 886        } elseif ($type === 'ntlm') {
 887            $httpAuth = \defined('CURLAUTH_NTLM') ? \constant('CURLAUTH_NTLM') : null;
 888        } else {
 889            return false;
 890        }
 891
 892        return $httpAuth !== null
 893            && \count($options['curl']) === 2
 894            && isset($options['curl'][\CURLOPT_HTTPAUTH], $options['curl'][\CURLOPT_USERPWD])
 895            && $options['curl'][\CURLOPT_HTTPAUTH] === $httpAuth;
 896    }
 897
 898    /**
 899     * @param mixed $value as passed via Request transfer options.
 900     *
 901     * @return array{0: string, 1: string|null}
 902     */
 903    private static function normalizeTlsFileOption(string $option, $value): array
 904    {
 905        $passphrase = null;
 906
 907        if (\is_array($value)) {
 908            if (!isset($value[0]) || !\is_string($value[0])) {
 909                throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
 910            }
 911            if (isset($value[1])) {
 912                if (!\is_string($value[1])) {
 913                    throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
 914                }
 915                $passphrase = $value[1];
 916            }
 917            $value = $value[0];
 918        }
 919
 920        if (!\is_string($value)) {
 921            throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
 922        }
 923
 924        return [$value, $passphrase];
 925    }
 926
 927    private static function setTlsPassphrase(array &$options, ?string $passphrase, string $option): void
 928    {
 929        if ($passphrase === null) {
 930            return;
 931        }
 932
 933        if (isset($options['ssl']['passphrase']) && $options['ssl']['passphrase'] !== $passphrase) {
 934            throw new \InvalidArgumentException(\sprintf('Cannot use different passphrases for cert and ssl_key with the stream handler; %s conflicts with an existing TLS passphrase.', $option));
 935        }
 936
 937        $options['ssl']['passphrase'] = $passphrase;
 938    }
 939
 940    /**
 941     * @param mixed $value as passed via Request transfer options.
 942     */
 943    private static function assertStreamTlsType(string $option, $value): void
 944    {
 945        if (!\is_string($value) || $value === '') {
 946            throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
 947        }
 948
 949        if (Psr7\Utils::asciiToUpper($value) !== 'PEM') {
 950            throw new \InvalidArgumentException(\sprintf('The stream handler only supports "PEM" for the %s request option.', $option));
 951        }
 952    }
 953
 954    /**
 955     * @param mixed $value as passed via Request transfer options.
 956     */
 957    private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): bool
 958    {
 959        $uri = null;
 960
 961        if (!\is_array($value)) {
 962            $uri = $value;
 963        } else {
 964            $scheme = $request->getUri()->getScheme();
 965            if (isset($value[$scheme])) {
 966                if (
 967                    !isset($value['no'])
 968                    || !Utils::isUriInNoProxy($request->getUri(), $value['no'])
 969                ) {
 970                    $uri = $value[$scheme];
 971                }
 972            }
 973        }
 974
 975        if (!$uri) {
 976            return false;
 977        }
 978
 979        $parsed = $this->parse_proxy($uri);
 980
 981        // PHP extracts and removes only one Proxy-Authorization line for a
 982        // CONNECT tunnel. Serialize exactly one validated first-class value;
 983        // more than one could leave a credential in the tunneled origin
 984        // request. A first-class value, including an empty one, is
 985        // authoritative over Basic credentials embedded in the proxy URI.
 986        $managed = $request->getHeader('Proxy-Authorization');
 987        if (\count($managed) > 1) {
 988            throw new \InvalidArgumentException('The stream handler supports exactly one Proxy-Authorization request header value when a proxy is selected.');
 989        }
 990        if ($managed !== [] && \strpbrk($managed[0], "\r\n") !== false) {
 991            throw new \InvalidArgumentException('Proxy-Authorization request header values must not contain a carriage return or line feed.');
 992        }
 993
 994        $options['http']['proxy'] = $parsed['proxy'];
 995
 996        if (($managed !== [] || $parsed['auth']) && !isset($options['http']['header'])) {
 997            $options['http']['header'] = '';
 998        }
 999        if ($managed !== []) {
1000            $options['http']['header'] .= "\r\nProxy-Authorization: {$managed[0]}";
1001
1002            return true;
1003        } elseif ($parsed['auth']) {
1004            $options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
1005
1006            return true;
1007        }
1008
1009        return false;
1010    }
1011
1012    /**
1013     * Parses the given proxy URL to make it compatible with the format PHP's stream context expects.
1014     */
1015    private function parse_proxy(string $url): array
1016    {
1017        $parsed = \parse_url($url);
1018
1019        // parse_url() misreads scheme-less proxy authorities like
1020        // "user:pass@host"; re-parse only those forms as HTTP.
1021        $schemeLessAuthority = \strpos($url, '://') === false && \strncmp($url, '//', 2) !== 0;
1022        if ($schemeLessAuthority) {
1023            if (\is_array($parsed) && !isset($parsed['scheme']) && isset($parsed['host'], $parsed['port'])) {
1024                $parsed['scheme'] = 'http';
1025            } elseif (
1026                (!\is_array($parsed) || !isset($parsed['host']))
1027                && (\strpos($url, '@') !== false || \strncmp($url, '[', 1) === 0)
1028            ) {
1029                $parsed = \parse_url('http://'.$url);
1030            }
1031        }
1032
1033        if (\is_array($parsed) && isset($parsed['scheme']) && Psr7\Utils::caselessEquals($parsed['scheme'], 'http')) {
1034            if (isset($parsed['host'], $parsed['port'])) {
1035                $user = $parsed['user'] ?? '';
1036                $pass = $parsed['pass'] ?? '';
1037                $auth = ($user !== '' || $pass !== '') ? 'Basic '.\base64_encode("{$user}:{$pass}") : null;
1038
1039                return [
1040                    'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}",
1041                    'auth' => $auth,
1042                ];
1043            }
1044        }
1045
1046        // Return proxy as-is.
1047        return [
1048            'proxy' => $url,
1049            'auth' => null,
1050        ];
1051    }
1052
1053    /**
1054     * @param mixed $value as passed via Request transfer options.
1055     */
1056    private function add_timeout(RequestInterface $request, array &$options, $value, array &$params): void
1057    {
1058        if ($value > 0) {
1059            $options['http']['timeout'] = $value;
1060        }
1061    }
1062
1063    /**
1064     * @param mixed $value as passed via Request transfer options.
1065     */
1066    private function add_crypto_method(RequestInterface $request, array &$options, $value, array &$params): void
1067    {
1068        if (
1069            $value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT
1070            || $value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT
1071            || $value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
1072            || (defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT)
1073        ) {
1074            $options['http']['crypto_method'] = $value;
1075
1076            return;
1077        }
1078
1079        throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
1080    }
1081
1082    /**
1083     * @param mixed $value as passed via Request transfer options.
1084     */
1085    private function add_crypto_method_max(RequestInterface $request, array &$options, $value, array &$params): void
1086    {
1087        $options['ssl']['max_proto_version'] = TlsVersion::streamProtocolVersion('crypto_method_max', $value);
1088    }
1089
1090    private static function assertTlsVersionRangeForOptions(array $options): void
1091    {
1092        if (!isset($options['crypto_method_max'])) {
1093            return;
1094        }
1095
1096        TlsVersion::assertRange(
1097            $options['crypto_method'] ?? null,
1098            $options['crypto_method_max']
1099        );
1100    }
1101
1102    /**
1103     * @param mixed $value as passed via Request transfer options.
1104     */
1105    private function add_verify(RequestInterface $request, array &$options, $value, array &$params): void
1106    {
1107        if ($value === false) {
1108            $options['ssl']['verify_peer'] = false;
1109            $options['ssl']['verify_peer_name'] = false;
1110
1111            return;
1112        }
1113
1114        if (\is_string($value)) {
1115            $options['ssl']['cafile'] = $value;
1116            if (!\file_exists($value)) {
1117                throw new \RuntimeException("SSL CA bundle not found: $value");
1118            }
1119        } elseif ($value !== true) {
1120            throw new \InvalidArgumentException('Invalid verify request option');
1121        }
1122
1123        $options['ssl']['verify_peer'] = true;
1124        $options['ssl']['verify_peer_name'] = true;
1125        $options['ssl']['allow_self_signed'] = false;
1126    }
1127
1128    /**
1129     * @param mixed $value as passed via Request transfer options.
1130     */
1131    private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void
1132    {
1133        [$value, $passphrase] = self::normalizeTlsFileOption('cert', $value);
1134
1135        if (!\file_exists($value)) {
1136            throw new \RuntimeException("SSL certificate not found: {$value}");
1137        }
1138
1139        self::setTlsPassphrase($options, $passphrase, 'cert');
1140        $options['ssl']['local_cert'] = $value;
1141    }
1142
1143    /**
1144     * @param mixed $value as passed via Request transfer options.
1145     */
1146    private function add_cert_type(RequestInterface $request, array &$options, $value, array &$params): void
1147    {
1148        self::assertStreamTlsType('cert_type', $value);
1149    }
1150
1151    /**
1152     * @param mixed $value as passed via Request transfer options.
1153     */
1154    private function add_ssl_key(RequestInterface $request, array &$options, $value, array &$params): void
1155    {
1156        [$value, $passphrase] = self::normalizeTlsFileOption('ssl_key', $value);
1157
1158        if (!\file_exists($value)) {
1159            throw new \RuntimeException("SSL private key not found: {$value}");
1160        }
1161
1162        self::setTlsPassphrase($options, $passphrase, 'ssl_key');
1163        $options['ssl']['local_pk'] = $value;
1164    }
1165
1166    /**
1167     * @param mixed $value as passed via Request transfer options.
1168     */
1169    private function add_ssl_key_type(RequestInterface $request, array &$options, $value, array &$params): void
1170    {
1171        self::assertStreamTlsType('ssl_key_type', $value);
1172    }
1173
1174    /**
1175     * @param mixed $value as passed via Request transfer options.
1176     */
1177    private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void
1178    {
1179        if (!\is_callable($value)) {
1180            throw new \InvalidArgumentException('progress client option must be callable');
1181        }
1182
1183        self::addNotification(
1184            $params,
1185            static function ($code, $a, $b, $c, $transferred, $total) use ($value) {
1186                if ($code == \STREAM_NOTIFY_PROGRESS) {
1187                    // The upload progress cannot be determined. Use 0 for cURL compatibility:
1188                    // https://curl.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html
1189                    $value($total, $transferred, 0, 0);
1190                }
1191            }
1192        );
1193    }
1194
1195    /**
1196     * @param mixed $value as passed via Request transfer options.
1197     */
1198    private function add_debug(RequestInterface $request, array &$options, $value, array &$params): void
1199    {
1200        if ($value === false) {
1201            return;
1202        }
1203
1204        static $map = [
1205            \STREAM_NOTIFY_CONNECT => 'CONNECT',
1206            \STREAM_NOTIFY_AUTH_REQUIRED => 'AUTH_REQUIRED',
1207            \STREAM_NOTIFY_AUTH_RESULT => 'AUTH_RESULT',
1208            \STREAM_NOTIFY_MIME_TYPE_IS => 'MIME_TYPE_IS',
1209            \STREAM_NOTIFY_FILE_SIZE_IS => 'FILE_SIZE_IS',
1210            \STREAM_NOTIFY_REDIRECTED => 'REDIRECTED',
1211            \STREAM_NOTIFY_PROGRESS => 'PROGRESS',
1212            \STREAM_NOTIFY_FAILURE => 'FAILURE',
1213            \STREAM_NOTIFY_COMPLETED => 'COMPLETED',
1214            \STREAM_NOTIFY_RESOLVE => 'RESOLVE',
1215        ];
1216        static $args = ['severity', 'message', 'message_code', 'bytes_transferred', 'bytes_max'];
1217
1218        $value = Utils::debugResource($value);
1219        $ident = $request->getMethod().' '.$request->getUri()->withFragment('');
1220        self::addNotification(
1221            $params,
1222            static function (int $code, ...$passed) use ($ident, $value, $map, $args): void {
1223                \fprintf($value, '<%s> [%s] ', $ident, $map[$code]);
1224                foreach (\array_filter($passed) as $i => $v) {
1225                    \fwrite($value, $args[$i].': "'.$v.'" ');
1226                }
1227                \fwrite($value, "\n");
1228            }
1229        );
1230    }
1231
1232    private static function addNotification(array &$params, callable $notify): void
1233    {
1234        // Wrap the existing function if needed.
1235        if (!isset($params['notification'])) {
1236            $params['notification'] = $notify;
1237        } else {
1238            $params['notification'] = self::callArray([
1239                $params['notification'],
1240                $notify,
1241            ]);
1242        }
1243    }
1244
1245    private static function callArray(array $functions): callable
1246    {
1247        return static function (...$args) use ($functions) {
1248            foreach ($functions as $fn) {
1249                $fn(...$args);
1250            }
1251        };
1252    }
1253}