This commit is contained in:
Javier Casares 2026-07-18 13:29:38 +00:00
commit 916d7845be
27 changed files with 6861 additions and 6907 deletions

File diff suppressed because it is too large Load diff

View file

@ -1,94 +0,0 @@
![Guzzle](.github/logo.png?raw=true)
# Guzzle, PHP HTTP client
[![Latest Version](https://img.shields.io/github/release/guzzle/guzzle.svg?style=flat-square)](https://github.com/guzzle/guzzle/releases)
[![Build Status](https://img.shields.io/github/actions/workflow/status/guzzle/guzzle/ci.yml?label=ci%20build&style=flat-square)](https://github.com/guzzle/guzzle/actions?query=workflow%3ACI)
[![Total Downloads](https://img.shields.io/packagist/dt/guzzlehttp/guzzle.svg?style=flat-square)](https://packagist.org/packages/guzzlehttp/guzzle)
Guzzle is a PHP HTTP client that makes it easy to send HTTP requests and
trivial to integrate with web services.
- Simple interface for building query strings, POST requests, streaming large
uploads, streaming large downloads, using HTTP cookies, uploading JSON data,
etc...
- Can send both synchronous and asynchronous requests using the same interface.
- Uses PSR-7 interfaces for requests, responses, and streams. This allows you
to utilize other PSR-7 compatible libraries with Guzzle.
- Supports PSR-18 allowing interoperability between other PSR-18 HTTP Clients.
- Abstracts away the underlying HTTP transport, allowing you to write
environment and transport agnostic code; i.e., no hard dependency on cURL,
PHP streams, sockets, or non-blocking event loops.
- Middleware system allows you to augment and compose client behavior.
```php
$client = new \GuzzleHttp\Client();
$response = $client->request('GET', 'https://api.github.com/repos/guzzle/guzzle');
echo $response->getStatusCode(); // 200
echo $response->getHeaderLine('content-type'); // 'application/json; charset=utf8'
echo $response->getBody(); // '{"id": 1420053, "name": "guzzle", ...}'
// Send an asynchronous request.
$request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
$promise = $client->sendAsync($request)->then(function ($response) {
echo 'I completed! ' . $response->getBody();
});
$promise->wait();
```
## Help and docs
We use GitHub issues only to discuss bugs and new features. For support please refer to:
- [Documentation](docs/index.md)
- [Stack Overflow](https://stackoverflow.com/questions/tagged/guzzle)
- [#guzzle](https://app.slack.com/client/T0D2S9JCT/CE6UAAKL4) channel on [PHP-HTTP Slack](https://slack.httplug.io/)
- [Gitter](https://gitter.im/guzzle/guzzle)
## Installing Guzzle
The recommended way to install Guzzle is through
[Composer](https://getcomposer.org/).
```bash
composer require guzzlehttp/guzzle
```
## Version Guidance
| Version | Status | Packagist | Namespace | Repo | Docs | PSR-7 | PHP Version |
|---------|---------------------|---------------------|--------------|---------------------|---------------------|-------|--------------|
| 3.x | EOL (2016-10-31) | `guzzle/guzzle` | `Guzzle` | [v3][guzzle-3-repo] | [v3][guzzle-3-docs] | No | >=5.3.3,<7.0 |
| 4.x | EOL (2016-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v4][guzzle-4-repo] | N/A | No | >=5.4,<7.0 |
| 5.x | EOL (2019-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v5][guzzle-5-repo] | [v5][guzzle-5-docs] | No | >=5.4,<7.4 |
| 6.x | EOL (2023-10-31) | `guzzlehttp/guzzle` | `GuzzleHttp` | [v6][guzzle-6-repo] | [v6][guzzle-6-docs] | Yes | >=5.5,<8.0 |
| 7.x | Latest | `guzzlehttp/guzzle` | `GuzzleHttp` | [v7][guzzle-7-repo] | [v7][guzzle-7-docs] | Yes | >=7.2.5,<8.6 |
[guzzle-3-repo]: https://github.com/guzzle/guzzle3
[guzzle-4-repo]: https://github.com/guzzle/guzzle/tree/4.x
[guzzle-5-repo]: https://github.com/guzzle/guzzle/tree/5.3
[guzzle-6-repo]: https://github.com/guzzle/guzzle/tree/6.5
[guzzle-7-repo]: https://github.com/guzzle/guzzle/tree/7.11
[guzzle-3-docs]: https://github.com/guzzle/guzzle3/tree/master/docs
[guzzle-5-docs]: https://github.com/guzzle/guzzle/tree/5.3/docs
[guzzle-6-docs]: https://github.com/guzzle/guzzle/tree/6.5/docs
[guzzle-7-docs]: https://github.com/guzzle/guzzle/blob/7.11/docs/index.md
## Security
If you discover a security vulnerability within this package, please send an email to security@tidelift.com. All security vulnerabilities will be promptly addressed. Please do not disclose security-related issues publicly until a fix has been announced. Please see [Security Policy](https://github.com/guzzle/guzzle/security/policy) for more information.
## License
Guzzle is made available under the MIT License (MIT). Please see [License File](LICENSE) for more information.
## For Enterprise
Available as part of the Tidelift Subscription
The maintainers of Guzzle and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-guzzlehttp-guzzle?utm_source=packagist-guzzlehttp-guzzle&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)

File diff suppressed because it is too large Load diff

View file

@ -1,6 +0,0 @@
{
"name": "guzzle",
"lockfileVersion": 3,
"requires": true,
"packages": {}
}

View file

@ -3,9 +3,11 @@
namespace GuzzleHttp;
use GuzzleHttp\Cookie\CookieJar;
use GuzzleHttp\Cookie\CookieJarInterface;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Handler\CurlShareHandleState;
use GuzzleHttp\Handler\CurlVersion;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use Psr\Http\Message\RequestInterface;
@ -52,6 +54,20 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
* into relative URIs. Can be a string or instance of UriInterface.
* - transport_sharing: (string|null) Transport sharing mode for the
* default handler. Accepts TransportSharing::* or null. Defaults to null.
* - max_host_connections: (int|null) Maximum concurrent connections per
* host, applied by the default CurlMultiHandler. The default stream
* fallback receives the cap as a marker only: it rejects enabled
* response streaming ("stream" => true) and does not limit overlapping
* buffered calls.
* - max_total_connections: (int|null) Maximum concurrent connections
* overall, applied by the default CurlMultiHandler. The default stream
* fallback receives the cap as a marker only: it rejects enabled
* response streaming ("stream" => true) and does not limit overlapping
* buffered calls.
* - multiplex: (string|null) Multiplexing::NONE to disable multiplexing on
* the default CurlMultiHandler; the value also becomes the default
* "multiplex" request option. Other Multiplexing::* values act as the
* default request option only.
* - **: any request option
*
* @param array $config Client configuration settings.
@ -60,16 +76,41 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
*/
public function __construct(array $config = [])
{
$handlerOptions = [];
foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
if (\array_key_exists($capOption, $config)) {
if ($config[$capOption] !== null) {
$handlerOptions[$capOption] = $config[$capOption];
}
unset($config[$capOption]);
}
}
// Deliberately not unset: the value also becomes the default
// "multiplex" request option, which the configured handler accepts.
$handlerMultiplex = ($config['multiplex'] ?? null) === Multiplexing::NONE;
$transportSharing = \array_key_exists('transport_sharing', $config) ? $config['transport_sharing'] : null;
$transportSharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
unset($config['transport_sharing']);
if (!isset($config['handler'])) {
$config['handler'] = $transportSharingMode === TransportSharing::NONE
if ($transportSharingMode !== TransportSharing::NONE) {
$handlerOptions['transport_sharing'] = $transportSharingMode;
}
if ($handlerMultiplex) {
$handlerOptions['multiplex'] = Multiplexing::NONE;
}
$config['handler'] = $handlerOptions === []
? HandlerStack::create()
: HandlerStack::create(Utils::chooseHandler(['transport_sharing' => $transportSharingMode]));
: HandlerStack::create(Utils::chooseHandler($handlerOptions));
} elseif (!\is_callable($config['handler'])) {
throw new InvalidArgumentException('handler must be a callable');
} elseif ($handlerOptions !== []) {
throw new InvalidArgumentException('The "max_host_connections" and "max_total_connections" client options require Guzzle to create the default handler. Configure the options on the CurlMultiHandler constructor to apply numeric connection caps, or on the StreamHandler constructor to reject enabled response streaming, when providing a custom handler.');
} elseif ($transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
throw new InvalidArgumentException('The "transport_sharing" client option can only require sharing when Guzzle creates the default handler. Configure the "transport_sharing" option on CurlHandler or CurlMultiHandler when providing a custom cURL handler.');
}
@ -92,6 +133,8 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
*/
public function __call($method, $args)
{
\trigger_deprecation('guzzlehttp/guzzle', '7.1', '%s::%s() is deprecated and will be removed in 8.0.', __CLASS__, __FUNCTION__);
if (\count($args) < 1) {
throw new InvalidArgumentException('Magic request methods require a URI and optional options array');
}
@ -101,7 +144,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
$isAsync = \substr($method, -5) === 'Async';
$method = $isAsync ? \substr($method, 0, -5) : $method;
$method = \strtoupper($method);
$method = Psr7\Utils::asciiToUpper($method);
return $isAsync
? $this->requestAsync($method, $uri, $opts)
@ -168,7 +211,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
*/
public function requestAsync(string $method, $uri = '', array $options = []): PromiseInterface
{
$normalizedMethod = \strtoupper($method);
$normalizedMethod = Psr7\Utils::asciiToUpper($method);
if ($method !== $normalizedMethod) {
\trigger_deprecation(
'guzzlehttp/guzzle',
@ -192,6 +235,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
if (\is_array($body)) {
throw $this->invalidBody();
}
$body = self::createBodyStream($body);
$request = new Psr7\Request($method, $uri, $headers, $body, $version);
// Remove the option so that they are not doubly-applied.
unset($options['headers'], $options['body'], $options['version']);
@ -214,7 +258,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
*/
public function request(string $method, $uri = '', array $options = []): ResponseInterface
{
$normalizedMethod = \strtoupper($method);
$normalizedMethod = Psr7\Utils::asciiToUpper($method);
if ($method !== $normalizedMethod) {
\trigger_deprecation(
'guzzlehttp/guzzle',
@ -258,7 +302,11 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
$uri = Utils::idnUriConvert($uri, $idnOptions);
}
return $uri->getScheme() === '' && $uri->getHost() !== '' ? $uri->withScheme('http') : $uri;
if ($uri->getScheme() === '' && $uri->getHost() !== '') {
$uri = $uri->withScheme('http');
}
return $uri;
}
/**
@ -307,7 +355,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
// Add the User-Agent header if one was not already set.
$hasUserAgent = false;
foreach (\array_keys($this->config['headers']) as $name) {
if (\strtolower((string) $name) === 'user-agent') {
if (Psr7\Utils::asciiToLower((string) $name) === 'user-agent') {
$hasUserAgent = true;
break;
}
@ -331,6 +379,8 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
*/
private function prepareDefaults(array $options): array
{
self::warnAboutRequestLevelHandler($options);
$defaults = $this->config;
if (!empty($defaults['headers'])) {
@ -363,7 +413,178 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
self::warnAboutInvalidRequestOptionTypes($result);
return $result;
return self::normalizeDeprecatedRequestOptionValues($result);
}
/**
* Normalize values that guzzlehttp/guzzle 8.0 rejects only after the
* corresponding 7.x deprecation has already been emitted.
*
* @param array<string, mixed> $options
*
* @return array<string, mixed>
*/
private static function normalizeDeprecatedRequestOptionValues(array $options): array
{
self::normalizeDeprecatedAuthOptionValues($options);
self::normalizeDeprecatedTlsFileOptionValues($options, 'cert');
self::normalizeDeprecatedTlsFileOptionValues($options, 'ssl_key');
self::normalizeDeprecatedStringOptionValues($options);
self::normalizeDeprecatedNumericOptionValues($options);
self::normalizeDeprecatedIntegerOptionValues($options);
return $options;
}
/**
* @param mixed $value
*/
private static function canStringifyDeprecatedValue($value): bool
{
return $value === null
|| \is_scalar($value)
|| (\is_object($value) && \method_exists($value, '__toString'));
}
/**
* @param mixed $value
*/
private static function stringifyDeprecatedValue($value): string
{
if (\is_float($value) && !\is_finite($value)) {
return \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
}
if ($value === null) {
return '';
}
if (\is_scalar($value)) {
return (string) $value;
}
if (\is_object($value) && \method_exists($value, '__toString')) {
return $value->__toString();
}
throw new \LogicException('Value is not stringable.');
}
/**
* @param array<string, mixed> $options
*/
private static function normalizeDeprecatedAuthOptionValues(array &$options): void
{
if (!isset($options['auth']) || !\is_array($options['auth']) || $options['auth'] === []) {
return;
}
foreach ([0, 1] as $index) {
if (
\array_key_exists($index, $options['auth'])
&& !\is_string($options['auth'][$index])
&& self::canStringifyDeprecatedValue($options['auth'][$index])
) {
$options['auth'][$index] = self::stringifyDeprecatedValue($options['auth'][$index]);
}
}
if (
\array_key_exists(2, $options['auth'])
&& $options['auth'][2] !== null
&& !\is_string($options['auth'][2])
&& self::canStringifyDeprecatedValue($options['auth'][2])
) {
$options['auth'][2] = self::stringifyDeprecatedValue($options['auth'][2]);
}
}
/**
* @param array<string, mixed> $options
*/
private static function normalizeDeprecatedTlsFileOptionValues(array &$options, string $option): void
{
if (!isset($options[$option]) || !\is_array($options[$option])) {
return;
}
foreach ([0, 1] as $index) {
if (
\array_key_exists($index, $options[$option])
&& $options[$option][$index] !== null
&& !\is_string($options[$option][$index])
&& self::canStringifyDeprecatedValue($options[$option][$index])
) {
$options[$option][$index] = self::stringifyDeprecatedValue($options[$option][$index]);
}
}
}
/**
* @param array<string, mixed> $options
*/
private static function normalizeDeprecatedStringOptionValues(array &$options): void
{
foreach (['cert_type', 'force_ip_resolve', 'ssl_key_type'] as $option) {
if (
\array_key_exists($option, $options)
&& !\is_string($options[$option])
&& self::canStringifyDeprecatedValue($options[$option])
) {
$options[$option] = self::stringifyDeprecatedValue($options[$option]);
}
}
}
/**
* @param array<string, mixed> $options
*/
private static function normalizeDeprecatedNumericOptionValues(array &$options): void
{
foreach (['connect_timeout', 'delay', 'read_timeout', 'timeout'] as $option) {
if (
\array_key_exists($option, $options)
&& \is_string($options[$option])
&& \is_numeric($options[$option])
) {
$options[$option] = $options[$option] + 0;
}
}
}
/**
* @param array<string, mixed> $options
*/
private static function normalizeDeprecatedIntegerOptionValues(array &$options): void
{
foreach (['crypto_method', 'crypto_method_max', 'retries'] as $option) {
if (!\array_key_exists($option, $options)) {
continue;
}
if (\is_string($options[$option]) && \preg_match('/^-?\d+$/D', $options[$option]) === 1) {
$options[$option] = (int) $options[$option];
} elseif (
\is_float($options[$option])
&& \is_finite($options[$option])
&& $options[$option] === (float) (int) $options[$option]
) {
$options[$option] = (int) $options[$option];
}
}
}
private static function warnAboutRequestLevelHandler(array $options): void
{
if (!\array_key_exists('handler', $options)) {
return;
}
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.12',
'Passing the "handler" request option is deprecated; guzzlehttp/guzzle 8.0 will ignore request-level handlers. Configure the handler when creating the Client, or use a separate Client instance for requests that need a different handler.'
);
}
private static function warnAboutInvalidRequestOptionTypes(array $options): void
@ -374,6 +595,8 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
if (isset($options['allow_redirects']) && \is_array($options['allow_redirects'])) {
self::warnAboutInvalidAllowRedirectsOptionTypes($options['allow_redirects']);
} elseif (isset($options['allow_redirects']) && !\is_bool($options['allow_redirects'])) {
self::warnInvalidRequestOptionType('allow_redirects', 'bool|array', $options['allow_redirects'], '7.13');
}
if (isset($options['auth'])) {
@ -388,9 +611,16 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
self::warnIfPresentAndNotString($options, 'cert_type');
self::warnIfPresentAndNotNumber($options, 'connect_timeout');
self::warnIfPresentAndNotInt($options, 'crypto_method');
self::warnIfPresentAndNotInt($options, 'crypto_method_max', null, '7.13');
self::warnIfPresentAndNotBoolOrResource($options, 'debug');
self::warnIfPresentAndNotBoolOrString($options, 'decode_content');
self::warnIfPresentAndNotNumber($options, 'delay');
if (isset($options['delay']) && \is_numeric($options['delay'])) {
$delay = (float) $options['delay'];
if (!\is_finite($delay) || $delay < 0.0) {
self::warnInvalidRequestOptionType('delay', 'finite int|float greater than or equal to 0', $options['delay'], '7.13');
}
}
self::warnIfPresentAndNotBoolOrInt($options, 'expect');
if (isset($options['form_params'])) {
@ -401,6 +631,15 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
self::warnInvalidRequestOptionType('force_ip_resolve', 'string', $options['force_ip_resolve']);
}
if (
isset($options['force_ip_resolve'])
&& \is_string($options['force_ip_resolve'])
&& $options['force_ip_resolve'] !== 'v4'
&& $options['force_ip_resolve'] !== 'v6'
) {
self::warnInvalidRequestOptionType('force_ip_resolve', '"v4"|"v6"', $options['force_ip_resolve'], '7.13');
}
if (isset($options['headers'])) {
self::warnAboutInvalidHeaderOptionTypes($options['headers']);
}
@ -413,8 +652,10 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
self::warnIfPresentAndNotCallable($options, 'on_headers');
self::warnIfPresentAndNotCallable($options, 'on_stats');
self::warnIfPresentAndNotCallable($options, 'on_trailers', null, '7.14');
self::warnIfPresentAndNotCallable($options, 'progress');
self::warnIfPresentAndNotStringArray($options, 'protocols', true);
self::warnAboutInvalidProtocolValues($options, 'protocols');
self::warnAboutInvalidProxyOptionTypes($options);
self::warnIfPresentAndNotNumber($options, 'read_timeout');
@ -437,6 +678,15 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
if (isset($options['cookies']) && $options['cookies'] === true) {
self::warnInvalidRequestOptionType('cookies', 'false|CookieJarInterface', $options['cookies']);
}
if (
isset($options['cookies'])
&& $options['cookies'] !== false
&& $options['cookies'] !== true
&& !($options['cookies'] instanceof CookieJarInterface)
) {
self::warnInvalidRequestOptionType('cookies', 'false|CookieJarInterface', $options['cookies'], '7.13');
}
}
private static function warnAboutInvalidAllowRedirectsOptionTypes(array $allowRedirects): void
@ -445,6 +695,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
self::warnIfPresentAndNotBool($allowRedirects, 'strict', 'allow_redirects.strict');
self::warnIfPresentAndNotBool($allowRedirects, 'referer', 'allow_redirects.referer');
self::warnIfPresentAndNotStringArray($allowRedirects, 'protocols', true, 'allow_redirects.protocols');
self::warnAboutInvalidProtocolValues($allowRedirects, 'protocols', 'allow_redirects.protocols');
self::warnIfPresentAndNotCallable($allowRedirects, 'on_redirect', 'allow_redirects.on_redirect');
self::warnIfPresentAndNotBool($allowRedirects, 'track_redirects', 'allow_redirects.track_redirects');
}
@ -700,17 +951,25 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
}
}
private static function warnIfPresentAndNotCallable(array $options, string $option, ?string $path = null): void
{
private static function warnIfPresentAndNotCallable(
array $options,
string $option,
?string $path = null,
string $since = '7.11'
): void {
if (\array_key_exists($option, $options) && !\is_callable($options[$option])) {
self::warnInvalidRequestOptionType($path ?? $option, 'callable', $options[$option]);
self::warnInvalidRequestOptionType($path ?? $option, 'callable', $options[$option], $since);
}
}
private static function warnIfPresentAndNotInt(array $options, string $option, ?string $path = null): void
{
private static function warnIfPresentAndNotInt(
array $options,
string $option,
?string $path = null,
string $since = '7.11'
): void {
if (\array_key_exists($option, $options) && !\is_int($options[$option])) {
self::warnInvalidRequestOptionType($path ?? $option, 'int', $options[$option]);
self::warnInvalidRequestOptionType($path ?? $option, 'int', $options[$option], $since);
}
}
@ -752,6 +1011,24 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
}
}
/**
* @param array<array-key, mixed> $options
*/
private static function warnAboutInvalidProtocolValues(array $options, string $option, ?string $path = null): void
{
if (!isset($options[$option]) || !\is_array($options[$option])) {
return;
}
$path = $path ?? $option;
foreach ($options[$option] as $index => $protocol) {
if (\is_string($protocol) && $protocol !== 'http' && $protocol !== 'https') {
self::warnInvalidRequestOptionType($path.'.'.(string) $index, '"http"|"https"', $protocol, '7.13');
}
}
}
private static function warnIfPresentAndNotStringOrNumber(array $options, string $option): void
{
if (
@ -767,11 +1044,11 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
/**
* @param mixed $value
*/
private static function warnInvalidRequestOptionType(string $option, string $expected, $value): void
private static function warnInvalidRequestOptionType(string $option, string $expected, $value, string $since = '7.11'): void
{
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.11',
$since,
'Passing %s to request option "%s" is deprecated; guzzlehttp/guzzle 8.0 requires %s.',
\get_debug_type($value),
$option,
@ -841,7 +1118,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
.'x-www-form-urlencoded requests, and the multipart '
.'option to send multipart/form-data requests.');
}
$options['body'] = \http_build_query($options['form_params'], '', '&');
$options['body'] = \http_build_query(self::normalizeNonFiniteFloats($options['form_params'], 'form_params'), '', '&');
unset($options['form_params']);
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
@ -854,16 +1131,20 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
}
if (isset($options['json'])) {
$options['body'] = Utils::jsonEncode($options['json']);
$json = \json_encode($options['json']);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var non-empty-string $json */
$options['body'] = $json;
unset($options['json']);
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Content-Type'], $options['_conditional']);
$options['_conditional']['Content-Type'] = 'application/json';
}
if (!empty($options['decode_content'])
&& $options['decode_content'] !== true
) {
if (isset($options['decode_content']) && \is_string($options['decode_content'])) {
// Ensure that we don't have the header in different case and set the new value.
$options['_conditional'] = Psr7\Utils::caselessRemove(['Accept-Encoding'], $options['_conditional']);
$modify['set_headers']['Accept-Encoding'] = (string) $options['decode_content'];
@ -873,13 +1154,13 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
if (\is_array($options['body'])) {
throw $this->invalidBody();
}
$modify['body'] = Psr7\Utils::streamFor($options['body']);
$modify['body'] = self::createBodyStream($options['body']);
unset($options['body']);
}
if (!empty($options['auth']) && \is_array($options['auth'])) {
$value = $options['auth'];
$type = isset($value[2]) ? \strtolower($value[2]) : 'basic';
$type = isset($value[2]) ? Psr7\Utils::asciiToLower($value[2]) : 'basic';
switch ($type) {
case 'basic':
// Ensure that we don't have the header in different case and set the new value.
@ -893,6 +1174,14 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
$options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
case 'ntlm':
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.12',
'Passing "ntlm" as the built-in auth type is deprecated; guzzlehttp/guzzle 8.0 will no longer apply NTLM through the "auth" request option. NTLM is also deprecated by curl/libcurl and may be unavailable in current or future libcurl builds. Avoid NTLM; if you must use it temporarily, configure cURL HTTP authentication options directly with a libcurl build that still supports NTLM.'
);
if (!CurlVersion::supportsNtlm()) {
throw new InvalidArgumentException('NTLM authentication is not available because the installed curl/libcurl build does not provide NTLM support.');
}
$options['curl'][\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
$options['curl'][\CURLOPT_USERPWD] = "$value[0]:$value[1]";
break;
@ -902,7 +1191,7 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
if (isset($options['query'])) {
$value = $options['query'];
if (\is_array($value)) {
$value = \http_build_query($value, '', '&', \PHP_QUERY_RFC3986);
$value = \http_build_query(self::normalizeNonFiniteFloats($value, 'query'), '', '&', \PHP_QUERY_RFC3986);
}
if (!\is_string($value)) {
throw new InvalidArgumentException('query must be a string or array');
@ -970,6 +1259,9 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
foreach ($value as $index => $item) {
if ($item === null || (!\is_string($item) && \is_scalar($item))) {
if (\is_float($item) && !\is_finite($item)) {
$item = \is_nan($item) ? 'NAN' : ($item > 0 ? 'INF' : '-INF');
}
$value[$index] = (string) $item;
}
}
@ -980,6 +1272,9 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
}
if ($value === null || (!\is_string($value) && \is_scalar($value))) {
if (\is_float($value) && !\is_finite($value)) {
$value = \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
}
$headers[$name] = (string) $value;
}
}
@ -987,6 +1282,72 @@ class Client implements ClientInterface, \Psr\Http\Client\ClientInterface
return $droppedHeaderNames;
}
/**
* @param mixed $body
*/
private static function createBodyStream($body): StreamInterface
{
if ($body instanceof StreamInterface) {
return $body;
}
if (\is_resource($body) || $body === null || \is_string($body) || $body instanceof \Iterator) {
return Psr7\Utils::streamFor($body);
}
if (\is_scalar($body)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.12', 'Passing a non-string scalar to the "body" request option is deprecated; guzzlehttp/guzzle 8.0 will reject non-string scalar bodies.');
return Psr7\Utils::streamFor(self::stringifyScalar($body));
}
if (\is_object($body) && \method_exists($body, '__toString')) {
return Psr7\Utils::streamFor((string) $body);
}
if (\is_callable($body)) {
return Psr7\Utils::streamFor($body);
}
throw new InvalidArgumentException(\sprintf(
'Passing %s to request option "body" is invalid; expected resource|string|null|int|float|bool|StreamInterface|callable&object|Iterator|Stringable.',
\get_debug_type($body)
));
}
/**
* @param bool|float|int|string $value
*/
private static function stringifyScalar($value): string
{
// Normalize non-finite floats to dodge PHP 8.5's (string) NAN
// coercion warning while the value is still accepted.
if (\is_float($value) && !\is_finite($value)) {
$value = \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
}
return (string) $value;
}
/**
* Converts non-finite floats in the array to the strings PHP coerces
* them to, as implicit coercion of NAN emits a warning on PHP 8.5.
*/
private static function normalizeNonFiniteFloats(array $values, string $option): array
{
foreach ($values as $key => $value) {
if (\is_array($value)) {
$values[$key] = self::normalizeNonFiniteFloats($value, $option);
} elseif (\is_float($value) && !\is_finite($value)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.12', 'Passing a non-finite float in the "%s" request option is deprecated; guzzlehttp/guzzle 8.0 will reject non-finite floats.', $option);
$values[$key] = \is_nan($value) ? 'NAN' : ($value > 0 ? 'INF' : '-INF');
}
}
return $values;
}
/**
* @param string|int|float $version
*/

View file

@ -2,6 +2,7 @@
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
@ -88,7 +89,7 @@ class CookieJar implements CookieJarInterface
public function getCookieByName(string $name): ?SetCookie
{
foreach ($this->cookies as $cookie) {
if ($cookie->getName() !== null && \strcasecmp($cookie->getName(), $name) === 0) {
if ($cookie->getName() !== null && Psr7\Utils::caselessEquals($cookie->getName(), $name)) {
return $cookie;
}
}
@ -109,14 +110,14 @@ class CookieJar implements CookieJarInterface
$this->cookies = [];
return;
} elseif (!$path) {
} elseif ($path === null) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($domain): bool {
return $cookie->getDomain() === null || !$cookie->matchesDomain($domain);
}
);
} elseif (!$name) {
} elseif ($name === null) {
$this->cookies = \array_filter(
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain): bool {
@ -130,7 +131,7 @@ class CookieJar implements CookieJarInterface
$this->cookies,
static function (SetCookie $cookie) use ($path, $domain, $name) {
return !($cookie->getDomain() !== null
&& $cookie->getName() == $name
&& $cookie->getName() === $name
&& $cookie->matchesPath($path)
&& $cookie->matchesDomain($domain));
}
@ -168,13 +169,22 @@ class CookieJar implements CookieJarInterface
return false;
}
$maxAge = $cookie->getMaxAge();
if ($maxAge !== null && $maxAge <= 0) {
if ($cookie->getDomain() !== null) {
$this->clear($cookie->getDomain(), $cookie->getPath(), $cookie->getName());
}
return false;
}
// Resolve conflicts with previously set cookies
foreach ($this->cookies as $i => $c) {
// Two cookies are identical, when their path, and domain are
// identical.
if ($c->getPath() != $cookie->getPath()
|| $c->getDomain() != $cookie->getDomain()
|| $c->getName() != $cookie->getName()
if ($c->getPath() !== $cookie->getPath()
|| $c->getDomain() !== $cookie->getDomain()
|| $c->getName() !== $cookie->getName()
) {
continue;
}
@ -226,7 +236,11 @@ class CookieJar implements CookieJarInterface
if ($cookieHeader = $response->getHeader('Set-Cookie')) {
foreach ($cookieHeader as $cookie) {
$sc = SetCookie::fromString($cookie);
if (!$sc->getDomain()) {
$domain = $sc->getDomain();
if ($domain === null || $domain === '') {
$sc->setDomain($request->getUri()->getHost());
} elseif (\substr($domain, -1) === '.' && '' !== \trim($domain, '.')) {
// Keep pure-dot domains rejected by the dot-only fix.
$sc->setDomain($request->getUri()->getHost());
}
if (0 !== \strpos($sc->getPath(), '/')) {

View file

@ -2,7 +2,7 @@
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Utils;
use GuzzleHttp\Exception\InvalidArgumentException;
/**
* Persists non-session cookies using a JSON formatted file
@ -64,7 +64,12 @@ class FileCookieJar extends CookieJar
}
}
$jsonStr = Utils::jsonEncode($json);
$jsonStr = \json_encode($json);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_encode error: '.\json_last_error_msg());
}
/** @var non-empty-string $jsonStr */
if (false === \file_put_contents($filename, $jsonStr, \LOCK_EX)) {
throw new \RuntimeException("Unable to save file {$filename}");
}
@ -89,7 +94,11 @@ class FileCookieJar extends CookieJar
return;
}
$data = Utils::jsonDecode($json, true);
$data = \json_decode($json, true);
if (\JSON_ERROR_NONE !== \json_last_error()) {
throw new InvalidArgumentException('json_decode error: '.\json_last_error_msg());
}
if (\is_array($data)) {
foreach ($data as $cookie) {
$this->setCookie(new SetCookie($cookie));

View file

@ -2,6 +2,8 @@
namespace GuzzleHttp\Cookie;
use GuzzleHttp\Psr7;
/**
* Set-Cookie object
*/
@ -37,7 +39,9 @@ class SetCookie
// Create the default return array
$data = self::$defaults;
// Explode the cookie string using a series of semicolons
$pieces = \array_filter(\array_map('trim', \explode(';', $cookie)));
$pieces = \array_filter(\array_map(static function (string $piece): string {
return \trim($piece, " \n\r\t\0\x0B");
}, \explode(';', $cookie)));
// The name of the cookie (first kvp) must exist and include an equal sign.
if (!isset($pieces[0]) || \strpos($pieces[0], '=') === false) {
return new self($data);
@ -46,7 +50,7 @@ class SetCookie
// Add the cookie pieces into the parsed data array
foreach ($pieces as $part) {
$cookieParts = \explode('=', $part, 2);
$key = \trim($cookieParts[0]);
$key = \trim($cookieParts[0], " \n\r\t\0\x0B");
$value = isset($cookieParts[1])
? \trim($cookieParts[1], " \n\r\t\0\x0B")
: true;
@ -57,7 +61,7 @@ class SetCookie
$data['Value'] = $value;
} else {
foreach (\array_keys(self::$defaults) as $search) {
if (!\strcasecmp($search, $key)) {
if (Psr7\Utils::caselessEquals($search, $key)) {
if ($search === 'Max-Age') {
if (is_numeric($value)) {
$data[$search] = (int) $value;
@ -128,14 +132,27 @@ class SetCookie
}
// Extract the Expires value and turn it into a UNIX timestamp if needed
if (!$this->getExpires() && $this->getMaxAge()) {
$maxAge = $this->getMaxAge();
if (!$this->getExpires() && $maxAge !== null) {
// Calculate the Expires date
$this->setExpires(\time() + $this->getMaxAge());
$this->setExpires(self::maxAgeToExpires($maxAge, \time()));
} elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
$this->setExpires($expires);
}
}
private static function maxAgeToExpires(int $maxAge, int $now): int
{
if ($maxAge <= 0) {
return $now - 1;
}
if ($maxAge > \PHP_INT_MAX - $now) {
return \PHP_INT_MAX;
}
return $now + $maxAge;
}
public function __toString()
{
$str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
@ -401,7 +418,7 @@ class SetCookie
$cookiePath = $this->getPath();
// Match on exact matches or when path is the default empty "/"
if ($cookiePath === '/' || $cookiePath == $requestPath) {
if ($cookiePath === '/' || $cookiePath === $requestPath) {
return true;
}
@ -433,22 +450,57 @@ class SetCookie
// Remove the leading '.' as per spec in RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.2.3
$cookieDomain = \ltrim(\strtolower($cookieDomain), '.');
$cookieDomain = Psr7\Utils::asciiToLower($cookieDomain);
if ($cookieDomain !== '' && $cookieDomain[0] === '.') {
/** @var string */
$cookieDomain = \substr($cookieDomain, 1);
}
if ('' === $cookieDomain) {
return false;
}
$domain = \strtolower($domain);
// Domain not set or exact match.
if ('' === $cookieDomain || $domain === $cookieDomain) {
$domain = Psr7\Utils::asciiToLower($domain);
if ($domain === $cookieDomain) {
return true;
}
// IP literals and numeric hosts are exact-match-only per RFC 6265.
// Only the exact match above may succeed for those cookie domains.
if (self::isIpAddressOrNumericHost($cookieDomain)) {
return false;
}
// Matching the subdomain according to RFC 6265.
// https://datatracker.ietf.org/doc/html/rfc6265#section-5.1.3
if (\filter_var($domain, \FILTER_VALIDATE_IP)) {
return false;
}
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/', $domain);
return (bool) \preg_match('/\.'.\preg_quote($cookieDomain, '/').'$/D', $domain);
}
private static function isIpAddressOrNumericHost(string $host): bool
{
// Strip one root dot before detection so trailing-dot numeric hosts
// still cannot be matched by subdomains.
if ($host !== '' && \str_ends_with($host, '.')) {
$host = \substr($host, 0, -1);
}
if (\str_starts_with($host, '[') && \str_ends_with($host, ']')) {
$host = \substr($host, 1, -1);
}
if (\filter_var($host, \FILTER_VALIDATE_IP) !== false) {
return true;
}
// Public DNS names do not have an all-numeric rightmost label; treat
// those private/internal hosts as exact-match-only too.
$labels = \explode('.', $host);
$last = (string) \end($labels);
return $last !== '' && \ctype_digit($last);
}
/**
@ -472,10 +524,7 @@ class SetCookie
}
// Check if any of the invalid characters are present in the cookie name
if (\preg_match(
'/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/',
$name
)) {
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5c\x7b\x7d\x7f]/', $name) !== 0) {
return 'Cookie name must not contain invalid characters: ASCII '
.'Control characters (0-31;127), space, tab and the '
.'following characters: ()<>@,;:\"/?={}';
@ -491,7 +540,7 @@ class SetCookie
// Domains must not be empty, but may be omitted. "0" is not a valid
// internet domain, but may be used as server name in a private network.
$domain = $this->getDomain();
if ($domain === '') {
if ($domain === '' || (null !== $domain && '' === \ltrim(\trim($domain, " \n\r\t\0\x0B"), '.'))) {
return 'The cookie domain must not be empty';
}

File diff suppressed because it is too large Load diff

View file

@ -17,6 +17,11 @@ use Psr\Http\Message\RequestInterface;
*/
class CurlHandler
{
private const KNOWN_CONSTRUCTOR_OPTIONS = [
'handle_factory' => true,
'transport_sharing' => true,
];
/**
* @var CurlFactoryInterface
*/
@ -37,6 +42,12 @@ class CurlHandler
*/
public function __construct(array $options = [])
{
foreach ($options as $name => $_) {
if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) {
\trigger_deprecation('guzzlehttp/guzzle', '7.14', \sprintf('The "%s" CurlHandler constructor option is unknown; guzzlehttp/guzzle 8.0 will reject unknown constructor options.', (string) $name));
}
}
CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler');
$transportSharing = $options['transport_sharing'] ?? null;
$sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
@ -53,7 +64,7 @@ class CurlHandler
: null;
$this->factory = $this->shareHandleState !== null
? new CurlFactory(3, $this->shareHandleState->mode, $this->shareHandleState->handle)
? new CurlFactory(3, $this->shareHandleState->mode, $this->shareHandleState)
: new CurlFactory(3);
}
@ -63,6 +74,11 @@ class CurlHandler
\usleep($options['delay'] * 1000);
}
// A Multiplexing::NONE request option holds unconditionally here:
// transport sharing never shares the connection cache on this
// branch, and nothing else executes during the blocking curl_exec(),
// so the transfer cannot share its connection with a concurrent
// transfer.
$easy = $this->factory->create($request, $options);
\curl_exec($easy->handle);
$easy->errno = \curl_errno($easy->handle);

File diff suppressed because it is too large Load diff

View file

@ -3,7 +3,6 @@
namespace GuzzleHttp\Handler;
use GuzzleHttp\TransportSharing;
use GuzzleHttp\Utils;
/**
* @internal
@ -70,7 +69,7 @@ final class CurlShareHandleState
throw new \InvalidArgumentException(\sprintf(
'The "%s" option must be null or a GuzzleHttp\\TransportSharing::* constant; received %s.',
$option,
Utils::describeType($sharing)
\get_debug_type($sharing)
));
}
@ -108,7 +107,7 @@ final class CurlShareHandleState
self::requireCurlConstant('CURLOPT_SHARE');
$shareOption = self::requireCurlConstant('CURLSHOPT_SHARE');
$locks = self::handlerLocks();
$locks = self::handlerLocks($mode);
$handle = curl_share_init();
try {
@ -135,12 +134,23 @@ final class CurlShareHandleState
/**
* @return int[]
*/
private static function handlerLocks(): array
private static function handlerLocks(string $mode): array
{
return [
CurlVersion::ensureHandlerSharingSupported();
if ($mode === TransportSharing::HANDLER_REQUIRE) {
CurlVersion::ensureSslSessionSharingSupported();
}
$locks = [
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'),
];
if (CurlVersion::supportsSslSessionSharing()) {
$locks[] = self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION');
}
return $locks;
}
private static function requireCurlConstant(string $constant): int

View file

@ -0,0 +1,322 @@
<?php
namespace GuzzleHttp\Handler;
/**
* @internal
*/
final class CurlVersion
{
private const MIN_VERSION = '7.21.2';
private const TLS_12_VERSION = '7.34.0';
private const TLS_13_VERSION = '7.52.0';
private const CONNECTION_CAP_VERSION = '7.30.0';
// CURLOPT_PIPEWAIT exists since libcurl 7.43.0, and multi handles have
// multiplexed by default since 7.62.0 - but a 7.65.0-7.65.1 regression
// dropped that default, which 7.65.2 restored, so 7.65.2 is the floor at
// which PIPEWAIT is reliably effective.
private const MULTIPLEX_VERSION = '7.65.2';
// libcurl's connection matcher refuses to hand a transfer wanting
// HTTP/1.x a pooled connection that already negotiated HTTP/2 or newer
// from 7.77.0: ConnectionExists() in lib/url.c gained the check between
// the 7.76.0 and 7.77.0 releases. The HTTP/2 branch of the check
// regressed to a debug log in 8.11.0 (curl commit 433d730) and was
// restored in 8.13.0 via the negotiation mask (curl commit db72b8d), so
// 8.11.0 through 8.12.1 are vulnerable again.
private const HTTP_VERSION_REUSE_MATCH_VERSION = '7.77.0';
private const HTTP_VERSION_REUSE_MATCH_REGRESSION = '8.11.0';
private const HTTP_VERSION_REUSE_MATCH_RESTORED = '8.13.0';
// CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE restricts the ALPN offer to h2 only
// since libcurl 8.10.0, and connection reuse matching stopped handing
// lower-version connections to prior-knowledge transfers in 8.14.0; below
// that, a required request could silently be sent over a reused HTTP/1.1
// connection.
private const REQUIRED_MULTIPLEX_VERSION = '8.14.0';
// curl 7.52.0 introduced HTTPS proxy support, advertised by a feature bit
// (a build can meet the version yet lack the feature). Earlier libcurl
// mishandles an https:// proxy: before 7.50.2 it silently downgrades to a
// plaintext HTTP proxy, and 7.50.2 through 7.51 reject it at connect time.
private const HTTPS_PROXY_VERSION = '7.52.0';
private const HANDLER_SHARING_VERSION = '7.35.0';
private const SSL_SESSION_SHARING_VERSION = '8.6.0';
// curl 7.57.0 added share-handle connection caches through
// CURL_LOCK_DATA_CONNECT; older share objects can only hold DNS, TLS
// session, and cookie data, never connections.
private const SHARE_CONNECTION_CACHE_VERSION = '7.57.0';
// curl 7.83.1 added proxy TLS-SRP to the connection-reuse match
// (CVE-2022-27782); the proxy client certificate was matched from 7.52.0,
// so proxy TLS credentials are trusted from 7.83.1 onwards.
private const PROXY_TLS_CREDENTIAL_REUSE_VERSION = '7.83.1';
// curl 8.19.0 fixed proxy tunnel reuse after credential changes
// (CVE-2026-3784), but related proxy credential leak flaws were only
// fixed in 8.20.0, so connection reuse is trusted from 8.20.0 onwards.
private const PROXY_CREDENTIAL_REUSE_VERSION = '8.20.0';
// curl 7.69.0 started comparing SOCKS proxy credentials when matching
// connections for reuse (curl #4835); older libcurl matches a SOCKS proxy
// by type, host, and port only.
private const SOCKS_PROXY_CREDENTIAL_REUSE_VERSION = '7.69.0';
private const PROXY_HEADER_SEPARATION_VERSION = '7.37.0';
/**
* @var array{version: string, features: int}|false|null
*/
private static $versionInfo;
private function __construct()
{
}
public static function supportsCurlHandler(): bool
{
$version = self::getVersion();
return $version !== null && \version_compare($version, self::MIN_VERSION, '>=');
}
public static function supportsTls12(): bool
{
$version = self::getVersion();
return self::supportsSsl()
&& \defined('CURL_SSLVERSION_TLSv1_2')
&& $version !== null
&& \version_compare($version, self::TLS_12_VERSION, '>=');
}
public static function supportsTls13(): bool
{
$version = self::getVersion();
return self::supportsSsl()
&& \defined('CURL_SSLVERSION_TLSv1_3')
&& $version !== null
&& \version_compare($version, self::TLS_13_VERSION, '>=');
}
public static function supportsHttp2(): bool
{
$versionInfo = self::getVersionInfo();
return self::supportsTls12()
&& \defined('CURL_VERSION_HTTP2')
&& $versionInfo !== null
&& 0 !== (\CURL_VERSION_HTTP2 & $versionInfo['features']);
}
public static function supportsMultiplex(): bool
{
$version = self::getVersion();
return \defined('CURLOPT_PIPEWAIT')
&& $version !== null
&& \version_compare($version, self::MULTIPLEX_VERSION, '>=');
}
public static function supportsHttpVersionReuseMatching(): bool
{
$version = self::getVersion();
if ($version === null || \version_compare($version, self::HTTP_VERSION_REUSE_MATCH_VERSION, '<')) {
return false;
}
return \version_compare($version, self::HTTP_VERSION_REUSE_MATCH_REGRESSION, '<')
|| \version_compare($version, self::HTTP_VERSION_REUSE_MATCH_RESTORED, '>=');
}
public static function supportsConnectionCaps(): bool
{
$version = self::getVersion();
return \defined('CURLMOPT_MAX_HOST_CONNECTIONS')
&& \defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')
&& $version !== null
&& \version_compare($version, self::CONNECTION_CAP_VERSION, '>=');
}
public static function ensureConnectionCapsSupported(string $option): void
{
if (self::supportsConnectionCaps()) {
return;
}
throw new \InvalidArgumentException(\sprintf(
'The "%s" option requires PHP cURL support for CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAX_TOTAL_CONNECTIONS with libcurl %s or newer.',
$option,
self::CONNECTION_CAP_VERSION
));
}
public static function supportsRequiredMultiplex(): bool
{
$version = self::getVersion();
return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')
&& $version !== null
&& self::supportsHttp2()
&& \version_compare($version, self::REQUIRED_MULTIPLEX_VERSION, '>=');
}
public static function supportsHttpsProxy(): bool
{
$versionInfo = self::getVersionInfo();
// CURL_VERSION_HTTPS_PROXY is not defined on every supported PHP
// version; fall back to the curl.h bit value.
$httpsProxyFeature = \defined('CURL_VERSION_HTTPS_PROXY') ? \CURL_VERSION_HTTPS_PROXY : (1 << 21);
return $versionInfo !== null
&& \version_compare($versionInfo['version'], self::HTTPS_PROXY_VERSION, '>=')
&& 0 !== ($httpsProxyFeature & $versionInfo['features']);
}
public static function supportsNtlm(): bool
{
$versionInfo = self::getVersionInfo();
// CURL_VERSION_NTLM is not defined on every supported PHP version; fall
// back to the curl.h bit value.
$ntlmFeature = \defined('CURL_VERSION_NTLM') ? \CURL_VERSION_NTLM : (1 << 4);
return \defined('CURLAUTH_NTLM')
&& $versionInfo !== null
&& 0 !== ($ntlmFeature & $versionInfo['features']);
}
public static function supportsHandlerSharing(): bool
{
$version = self::getVersion();
return $version !== null && \version_compare($version, self::HANDLER_SHARING_VERSION, '>=');
}
public static function ensureHandlerSharingSupported(): void
{
if (!self::supportsHandlerSharing()) {
throw new \InvalidArgumentException(\sprintf(
'The "transport_sharing" option requires libcurl %s or higher for cURL share handles.',
self::HANDLER_SHARING_VERSION
));
}
}
public static function supportsSslSessionSharing(): bool
{
$version = self::getVersion();
return self::supportsSsl()
&& $version !== null
&& \version_compare($version, self::SSL_SESSION_SHARING_VERSION, '>=');
}
public static function ensureSslSessionSharingSupported(): void
{
if (!self::supportsSslSessionSharing()) {
throw new \InvalidArgumentException(\sprintf(
'The "transport_sharing" option requires libcurl %s or higher with SSL support for SSL session sharing.',
self::SSL_SESSION_SHARING_VERSION
));
}
}
public static function supportsShareConnectionCaches(): bool
{
$version = self::getVersion();
// An undetectable libcurl version is treated as capable so the
// opaque share safeguards fail closed.
return $version === null || \version_compare($version, self::SHARE_CONNECTION_CACHE_VERSION, '>=');
}
public static function supportsProxyTlsCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsProxyCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsSocksProxyCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsProxyHeaderSeparation(): bool
{
$version = self::getVersion();
return $version !== null
&& \version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=')
&& \defined('CURLOPT_PROXYHEADER')
&& \defined('CURLOPT_HEADEROPT')
&& \defined('CURLHEADER_SEPARATE');
}
private static function supportsSsl(): bool
{
$versionInfo = self::getVersionInfo();
return \defined('CURL_VERSION_SSL')
&& $versionInfo !== null
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
}
public static function getVersion(): ?string
{
$versionInfo = self::getVersionInfo();
return $versionInfo === null ? null : $versionInfo['version'];
}
/**
* @return array{version: string, features: int}|null
*/
private static function getVersionInfo(): ?array
{
if (self::$versionInfo === null) {
if (!\function_exists('curl_version')) {
self::$versionInfo = false;
} else {
$versionInfo = \curl_version();
self::$versionInfo = \is_array($versionInfo)
&& isset($versionInfo['version'], $versionInfo['features'])
&& \is_string($versionInfo['version'])
&& \is_int($versionInfo['features'])
? [
'version' => $versionInfo['version'],
'features' => $versionInfo['features'],
]
: false;
}
}
return self::$versionInfo === false ? null : self::$versionInfo;
}
}

View file

@ -30,6 +30,17 @@ final class EasyHandle
*/
public $headers = [];
/**
* @var array Valid trailer lines, retained only when an on_trailers
* callback is configured
*/
public $trailers = [];
/**
* @var bool Whether this handle was configured with CURLOPT_PIPEWAIT
*/
public $usesPipewait = false;
/**
* @var ResponseInterface|null Received response (if any)
*/
@ -50,6 +61,19 @@ final class EasyHandle
*/
public $errno = 0;
/**
* @var string|null Effective CURLOPT_PROXY value the handle was created with (if any)
*/
public $effectiveProxy;
/**
* Proxy tunnel or SOCKS proxy section signature for connection-reuse
* isolation, or null when the request does not require sectioning.
*
* @var string|null
*/
public $proxyTunnelSignature;
/**
* @var \Throwable|null Exception during on_headers (if any)
*/
@ -74,7 +98,7 @@ final class EasyHandle
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
if (!empty($this->options['decode_content']) && isset($normalizedKeys['content-encoding'])) {
if (isset($this->options['decode_content']) && $this->options['decode_content'] !== false && isset($normalizedKeys['content-encoding'])) {
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
unset($headers[$normalizedKeys['content-encoding']]);
if (isset($normalizedKeys['content-length'])) {

View file

@ -44,7 +44,7 @@ final class HeaderProcessor
throw new \RuntimeException('HTTP status code missing from header data');
}
if (!\preg_match('/^\d{3}$/', $status)) {
if (!\preg_match('/^\d{3}$/D', $status)) {
throw new \RuntimeException('HTTP status code is invalid');
}
@ -57,6 +57,26 @@ final class HeaderProcessor
return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)];
}
public static function isStatusLineCandidate(string $line): bool
{
return \preg_match('/^HTTP\/[0-9]+(?:\.[0-9]+)? [0-9]{3}(?: [^\r\n]*)?(?:\r\n|\r|\n)?$/iD', $line) === 1;
}
public static function isValidHeaderFieldLine(string $line): bool
{
$parts = \explode(':', $line, 2);
if (!isset($parts[1])) {
return false;
}
if (!\preg_match('/^[a-zA-Z0-9\'`#$%&*+.^_|~!-]+$/D', $parts[0])) {
return false;
}
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*(?:\r\n|\r|\n)?$/D', \trim($parts[1], " \t")) === 1;
}
/**
* @param non-empty-list<string> $headers
*
@ -67,7 +87,7 @@ final class HeaderProcessor
$lastStatusLine = 0;
foreach ($headers as $index => $line) {
if (\preg_match('/^HTTP\/\S+\s+/i', $line)) {
if (self::isStatusLineCandidate($line)) {
$lastStatusLine = $index;
}
}

View file

@ -7,7 +7,6 @@ use GuzzleHttp\HandlerStack;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\TransferStats;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
@ -160,7 +159,7 @@ class MockHandler implements \Countable
) {
$this->queue[] = $value;
} else {
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.Utils::describeType($value));
throw new \TypeError('Expected a Response, Promise, Throwable or callable. Found '.\get_debug_type($value));
}
}
}

View file

@ -48,4 +48,34 @@ class Proxy
return empty($options['stream']) ? $default($request, $options) : $streaming($request, $options);
};
}
/**
* Sends requests to a fallback handler when the default cURL handler cannot
* honor TLS 1.2 selection.
*
* @param callable(RequestInterface, array): PromiseInterface $default
* @param callable(RequestInterface, array): PromiseInterface $fallback
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
*/
public static function wrapTlsFallback(callable $default, callable $fallback): callable
{
return static function (RequestInterface $request, array $options) use ($default, $fallback): PromiseInterface {
if (self::requiresTls12Fallback($options)) {
return $fallback($request, $options);
}
return $default($request, $options);
};
}
/**
* @param array<string, mixed> $options
*/
private static function requiresTls12Fallback(array $options): bool
{
return isset($options[RequestOptions::CRYPTO_METHOD])
&& $options[RequestOptions::CRYPTO_METHOD] === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT
&& !CurlVersion::supportsTls12();
}
}

View file

@ -0,0 +1,121 @@
<?php
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7;
/**
* Resolves proxy configuration from the process environment with the same
* semantics libcurl applies, so the cURL handlers can pin CURLOPT_PROXY and
* CURLOPT_NOPROXY explicitly and libcurl never reads the environment itself.
*
* @internal
*/
final class ProxyEnvironment
{
private function __construct()
{
}
/**
* Resolves the proxy to use for the given request scheme.
*
* The lookup mirrors libcurl for the http and https schemes the handlers
* accept: the lowercase scheme-specific variable first, its uppercase
* variant next (except for "http", where uppercase HTTP_PROXY is never
* read), then all_proxy/ALL_PROXY.
*
* @return string|null The proxy to use; null when the environment
* configures none.
*/
public static function getProxyForScheme(string $scheme): ?string
{
$scheme = Psr7\Utils::asciiToLower($scheme);
$candidates = [$scheme.'_proxy'];
if ($scheme !== 'http') {
// Uppercase HTTP_PROXY is deliberately never consulted: a CGI
// request header "Proxy:" becomes HTTP_PROXY in the environment.
// See https://httpoxy.org for more information.
$candidates[] = Psr7\Utils::asciiToUpper($scheme).'_PROXY';
}
$candidates[] = 'all_proxy';
$candidates[] = 'ALL_PROXY';
foreach ($candidates as $name) {
$value = self::getenv($name);
if ($value !== null) {
return $value;
}
}
return null;
}
/**
* @return string|null The no-proxy list; null when nothing is set.
*/
public static function getNoProxy(): ?string
{
foreach (['no_proxy', 'NO_PROXY'] as $name) {
$value = self::getenv($name);
if ($value !== null) {
return $value;
}
}
return null;
}
/**
* Splits a no_proxy environment value into matchable entries.
*
* Mirrors libcurl's tokenization: entries may be separated by commas or
* blanks, and a single leading dot is ignored, so ".example.com" bypasses
* example.com and its subdomains exactly as a bare domain entry does.
*
* @return string[]
*/
public static function splitNoProxy(string $noProxy): array
{
$entries = [];
$split = \preg_split('/[\s,]+/', $noProxy);
if ($split === false) {
throw new \RuntimeException('Unable to split the no_proxy value: '.\preg_last_error_msg());
}
foreach ($split as $entry) {
if ($entry !== '' && $entry[0] === '.') {
$entry = \substr($entry, 1);
}
if ($entry !== '') {
$entries[] = $entry;
}
}
return $entries;
}
private static function getenv(string $name): ?string
{
// Windows environment variables are case-insensitive, so the
// lowercase-only httpoxy defence does not hold there. Outside the
// CLI SAPI on Windows, environment proxies are not resolved at all
// (a safe-side divergence from libcurl).
if (\PHP_OS_FAMILY === 'Windows' && \PHP_SAPI !== 'cli') {
return null;
}
// local_only: the OS environment and putenv() only - the same
// environ(7) libcurl reads. SAPI request environments such as
// fastcgi_param or SetEnv are deliberately excluded.
$value = \getenv($name, true);
// libcurl's GetEnv (lib/getenv.c) treats variables set to an empty
// string as unset on every version, so the lookup falls through to
// the next candidate.
return $value === false || $value === '' ? null : $value;
}
}

View file

@ -4,6 +4,7 @@ namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Multiplexing;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\FulfilledPromise;
use GuzzleHttp\Promise\PromiseInterface;
@ -23,6 +24,12 @@ use Psr\Http\Message\UriInterface;
*/
class StreamHandler
{
private const KNOWN_CONSTRUCTOR_OPTIONS = [
'max_host_connections' => true,
'max_total_connections' => true,
'transport_sharing' => true,
];
private const CONNECTION_ERRORS = [
'php_network_getaddresses:',
'getaddrinfo',
@ -46,6 +53,61 @@ class StreamHandler
*/
private $lastHeaders = [];
/**
* @var string
*/
private $transportSharingMode;
/**
* @var bool
*/
private $connectionCapsConfigured = false;
/**
* Accepts an associative array of options:
*
* - max_host_connections: Optional positive integer or null. A non-null
* value marks the handler as incompatible with enabled response
* streaming; the number is not used for stream-handler admission.
* - max_total_connections: Optional positive integer or null. A non-null
* value marks the handler as incompatible with enabled response
* streaming; the number is not used for stream-handler admission.
* - transport_sharing: Optional transport sharing mode.
*
* The stream handler cannot cap streamed connections, so a configured cap
* marker rejects enabled response streaming ("stream" => true). Accepted
* transfers are buffered and hold at most one connection per in-flight
* call, but overlapping buffered calls are not collectively limited.
*
* @param array{max_host_connections?: mixed, max_total_connections?: mixed, transport_sharing?: mixed} $options Array of options to use with the handler
*/
public function __construct(array $options = [])
{
foreach ($options as $name => $_) {
if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) {
\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));
}
}
$this->transportSharingMode = CurlShareHandleState::normalizeMode(
$options['transport_sharing'] ?? null,
'transport_sharing'
);
foreach (['max_host_connections', 'max_total_connections'] as $capOption) {
$value = $options[$capOption] ?? null;
if ($value === null) {
continue;
}
if (!\is_int($value) || $value < 1) {
throw new \InvalidArgumentException(\sprintf('%s must be a positive integer.', $capOption));
}
$this->connectionCapsConfigured = true;
}
}
/**
* Sends an HTTP request.
*
@ -59,6 +121,29 @@ class StreamHandler
\usleep($options['delay'] * 1000);
}
$multiplex = $options['multiplex'] ?? null;
// Multiplexing::NONE is trivially satisfied: the stream handler sends
// one HTTP/1.x request per connection and never multiplexes.
if (null !== $multiplex && !\in_array($multiplex, [Multiplexing::NONE, Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
throw new \InvalidArgumentException(\sprintf(
'The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.',
\get_debug_type($multiplex)
));
}
if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
throw new ConnectException('The stream handler cannot guarantee a multiplexed protocol; required multiplexing needs a cURL handler.', $request);
}
if ($this->connectionCapsConfigured && !empty($options['stream'])) {
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.');
}
if (isset($options['on_trailers'])) {
throw new \InvalidArgumentException('Passing the "on_trailers" request option to the stream handler is not supported because the stream handler cannot observe trailers.');
}
$protocolVersion = $request->getProtocolVersion();
if ('' === $protocolVersion) {
@ -75,6 +160,7 @@ class StreamHandler
$startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
self::triggerUnsupportedRequestOptionDeprecations($request, $options);
$this->assertTransportSharingSupported();
try {
// Does not support the expect header.
@ -84,8 +170,8 @@ class StreamHandler
// the behavior of `CurlHandler`
if (
(
0 === \strcasecmp('PUT', $request->getMethod())
|| 0 === \strcasecmp('POST', $request->getMethod())
Psr7\Utils::caselessEquals('PUT', $request->getMethod())
|| Psr7\Utils::caselessEquals('POST', $request->getMethod())
)
&& 0 === $request->getBody()->getSize()
) {
@ -155,7 +241,7 @@ class StreamHandler
$stream = Psr7\Utils::streamFor($stream);
$sink = $stream;
if (\strcasecmp('HEAD', $request->getMethod())) {
if (!Psr7\Utils::caselessEquals('HEAD', $request->getMethod())) {
$sink = $this->createSink($stream, $options);
}
@ -221,7 +307,7 @@ class StreamHandler
private function checkDecode(array $options, array $headers, $stream): array
{
// Automatically decode responses when instructed.
if (!empty($options['decode_content'])) {
if (isset($options['decode_content']) && $options['decode_content'] !== false) {
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
if (isset($normalizedKeys['content-encoding'])) {
$encoding = $headers[$normalizedKeys['content-encoding']];
@ -307,7 +393,7 @@ class StreamHandler
$message .= "[$key] $value".\PHP_EOL;
}
}
throw new \RuntimeException(\trim($message));
throw new \RuntimeException(\trim($message, " \n\r\t\0\x0B"));
}
return $resource;
@ -323,7 +409,12 @@ class StreamHandler
$methods = \array_flip(\get_class_methods(__CLASS__));
}
$scheme = $request->getUri()->getScheme();
$uri = $request->getUri();
$scheme = $uri->getScheme();
if ($scheme === '') {
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);
}
if (!\in_array($scheme, ['http', 'https'], true)) {
throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
}
@ -333,6 +424,10 @@ class StreamHandler
throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $request);
}
if ($uri->getHost() === '') {
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);
}
// HTTP/1.1 streams using the PHP stream wrapper require a
// Connection: close header
if ($request->getProtocolVersion() === '1.1'
@ -353,10 +448,19 @@ class StreamHandler
throw new \InvalidArgumentException('on_headers must be callable');
}
self::assertTlsVersionRangeForOptions($options);
$proxyAuthorizationAdded = false;
if (!empty($options)) {
foreach ($options as $key => $value) {
$method = "add_{$key}";
if (isset($methods[$method])) {
if ($method === 'add_proxy') {
$proxyAuthorizationAdded = $this->add_proxy($request, $context, $value, $params);
continue;
}
$this->{$method}($request, $context, $value, $params);
}
}
@ -366,6 +470,16 @@ class StreamHandler
if (!\is_array($options['stream_context'])) {
throw new \InvalidArgumentException('stream_context must be an array');
}
if (
$proxyAuthorizationAdded
&& isset($options['stream_context']['http'])
&& \is_array($options['stream_context']['http'])
&& \array_key_exists('proxy', $options['stream_context']['http'])
) {
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.');
}
self::triggerConflictingStreamContextOptionDeprecations($options['stream_context']);
self::triggerUnsupportedStreamContextOptionDeprecations($options['stream_context']);
$context = \array_replace_recursive($context, $options['stream_context']);
}
@ -394,7 +508,7 @@ class StreamHandler
$this->lastHeaders = $http_response_header ?? [];
if (false === $resource) {
throw new ConnectException(sprintf('Connection refused for URI %s', $uri), $request, null, $context);
throw new ConnectException(sprintf('Connection refused for URI %s', Psr7\Utils::redactUserInfo($uri)), $request, null, $context);
}
if (isset($options['read_timeout'])) {
@ -413,7 +527,11 @@ class StreamHandler
{
$uri = $request->getUri();
if (isset($options['force_ip_resolve']) && !\filter_var($uri->getHost(), \FILTER_VALIDATE_IP)) {
$host = $uri->getHost();
$hostForIpCheck = $host !== '' && $host[0] === '[' && \substr($host, -1) === ']'
? \substr($host, 1, -1)
: $host;
if (isset($options['force_ip_resolve']) && !\filter_var($hostForIpCheck, \FILTER_VALIDATE_IP)) {
if ('v4' === $options['force_ip_resolve']) {
$records = \dns_get_record($uri->getHost(), \DNS_A);
if (false === $records || !isset($records[0]['ip'])) {
@ -439,6 +557,17 @@ class StreamHandler
{
$headers = '';
foreach ($request->getHeaders() as $name => $value) {
// A first-class Proxy-Authorization header is proxy-scoped. Keep
// it out of the origin context; add_proxy() adds one
// validated canonical line only when Guzzle selects a proxy; PHP
// extracts that line for CONNECT and removes it before sending the
// tunneled origin request. The caselessEquals() helper is
// locale-independent, unlike strcasecmp(), so a locale cannot
// make this match miss and re-leak the credential.
if (Psr7\Utils::caselessEquals((string) $name, 'Proxy-Authorization')) {
continue;
}
foreach ($value as $val) {
$headers .= "$name: $val\r\n";
}
@ -467,21 +596,13 @@ class StreamHandler
}
}
$context['http']['header'] = \rtrim($context['http']['header']);
$context['http']['header'] = \rtrim($context['http']['header'], " \n\r\t\0\x0B");
return $context;
}
private static function triggerUnsupportedRequestOptionDeprecations(RequestInterface $request, array $options): void
{
if (\array_key_exists('transport_sharing', $options)) {
$transportSharingMode = CurlShareHandleState::normalizeMode($options['transport_sharing'], 'transport_sharing');
if ($transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
throw new \InvalidArgumentException('The "transport_sharing" option requires transport sharing, but the stream handler does not support it.');
}
}
if (
\array_key_exists('curl', $options)
&& $options['curl'] !== null
@ -491,15 +612,170 @@ class StreamHandler
\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.');
}
if (self::usesDigestAuth($options)) {
\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing digest authentication to the stream handler is deprecated; guzzlehttp/guzzle 8.0 will reject digest authentication with the stream handler because it is only supported by cURL handlers.');
}
if (\array_key_exists('expect', $options) && $options['expect'] !== false && $request->hasHeader('Expect')) {
\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.');
}
}
private static function triggerConflictingStreamContextOptionDeprecations(array $streamContext): void
{
$conflictingOptions = self::conflictingStreamContextOptions();
foreach ($streamContext as $wrapper => $contextOptions) {
if (!\is_string($wrapper) || !isset($conflictingOptions[$wrapper]) || !\is_array($contextOptions)) {
continue;
}
foreach ($contextOptions as $option => $_) {
if (!\is_string($option) || !\array_key_exists($option, $conflictingOptions[$wrapper])) {
continue;
}
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.12',
\sprintf(
'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.',
$wrapper,
$option,
$conflictingOptions[$wrapper][$option]
)
);
}
}
}
private static function triggerUnsupportedStreamContextOptionDeprecations(array $streamContext): void
{
$unsupportedOptions = self::unsupportedStreamContextOptions($streamContext);
if ($unsupportedOptions === []) {
return;
}
\trigger_deprecation(
'guzzlehttp/guzzle',
'7.12',
\sprintf(
'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.',
\count($unsupportedOptions) === 1 ? '' : 's',
\implode(', ', $unsupportedOptions)
)
);
}
/**
* @return string[]
*/
private static function unsupportedStreamContextOptions(array $streamContext): array
{
$supportedOptions = self::supportedStreamContextOptions();
$conflictingOptions = self::conflictingStreamContextOptions();
$unsupportedOptions = [];
foreach ($streamContext as $wrapper => $contextOptions) {
if (!\is_string($wrapper) || !isset($supportedOptions[$wrapper])) {
if (\is_array($contextOptions)) {
foreach ($contextOptions as $option => $_) {
if (\is_string($wrapper) && \is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) {
continue;
}
$unsupportedOptions[] = \sprintf('stream_context.%s.%s', (string) $wrapper, (string) $option);
}
} else {
$unsupportedOptions[] = \sprintf('stream_context.%s', (string) $wrapper);
}
continue;
}
if (!\is_array($contextOptions)) {
$unsupportedOptions[] = \sprintf('stream_context.%s', $wrapper);
continue;
}
foreach ($contextOptions as $option => $_) {
if (\is_string($option) && isset($conflictingOptions[$wrapper]) && \array_key_exists($option, $conflictingOptions[$wrapper])) {
continue;
}
if (!\is_string($option) || !\array_key_exists($option, $supportedOptions[$wrapper])) {
$unsupportedOptions[] = \sprintf('stream_context.%s.%s', $wrapper, (string) $option);
}
}
}
return $unsupportedOptions;
}
/**
* @return array<string, array<string, true>>
*/
private static function supportedStreamContextOptions(): array
{
return [
'http' => [
'request_fulluri' => true,
],
'socket' => [
'bindto' => true,
'tcp_nodelay' => true,
],
'ssl' => [
'SNI_enabled' => true,
'capture_peer_cert' => true,
'capture_peer_cert_chain' => true,
'ciphers' => true,
'disable_compression' => true,
'no_ticket' => true,
'peer_fingerprint' => true,
'security_level' => true,
'verify_depth' => true,
],
];
}
/**
* @return array<string, array<string, string>>
*/
private static function conflictingStreamContextOptions(): array
{
return [
'http' => [
'content' => 'the request body',
'follow_location' => 'the "allow_redirects" request option',
'header' => 'the request headers',
'max_redirects' => 'the "allow_redirects" request option',
'method' => 'the request method',
'protocol_version' => 'the request protocol version',
'proxy' => 'the "proxy" request option',
'timeout' => 'the "timeout" request option',
],
'ssl' => [
'allow_self_signed' => 'the "verify" request option',
'cafile' => 'the "verify" request option',
'capath' => 'the "verify" request option',
'crypto_method' => 'the "crypto_method" request option',
'local_cert' => 'the "cert" request option',
'local_pk' => 'the "ssl_key" request option',
'max_proto_version' => 'the "crypto_method_max" request option',
'min_proto_version' => 'the "crypto_method" request option',
'passphrase' => 'the "cert" or "ssl_key" request option',
'peer_name' => 'the request URI',
'verify_peer' => 'the "verify" request option',
'verify_peer_name' => 'the "verify" request option',
],
];
}
private function assertTransportSharingSupported(): void
{
if ($this->transportSharingMode === TransportSharing::HANDLER_REQUIRE) {
throw new \InvalidArgumentException('The "transport_sharing" option requires transport sharing, but the stream handler does not support it.');
}
}
private static function isCurlOptionGeneratedByAuth(array $options): bool
{
if (!isset($options['curl']) || !\is_array($options['curl']) || !isset($options['auth'][2]) || !\is_string($options['auth'][2])) {
@ -510,7 +786,7 @@ class StreamHandler
return false;
}
$type = \strtolower($options['auth'][2]);
$type = Psr7\Utils::asciiToLower($options['auth'][2]);
if ($type === 'digest') {
$httpAuth = \defined('CURLAUTH_DIGEST') ? \constant('CURLAUTH_DIGEST') : null;
} elseif ($type === 'ntlm') {
@ -525,13 +801,6 @@ class StreamHandler
&& $options['curl'][\CURLOPT_HTTPAUTH] === $httpAuth;
}
private static function usesDigestAuth(array $options): bool
{
return isset($options['auth'][2])
&& \is_string($options['auth'][2])
&& \strtolower($options['auth'][2]) === 'digest';
}
/**
* @param mixed $value as passed via Request transfer options.
*
@ -583,7 +852,7 @@ class StreamHandler
throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
}
if (\strtoupper($value) !== 'PEM') {
if (Psr7\Utils::asciiToUpper($value) !== 'PEM') {
throw new \InvalidArgumentException(\sprintf('The stream handler only supports "PEM" for the %s request option.', $option));
}
}
@ -591,7 +860,7 @@ class StreamHandler
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): void
private function add_proxy(RequestInterface $request, array &$options, $value, array &$params): bool
{
$uri = null;
@ -610,18 +879,40 @@ class StreamHandler
}
if (!$uri) {
return;
return false;
}
$parsed = $this->parse_proxy($uri);
// PHP extracts and removes only one Proxy-Authorization line for a
// CONNECT tunnel. Serialize exactly one validated first-class value;
// more than one could leave a credential in the tunneled origin
// request. A first-class value, including an empty one, is
// authoritative over Basic credentials embedded in the proxy URI.
$managed = $request->getHeader('Proxy-Authorization');
if (\count($managed) > 1) {
throw new \InvalidArgumentException('The stream handler supports exactly one Proxy-Authorization request header value when a proxy is selected.');
}
if ($managed !== [] && \strpbrk($managed[0], "\r\n") !== false) {
throw new \InvalidArgumentException('Proxy-Authorization request header values must not contain a carriage return or line feed.');
}
$options['http']['proxy'] = $parsed['proxy'];
if ($parsed['auth']) {
if (!isset($options['http']['header'])) {
$options['http']['header'] = [];
}
$options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
if (($managed !== [] || $parsed['auth']) && !isset($options['http']['header'])) {
$options['http']['header'] = '';
}
if ($managed !== []) {
$options['http']['header'] .= "\r\nProxy-Authorization: {$managed[0]}";
return true;
} elseif ($parsed['auth']) {
$options['http']['header'] .= "\r\nProxy-Authorization: {$parsed['auth']}";
return true;
}
return false;
}
/**
@ -631,16 +922,29 @@ class StreamHandler
{
$parsed = \parse_url($url);
if ($parsed !== false && isset($parsed['scheme']) && $parsed['scheme'] === 'http') {
if (isset($parsed['host']) && isset($parsed['port'])) {
$auth = null;
if (isset($parsed['user']) && isset($parsed['pass'])) {
$auth = \base64_encode("{$parsed['user']}:{$parsed['pass']}");
}
// parse_url() misreads scheme-less proxy authorities like
// "user:pass@host"; re-parse only those forms as HTTP.
$schemeLessAuthority = \strpos($url, '://') === false && \strncmp($url, '//', 2) !== 0;
if ($schemeLessAuthority) {
if (\is_array($parsed) && !isset($parsed['scheme']) && isset($parsed['host'], $parsed['port'])) {
$parsed['scheme'] = 'http';
} elseif (
(!\is_array($parsed) || !isset($parsed['host']))
&& (\strpos($url, '@') !== false || \strncmp($url, '[', 1) === 0)
) {
$parsed = \parse_url('http://'.$url);
}
}
if (\is_array($parsed) && isset($parsed['scheme']) && Psr7\Utils::caselessEquals($parsed['scheme'], 'http')) {
if (isset($parsed['host'], $parsed['port'])) {
$user = $parsed['user'] ?? '';
$pass = $parsed['pass'] ?? '';
$auth = ($user !== '' || $pass !== '') ? 'Basic '.\base64_encode("{$user}:{$pass}") : null;
return [
'proxy' => "tcp://{$parsed['host']}:{$parsed['port']}",
'auth' => $auth ? "Basic {$auth}" : null,
'auth' => $auth,
];
}
}
@ -681,6 +985,26 @@ class StreamHandler
throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
}
/**
* @param mixed $value as passed via Request transfer options.
*/
private function add_crypto_method_max(RequestInterface $request, array &$options, $value, array &$params): void
{
$options['ssl']['max_proto_version'] = TlsVersion::streamProtocolVersion('crypto_method_max', $value);
}
private static function assertTlsVersionRangeForOptions(array $options): void
{
if (!isset($options['crypto_method_max'])) {
return;
}
TlsVersion::assertRange(
$options['crypto_method'] ?? null,
$options['crypto_method_max']
);
}
/**
* @param mixed $value as passed via Request transfer options.
*/

View file

@ -0,0 +1,84 @@
<?php
namespace GuzzleHttp\Handler;
/**
* @internal
*/
final class TlsVersion
{
/**
* @param mixed $value
*/
public static function ordinal(string $option, $value): int
{
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
return 10;
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
return 11;
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
return 12;
}
if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return 13;
}
throw new \InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
}
/**
* @param mixed $min
* @param mixed $max
*/
public static function assertRange($min, $max): void
{
if ($min === null || $max === null) {
return;
}
if (self::ordinal('crypto_method_max', $max) < self::ordinal('crypto_method', $min)) {
throw new \InvalidArgumentException('Invalid crypto_method_max request option: maximum TLS version must be greater than or equal to crypto_method');
}
}
/**
* @param mixed $value
*/
public static function streamProtocolVersion(string $option, $value): int
{
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_0', $option);
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_1', $option);
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_2', $option);
}
if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_3', $option);
}
throw new \InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
}
/**
* Resolves a STREAM_CRYPTO_PROTO_* constant. The ssl.max_proto_version
* context option and these constants were added in PHP 7.3.0 (TLS 1.3 in
* 7.4.0); on older runtimes the option cannot be honored, so reject loudly.
*/
private static function requireStreamProto(string $constant, string $option): int
{
if (\defined($constant)) {
/** @var int */
return \constant($constant);
}
throw new \InvalidArgumentException(\sprintf(
'Invalid %s request option: maximum TLS version control is not supported by your version of PHP',
$option
));
}
}

Some files were not shown because too many files have changed in this diff Show more