This commit is contained in:
Javier Casares 2026-08-17 15:50:51 +00:00
commit a80a4aa4f9
20 changed files with 3186001 additions and 9155 deletions

View file

@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
/**
* @internal
*/
final class Clock
{
private function __construct()
{
}
/**
* Returns the current monotonic clock reading in seconds.
*/
public static function now(): float
{
return \hrtime(true) / 1e9;
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,5 +1,7 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use Psr\Http\Message\RequestInterface;
@ -9,6 +11,10 @@ interface CurlFactoryInterface
/**
* Creates a cURL handle resource.
*
* Implementations must return an EasyHandle whose public state properties,
* including the request and sink, contain values compatible with Guzzle's
* cURL handlers.
*
* @param RequestInterface $request Request
* @param array $options Transfer options
*

View file

@ -1,10 +1,16 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\Psr7\DiagnosticValue;
use GuzzleHttp\TransportSharing;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* HTTP handler that uses cURL easy handles as a transport layer.
@ -12,25 +18,23 @@ use Psr\Http\Message\RequestInterface;
* When using the CurlHandler, custom curl options can be specified as an
* associative array of curl option constants mapping to values in the
* **curl** key of the "client" key of the request.
*
* @final
*/
class CurlHandler
final class CurlHandler
{
use NonSerializableTrait;
private const KNOWN_CONSTRUCTOR_OPTIONS = [
'handle_factory' => true,
'transport_sharing' => true,
];
/**
* @var CurlFactoryInterface
*/
private $factory;
private CurlFactoryInterface $factory;
/**
* @var CurlShareHandleState|null
*/
private $shareHandleState;
private bool $ownsFactory;
private bool $closed = false;
private ?CurlShareHandleState $shareHandleState;
/**
* Accepts an associative array of options:
@ -44,7 +48,7 @@ class CurlHandler
{
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));
throw new InvalidArgumentException(\sprintf('Invalid CurlHandler constructor option "%s".', DiagnosticValue::escape((string) $name)));
}
}
@ -55,6 +59,7 @@ class CurlHandler
if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
$this->shareHandleState = null;
$this->factory = $options['handle_factory'];
$this->ownsFactory = false;
return;
}
@ -66,25 +71,92 @@ class CurlHandler
$this->factory = $this->shareHandleState !== null
? new CurlFactory(3, $this->shareHandleState->mode, $this->shareHandleState)
: new CurlFactory(3);
$this->ownsFactory = true;
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
/**
* @return PromiseInterface<ResponseInterface, mixed>
*/
public function __invoke(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options
): PromiseInterface {
$this->assertOpen();
HostValidator::assertRequestHost($request);
if (isset($options['delay'])) {
\usleep($options['delay'] * 1000);
\usleep((int) ($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.
// the transfer runs alone during the blocking curl_exec(), and even
// under persistent transport sharing an in-use connection cannot be
// joined from another multi handle, so it never shares its
// connection with a concurrent transfer.
$easy = $this->factory->create($request, $options);
\curl_exec($easy->handle);
$easy->errno = \curl_errno($easy->handle);
return CurlFactory::finish($this, $easy, $this->factory);
}
/**
* Closes native cURL resources owned by this handler.
*
* After closing, the handler is terminal and must not be reused.
*/
public function close(): void
{
$this->doClose(true);
}
public function __destruct()
{
try {
$this->doClose(false);
} catch (\Throwable $e) {
// Destructors must not throw.
}
}
public function __unserialize(array $data): void
{
$this->closed = true;
throw new \LogicException(static::class.' should never be unserialized');
}
private function assertOpen(): void
{
if ($this->closed) {
// Programmer misuse (reusing a closed handler), not a transfer failure;
// intentionally a LogicException outside the GuzzleException hierarchy.
throw new \BadMethodCallException('Cannot use the cURL handler after it has been closed.');
}
}
private function doClose(bool $explicit): void
{
if ($this->closed) {
return;
}
$this->closed = true;
try {
if ($this->ownsFactory && $this->factory instanceof CurlFactory) {
$this->factory->close();
}
} catch (\Throwable $e) {
if ($explicit) {
throw $e;
}
} finally {
$this->shareHandleState = null;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,11 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\TransportSharing;
/**
@ -9,18 +13,17 @@ use GuzzleHttp\TransportSharing;
*/
final class CurlShareHandleState
{
use NonSerializableTrait;
/**
* @var resource|\CurlShareHandle|null
* @var resource|\CurlShareHandle|\CurlSharePersistentHandle|null
*/
public $handle;
/**
* @var string
*/
public $mode;
public string $mode;
/**
* @param resource|\CurlShareHandle|null $handle
* @param resource|\CurlShareHandle|\CurlSharePersistentHandle|null $handle
*/
private function __construct(string $mode, $handle)
{
@ -46,7 +49,15 @@ final class CurlShareHandleState
return self::createHandlerShareOrNull($mode);
}
return self::createHandlerShare($mode);
if ($mode === TransportSharing::HANDLER_REQUIRE) {
return self::createHandlerShare($mode);
}
if ($mode === TransportSharing::PERSISTENT_PREFER) {
return self::createPersistentShareOrFallback();
}
return self::createPersistentShare($mode);
}
/**
@ -62,11 +73,16 @@ final class CurlShareHandleState
return TransportSharing::NONE;
}
if ($sharing === TransportSharing::HANDLER_PREFER || $sharing === TransportSharing::HANDLER_REQUIRE) {
if (
$sharing === TransportSharing::HANDLER_PREFER
|| $sharing === TransportSharing::HANDLER_REQUIRE
|| $sharing === TransportSharing::PERSISTENT_PREFER
|| $sharing === TransportSharing::PERSISTENT_REQUIRE
) {
return $sharing;
}
throw new \InvalidArgumentException(\sprintf(
throw new InvalidArgumentException(\sprintf(
'The "%s" option must be null or a GuzzleHttp\\TransportSharing::* constant; received %s.',
$option,
\get_debug_type($sharing)
@ -80,11 +96,11 @@ final class CurlShareHandleState
}
$mode = self::normalizeMode($options['transport_sharing'] ?? null, 'transport_sharing');
if ($mode !== TransportSharing::HANDLER_REQUIRE) {
if (!\in_array($mode, [TransportSharing::HANDLER_REQUIRE, TransportSharing::PERSISTENT_REQUIRE], true)) {
return;
}
throw new \InvalidArgumentException(\sprintf(
throw new InvalidArgumentException(\sprintf(
'The "transport_sharing" %s option cannot require sharing with a custom "handle_factory" because Guzzle cannot ensure that the custom factory applies CURLOPT_SHARE.',
$handlerName
));
@ -102,7 +118,7 @@ final class CurlShareHandleState
private static function createHandlerShare(string $mode): self
{
if (!\function_exists('curl_share_init') || !\function_exists('curl_share_setopt')) {
throw new \InvalidArgumentException('The "transport_sharing" option requires cURL share support.');
throw new InvalidArgumentException('The "transport_sharing" option requires cURL share support.');
}
self::requireCurlConstant('CURLOPT_SHARE');
@ -115,11 +131,11 @@ final class CurlShareHandleState
try {
$success = curl_share_setopt($handle, $shareOption, $lock);
} catch (\Throwable $e) {
throw new \InvalidArgumentException('Unable to configure cURL share handle: '.$e->getMessage(), 0, $e);
throw new InvalidArgumentException('Unable to configure cURL share handle: '.$e->getMessage(), 0, $e);
}
if (!$success) {
throw new \InvalidArgumentException(\sprintf('Unable to configure cURL share handle with lock data %d.', $lock));
throw new InvalidArgumentException(\sprintf('Unable to configure cURL share handle with lock data %d.', $lock));
}
}
} catch (\Throwable $e) {
@ -131,6 +147,54 @@ final class CurlShareHandleState
return new self($mode, $handle);
}
private static function createPersistentShareOrFallback(): ?self
{
if (self::supportsPersistentShare()) {
try {
return self::createPersistentShare(TransportSharing::PERSISTENT_PREFER);
} catch (\Throwable $e) {
// Fall back to handler-lifetime best effort below.
}
}
return self::createHandlerShareOrNull(TransportSharing::HANDLER_PREFER);
}
private static function createPersistentShare(string $mode): self
{
CurlVersion::ensureConnectionSharingSupported();
CurlVersion::ensureSslSessionSharingSupported();
if (!self::supportsPersistentShare()) {
throw new InvalidArgumentException('The "transport_sharing" option requires persistent cURL share handle support.');
}
self::requireCurlConstant('CURLOPT_SHARE');
try {
$handle = curl_share_init_persistent(self::persistentLocks());
} catch (\Throwable $e) {
throw new InvalidArgumentException(
'Unable to create persistent cURL share handle: '.$e->getMessage(),
0,
$e
);
}
return new self($mode, $handle);
}
private static function supportsPersistentShare(): bool
{
return CurlVersion::supportsConnectionSharing()
&& CurlVersion::supportsSslSessionSharing()
&& \function_exists('curl_share_init_persistent')
&& \class_exists('CurlSharePersistentHandle')
&& \defined('CURL_LOCK_DATA_DNS')
&& \defined('CURL_LOCK_DATA_CONNECT')
&& \defined('CURL_LOCK_DATA_SSL_SESSION');
}
/**
* @return int[]
*/
@ -153,10 +217,22 @@ final class CurlShareHandleState
return $locks;
}
/**
* @return int[]
*/
private static function persistentLocks(): array
{
return [
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
self::requireCurlConstant('CURL_LOCK_DATA_CONNECT'),
self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'),
];
}
private static function requireCurlConstant(string $constant): int
{
if (!\defined($constant)) {
throw new \InvalidArgumentException(\sprintf(
throw new InvalidArgumentException(\sprintf(
'The "transport_sharing" option requires %s, but it is not available in the installed PHP cURL extension.',
$constant
));
@ -164,7 +240,7 @@ final class CurlShareHandleState
$value = \constant($constant);
if (!\is_int($value)) {
throw new \InvalidArgumentException(\sprintf('The cURL constant %s must resolve to an integer.', $constant));
throw new InvalidArgumentException(\sprintf('The cURL constant %s must resolve to an integer.', $constant));
}
return $value;

View file

@ -1,20 +1,22 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\InvalidArgumentException;
use Psr\Http\Message\RequestInterface;
/**
* @internal
*/
final class CurlVersion
{
private const MIN_VERSION = '7.21.2';
private const TLS_12_VERSION = '7.34.0';
private const MIN_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
@ -37,23 +39,43 @@ final class CurlVersion
// 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
// that, a required HTTP/2 request could silently be sent over a reused
// HTTP/1.1 connection.
private const REQUIRED_HTTP2_MULTIPLEX_VERSION = '8.14.0';
// Version-aware connection reuse matching arrived in libcurl 8.13.0 with
// an HTTP/3-only mask for CURL_HTTP_VERSION_3ONLY transfers; below that,
// a required HTTP/3 request could silently ride a reused HTTP/2
// connection.
private const REQUIRED_MULTIPLEX_VERSION = '8.14.0';
private const REQUIRED_HTTP3_MULTIPLEX_VERSION = '8.13.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';
// The 7.52.0 TLS rework also shipped verification flaws in exactly this
// path (CVE-2017-2629, CVE-2017-7468); the latter affects 7.52.0-7.53.1
// and was fixed in 7.54.0, so TLS to a proxy is only trusted from there.
private const HTTPS_PROXY_VERSION = '7.54.0';
// HTTP/3 arrived in libcurl 7.66.0, but CURL_HTTP_VERSION_3ONLY only
// exists from 7.88.0; requiring it keeps every HTTP/3-capable runtime
// able to pin HTTP/3 with no downgrade.
private const HTTP_3_VERSION = '7.88.0';
private const PROTOCOLS_STR_VERSION = '7.85.0';
private const HANDLER_SHARING_VERSION = '7.35.0';
private const SSL_SESSION_SHARING_VERSION = '8.6.0';
private const CONNECTION_SHARING_VERSION = '8.12.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.
// session, and cookie data, never connections. This is libcurl's raw
// capability floor for the opaque share safeguards; Guzzle-managed
// connection sharing is separately gated by CONNECTION_SHARING_VERSION.
private const SHARE_CONNECTION_CACHE_VERSION = '7.57.0';
// curl 7.83.1 added proxy TLS-SRP to the connection-reuse match
@ -73,6 +95,11 @@ final class CurlVersion
private const PROXY_HEADER_SEPARATION_VERSION = '7.37.0';
// CURLOPT_SUPPRESS_CONNECT_HEADERS arrived in curl 7.54.0; proxy CONNECT
// tunneling is gated on it so the proxy's interim reply can never surface
// as a phantom response on any build that can tunnel.
private const PROXY_TUNNEL_VERSION = '7.54.0';
/**
* @var array{version: string, features: int}|false|null
*/
@ -84,132 +111,114 @@ final class CurlVersion
public static function supportsCurlHandler(): bool
{
$version = self::getVersion();
$versionInfo = self::getVersionInfo();
return $version !== null && \version_compare($version, self::MIN_VERSION, '>=');
}
public static function supportsTls12(): bool
{
$version = self::getVersion();
return self::supportsSsl()
return \defined('CURL_VERSION_SSL')
&& \defined('CURL_SSLVERSION_TLSv1_2')
&& $version !== null
&& \version_compare($version, self::TLS_12_VERSION, '>=');
&& \defined('CURLMOPT_MAX_HOST_CONNECTIONS')
&& \defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')
&& null !== $versionInfo
&& version_compare($versionInfo['version'], self::MIN_VERSION, '>=')
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
}
public static function supportsTls13(): bool
{
$version = self::getVersion();
$version = self::get();
return self::supportsSsl()
&& \defined('CURL_SSLVERSION_TLSv1_3')
&& $version !== null
&& \version_compare($version, self::TLS_13_VERSION, '>=');
return \defined('CURL_SSLVERSION_TLSv1_3')
&& null !== $version
&& version_compare($version, self::TLS_13_VERSION, '>=');
}
public static function supportsMultiplex(): bool
{
$version = self::get();
return \defined('CURLOPT_PIPEWAIT')
&& null !== $version
&& version_compare($version, self::MULTIPLEX_VERSION, '>=');
}
public static function supportsHttpVersionReuseMatching(): bool
{
$version = self::get();
if (null === $version || 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 supportsRequiredHttp2Multiplex(): bool
{
$version = self::get();
return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')
&& null !== $version
&& self::supportsHttp2()
&& version_compare($version, self::REQUIRED_HTTP2_MULTIPLEX_VERSION, '>=');
}
public static function supportsHttp2(): bool
{
$versionInfo = self::getVersionInfo();
return self::supportsTls12()
&& \defined('CURL_VERSION_HTTP2')
&& $versionInfo !== null
// Requiring dependable CURLOPT_PIPEWAIT support keeps waiting from
// ever being silently unavailable where HTTP/2 works.
return \defined('CURL_VERSION_HTTP2')
&& null !== $versionInfo
&& self::supportsMultiplex()
&& 0 !== (\CURL_VERSION_HTTP2 & $versionInfo['features']);
}
public static function supportsMultiplex(): bool
public static function supportsHttp3(): 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, '<')) {
if (!\defined('CURL_VERSION_HTTP3') || !\defined('CURL_HTTP_VERSION_3') || !\defined('CURL_HTTP_VERSION_3ONLY')) {
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;
$versionInfo = self::getVersionInfo();
if (null === $versionInfo || version_compare($versionInfo['version'], self::HTTP_3_VERSION, '<')) {
return false;
}
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
));
return 0 !== ((int) \constant('CURL_VERSION_HTTP3') & $versionInfo['features']);
}
public static function supportsRequiredMultiplex(): bool
public static function supportsRequiredHttp3Multiplex(): bool
{
$version = self::getVersion();
$version = self::get();
return \defined('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE')
&& $version !== null
&& self::supportsHttp2()
&& \version_compare($version, self::REQUIRED_MULTIPLEX_VERSION, '>=');
return self::supportsHttp3()
&& null !== $version
&& version_compare($version, self::REQUIRED_HTTP3_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']);
return \defined('CURL_VERSION_HTTPS_PROXY')
&& null !== $versionInfo
&& version_compare($versionInfo['version'], self::HTTPS_PROXY_VERSION, '>=')
&& 0 !== (\CURL_VERSION_HTTPS_PROXY & $versionInfo['features']);
}
public static function supportsHandlerSharing(): bool
{
$version = self::getVersion();
$version = self::get();
return $version !== null && \version_compare($version, self::HANDLER_SHARING_VERSION, '>=');
return null !== $version
&& version_compare($version, self::HANDLER_SHARING_VERSION, '>=');
}
public static function ensureHandlerSharingSupported(): void
{
if (!self::supportsHandlerSharing()) {
throw new \InvalidArgumentException(\sprintf(
throw new InvalidArgumentException(\sprintf(
'The "transport_sharing" option requires libcurl %s or higher for cURL share handles.',
self::HANDLER_SHARING_VERSION
));
@ -218,81 +227,142 @@ final class CurlVersion
public static function supportsSslSessionSharing(): bool
{
$version = self::getVersion();
$versionInfo = self::getVersionInfo();
return self::supportsSsl()
&& $version !== null
&& \version_compare($version, self::SSL_SESSION_SHARING_VERSION, '>=');
return \defined('CURL_VERSION_SSL')
&& null !== $versionInfo
&& version_compare($versionInfo['version'], self::SSL_SESSION_SHARING_VERSION, '>=')
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
}
public static function ensureSslSessionSharingSupported(): void
{
if (!self::supportsSslSessionSharing()) {
throw new \InvalidArgumentException(\sprintf(
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 supportsConnectionSharing(): bool
{
$version = self::get();
return null !== $version
&& version_compare($version, self::CONNECTION_SHARING_VERSION, '>=');
}
public static function ensureConnectionSharingSupported(): void
{
if (!self::supportsConnectionSharing()) {
throw new InvalidArgumentException(\sprintf(
'The "transport_sharing" option requires libcurl %s or higher for persistent connection sharing.',
self::CONNECTION_SHARING_VERSION
));
}
}
public static function supportsShareConnectionCaches(): bool
{
$version = self::getVersion();
$version = self::get();
// 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, '>=');
return null === $version
|| version_compare($version, self::SHARE_CONNECTION_CACHE_VERSION, '>=');
}
public static function supportsProxyTlsCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
$version = self::get();
return $version !== null
&& \version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>=');
return null !== $version
&& version_compare($version, self::PROXY_TLS_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsProxyCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
$version = self::get();
return $version !== null
&& \version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>=');
return null !== $version
&& version_compare($version, self::PROXY_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsSocksProxyCredentialAwareConnectionReuse(): bool
{
$version = self::getVersion();
$version = self::get();
return $version !== null
&& \version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>=');
return null !== $version
&& version_compare($version, self::SOCKS_PROXY_CREDENTIAL_REUSE_VERSION, '>=');
}
public static function supportsProxyHeaderSeparation(): bool
{
$version = self::getVersion();
$version = self::get();
return $version !== null
&& \version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=')
return null !== $version
&& version_compare($version, self::PROXY_HEADER_SEPARATION_VERSION, '>=')
&& \defined('CURLOPT_PROXYHEADER')
&& \defined('CURLOPT_HEADEROPT')
&& \defined('CURLHEADER_SEPARATE');
}
private static function supportsSsl(): bool
public static function supportsProtocolsStr(): bool
{
$versionInfo = self::getVersionInfo();
$version = self::get();
return \defined('CURL_VERSION_SSL')
&& $versionInfo !== null
&& 0 !== (\CURL_VERSION_SSL & $versionInfo['features']);
return \defined('CURLOPT_PROTOCOLS_STR')
&& null !== $version
&& version_compare($version, self::PROTOCOLS_STR_VERSION, '>=');
}
public static function getVersion(): ?string
public static function supportsProxyTunneling(): bool
{
$version = self::get();
return \defined('CURLOPT_SUPPRESS_CONNECT_HEADERS')
&& null !== $version
&& version_compare($version, self::PROXY_TUNNEL_VERSION, '>=');
}
public static function ensureSupported(
#[\SensitiveParameter]
RequestInterface $request
): void {
if (self::supportsCurlHandler()) {
return;
}
$version = self::get();
if (null === $version || version_compare($version, self::MIN_VERSION, '<')) {
throw new ConnectException(\sprintf(
'cURL %s or higher is required by the cURL handler; %s is installed.',
self::MIN_VERSION,
$version ?? 'an unknown version'
), $request);
}
if (!\defined('CURL_SSLVERSION_TLSv1_2')) {
throw new ConnectException(\sprintf(
'The PHP cURL extension must be built against cURL %s or higher to use the cURL handler.',
self::MIN_VERSION
), $request);
}
if (!\defined('CURLMOPT_MAX_HOST_CONNECTIONS') || !\defined('CURLMOPT_MAX_TOTAL_CONNECTIONS')) {
throw new ConnectException('The PHP cURL extension must expose CURLMOPT_MAX_HOST_CONNECTIONS and CURLMOPT_MAX_TOTAL_CONNECTIONS to use the cURL handler.', $request);
}
throw new ConnectException('The cURL handler requires libcurl SSL support.', $request);
}
private static function get(): ?string
{
$versionInfo = self::getVersionInfo();
return $versionInfo === null ? null : $versionInfo['version'];
return null === $versionInfo ? null : $versionInfo['version'];
}
/**
@ -300,7 +370,7 @@ final class CurlVersion
*/
private static function getVersionInfo(): ?array
{
if (self::$versionInfo === null) {
if (null === self::$versionInfo) {
if (!\function_exists('curl_version')) {
self::$versionInfo = false;
} else {
@ -317,6 +387,6 @@ final class CurlVersion
}
}
return self::$versionInfo === false ? null : self::$versionInfo;
return false === self::$versionInfo ? null : self::$versionInfo;
}
}

View file

@ -0,0 +1,114 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\Exception\TimeoutException;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
/**
* Decorates the transport stream of a buffered response so every read
* observes the wall-clock deadline of the "timeout" request option.
*
* The transport resource must be in non-blocking mode: PHP's filtered
* stream reads (chunked and compressed responses) otherwise block until
* the full requested length arrives, so a deadline check between reads
* never runs while a server keeps sending small pieces of data. Reads
* return whatever bytes are available and poll briefly for more, so the
* deadline is checked between packets rather than between buffers. The
* wait is a bounded sleep because stream_select() cannot watch a stream
* that carries a filter.
*
* @internal
*/
final class DeadlineSourceStream implements StreamInterface
{
use NonSerializableTrait;
use StreamDecoratorTrait;
private const POLL_INTERVAL = 0.05;
private StreamInterface $stream;
private float $deadline;
private ?float $readTimeout;
private bool $timedOut = false;
/**
* @param StreamInterface $stream Transport stream in non-blocking mode.
* @param float $deadline Deadline based on Clock::now().
* @param float|null $readTimeout Optional idle timeout per read, in seconds.
*/
public function __construct(StreamInterface $stream, float $deadline, ?float $readTimeout)
{
$this->stream = $stream;
$this->deadline = $deadline;
$this->readTimeout = $readTimeout;
}
public function read(int $length): string
{
$idleStart = null;
while (true) {
$remaining = $this->deadline - Clock::now();
if ($remaining <= 0) {
$this->timedOut = true;
throw new TimeoutException('Unable to read from stream: timed out');
}
$data = $this->stream->read($length);
if ($data !== '') {
return $data;
}
if ($this->stream->eof()) {
return '';
}
$now = Clock::now();
if ($idleStart === null) {
$idleStart = $now;
}
if ($this->readTimeout !== null && $now - $idleStart >= $this->readTimeout) {
$this->timedOut = true;
throw new TimeoutException('Unable to read from stream: timed out');
}
$wait = \min($remaining, self::POLL_INTERVAL);
if ($this->readTimeout !== null) {
$wait = \min($wait, $this->readTimeout - ($now - $idleStart));
}
\usleep((int) \ceil($wait * 1e6));
}
}
/**
* Reports the deadline timeout through the timed_out metadata: reads on
* a decoding layer above this stream surface as a generic read failure,
* and its timeout recovery consults this stream's metadata to classify
* the failure. The transport itself never reports timed_out while in
* non-blocking mode.
*
* @return mixed
*/
public function getMetadata(?string $key = null)
{
if ($key === 'timed_out') {
return $this->timedOut || $this->stream->getMetadata($key) === true;
}
$metadata = $this->stream->getMetadata($key);
if ($key === null && \is_array($metadata) && $this->timedOut) {
$metadata['timed_out'] = true;
}
return $metadata;
}
}

View file

@ -1,10 +1,20 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Exception\ResponseException;
use GuzzleHttp\Exception\ResponseTransferException;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\DiagnosticValue;
use GuzzleHttp\Psr7\Exception\TimeoutException;
use GuzzleHttp\Psr7\HttpFactory;
use GuzzleHttp\RequestOptions;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseFactoryInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
@ -15,74 +25,118 @@ use Psr\Http\Message\StreamInterface;
*/
final class EasyHandle
{
use NonSerializableTrait;
/**
* @var resource|\CurlHandle cURL resource
*/
public $handle;
/**
* @var StreamInterface Where data is being written
*/
public $sink;
public StreamInterface $sink;
public RequestInterface $request;
/**
* @var array Received HTTP headers so far
* @var list<string> Received HTTP headers so far
*/
public $headers = [];
public array $headers = [];
/**
* @var array Valid trailer lines, retained only when an on_trailers
* callback is configured
* @var list<string> Valid trailer lines, retained only when an
* on_trailers callback is configured
*/
public $trailers = [];
public array $trailers = [];
/**
* @var bool Whether this handle was configured with CURLOPT_PIPEWAIT
*/
public $usesPipewait = false;
public bool $usesPipewait = false;
/**
* @var ResponseInterface|null Received response (if any)
*/
public $response;
/**
* @var RequestInterface Request being sent
*/
public $request;
public ?ResponseInterface $response = null;
/**
* @var array Request options
*/
public $options = [];
public array $options = [];
/**
* @var int cURL error number (if any)
*/
public $errno = 0;
public int $errno = 0;
/**
* @var string|null Effective CURLOPT_PROXY value the handle was created with (if any)
*/
public $effectiveProxy;
public ?string $effectiveProxy = null;
/**
* 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;
public ?string $proxyTunnelSignature = null;
/**
* @var \Throwable|null Exception during on_headers (if any)
*/
public $onHeadersException;
public ?\Throwable $onHeadersException = null;
/**
* @var \Throwable|null Exception during progress callback (if any)
*/
public ?\Throwable $progressException = null;
/**
* @var bool Whether the progress callback requested abort
*/
public bool $progressAborted = false;
/**
* @var \Throwable|null Exception during createResponse (if any)
*/
public $createResponseException;
public ?\Throwable $createResponseException = null;
/**
* @var ResponseException|null Response header failure, if any.
*/
public ?ResponseException $responseHeaderException = null;
/**
* @var TimeoutException|null Exception during request body read timeout.
*/
public ?TimeoutException $bodyReadTimeoutException = null;
/**
* @var \Throwable|null Exception during request body read.
*/
public ?\Throwable $bodyReadException = null;
/**
* @var TimeoutException|null Exception during response sink write timeout.
*/
public ?TimeoutException $sinkWriteTimeoutException = null;
/**
* @var \Throwable|null Exception during response sink write.
*/
public ?\Throwable $sinkWriteException = null;
/**
* @var bool Whether the response sink accepted a different byte count.
*/
public bool $sinkWriteIncomplete = false;
/**
* @var int Number of response body bytes accepted by the sink.
*/
public int $responseBodyBytes = 0;
/**
* @var \OverflowException|null Unrepresentable response body size or byte count.
*/
public ?\OverflowException $responseBodySizeException = null;
/**
* Attach a response to the easy handle based on the received headers.
@ -93,46 +147,99 @@ final class EasyHandle
public function createResponse(): void
{
$this->response = null;
$this->responseBodyBytes = 0;
$this->responseBodySizeException = null;
$this->responseHeaderException = null;
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers);
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
// Non-101 informational responses precede the final response. Do not
// expose them as the response for a transfer that ends before the final
// response arrives. 101 switches protocol and is kept as terminal.
if ($status < 200 && $status !== 101) {
return;
}
if (isset($this->options['decode_content']) && $this->options['decode_content'] !== false && isset($normalizedKeys['content-encoding'])) {
$framingFailure = null;
try {
$declaredLength = HeaderProcessor::validateResponseFraming($this->request->getMethod(), $status, $headers);
HeaderProcessor::assertContentLengthWithinPlatformLimit($declaredLength);
} catch (\RuntimeException $e) {
$framingFailure = $e;
}
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
$decodeContent = $this->options['decode_content'] ?? false;
if ($framingFailure === null && $decodeContent !== false && isset($normalizedKeys['content-encoding'])) {
$headers['x-encoded-content-encoding'] = $headers[$normalizedKeys['content-encoding']];
unset($headers[$normalizedKeys['content-encoding']]);
if (isset($normalizedKeys['content-length'])) {
$headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
$encodedContentLength = HeaderProcessor::removeHeader('Content-Length', $headers);
if ($encodedContentLength !== []) {
$headers['x-encoded-content-length'] = $encodedContentLength;
$bodyLength = (int) $this->sink->getSize();
try {
$bodyLength = $this->sink->getSize();
} catch (\Exception $e) {
$bodyLength = null;
}
if ($bodyLength) {
$headers[$normalizedKeys['content-length']] = [(string) $bodyLength];
} else {
unset($headers[$normalizedKeys['content-length']]);
$headers['Content-Length'] = [(string) $bodyLength];
}
}
}
// Attach a response to the easy handle with the parsed headers.
$this->response = new Response(
$status,
$headers,
$this->sink,
$ver,
$reason
);
// Attach a response to the easy handle with the parsed headers. Any
// exception propagates to the caller (CurlFactory), which records it as
// the createResponseException — do not catch it here.
$responseFactory = self::requireResponseFactory($this->options[RequestOptions::RESPONSE_FACTORY] ?? new HttpFactory());
$response = $responseFactory->createResponse($status, $reason ?? '')->withProtocolVersion($ver);
foreach ($headers as $name => $value) {
$response = $response->withAddedHeader((string) $name, $value);
}
$this->response = $response->withBody($this->sink);
if ($framingFailure instanceof \OverflowException) {
$this->responseHeaderException = new ResponseException(
$framingFailure->getMessage(),
$this->request,
$this->response,
$framingFailure
);
} elseif ($framingFailure !== null) {
$this->responseHeaderException = new ResponseTransferException(
$framingFailure->getMessage(),
$this->request,
$this->response,
$framingFailure
);
}
}
/**
* @param mixed $factory
*/
private static function requireResponseFactory($factory): ResponseFactoryInterface
{
if (!$factory instanceof ResponseFactoryInterface) {
throw new InvalidArgumentException(\sprintf(
'%s must be an instance of %s',
RequestOptions::RESPONSE_FACTORY,
ResponseFactoryInterface::class
));
}
return $factory;
}
/**
* @param string $name
*
* @return void
*
* @throws \BadMethodCallException
*/
public function __get($name)
public function __get(string $name): void
{
$msg = $name === 'handle' ? 'The EasyHandle has been released' : 'Invalid property: '.$name;
$msg = $name === 'handle'
? 'The EasyHandle has been released'
: \sprintf('Invalid property: %s', DiagnosticValue::escape($name));
throw new \BadMethodCallException($msg);
}
}

View file

@ -0,0 +1,83 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7\StreamDecoratorTrait;
use Psr\Http\Message\StreamInterface;
/**
* Tracks encoded response bytes beneath a content-decoding stream.
*
* Reads are bounded by a positive, representable Content-Length so a decoder
* cannot consume bytes beyond the response message boundary.
*
* @internal
*/
final class EncodedBodyStream implements StreamInterface
{
use NonSerializableTrait;
use StreamDecoratorTrait;
private StreamInterface $stream;
private ?int $limit;
private int $bytesRead = 0;
public function __construct(StreamInterface $stream, string $declaredLength)
{
$this->stream = $stream;
$limit = HeaderProcessor::contentLengthToInt($declaredLength);
$this->limit = $limit !== null && $limit > 0 ? $limit : null;
}
public function eof(): bool
{
return ($this->limit !== null && $this->bytesRead >= $this->limit)
|| $this->stream->eof();
}
public function isSeekable(): bool
{
return false;
}
public function seek(int $offset, int $whence = \SEEK_SET): void
{
throw new \RuntimeException('Cannot seek a stream while tracking encoded response bytes');
}
public function read(int $length): string
{
if ($length < 0) {
throw new \RuntimeException('Length parameter cannot be negative');
}
if ($this->limit !== null) {
$remaining = $this->limit - $this->bytesRead;
if ($remaining === 0) {
return '';
}
$length = \min($length, $remaining);
}
$data = $this->stream->read($length);
$this->bytesRead = TransferByteCounter::add(
$this->bytesRead,
\strlen($data),
'Response body exceeds the maximum integer size supported on this platform'
);
return $data;
}
public function getBytesRead(): int
{
return $this->bytesRead;
}
}

View file

@ -1,7 +1,10 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Psr7;
use GuzzleHttp\Utils;
/**
@ -9,6 +12,10 @@ use GuzzleHttp\Utils;
*/
final class HeaderProcessor
{
private function __construct()
{
}
/**
* Returns the HTTP version, status code, reason phrase, and headers.
*
@ -32,29 +39,41 @@ final class HeaderProcessor
}
$parts = \explode(' ', $statusLine, 3);
$version = \explode('/', $parts[0])[1] ?? null;
$protocol = $parts[0];
if ($version === null) {
if (!Psr7\Utils::caselessEquals(\substr($protocol, 0, 5), 'HTTP/')) {
throw new \RuntimeException('HTTP version missing from header data');
}
$version = \substr($protocol, 5);
if (!\preg_match('/^\d+(?:\.\d+)?$/D', $version)) {
throw new \RuntimeException('HTTP version is invalid');
}
$status = $parts[1] ?? null;
if ($status === null) {
throw new \RuntimeException('HTTP status code missing from header data');
}
if (!\preg_match('/^\d{3}$/D', $status)) {
if (!\preg_match('/^[1-5]\d{2}$/D', $status)) {
throw new \RuntimeException('HTTP status code is invalid');
}
$reason = $parts[2] ?? null;
if ($reason !== null && !\preg_match('/^[\x09\x20-\x7E\x80-\xFF]*$/D', $reason)) {
throw new \RuntimeException('HTTP reason phrase is invalid');
}
foreach ($headers as $header) {
if (\strpos($header, ':') === false) {
throw new \RuntimeException('HTTP header line is invalid');
}
}
return [$version, (int) $status, $parts[2] ?? null, Utils::headersFromLines($headers)];
return [$version, (int) $status, $reason, Utils::headersFromLines($headers)];
}
public static function isStatusLineCandidate(string $line): bool
@ -77,6 +96,138 @@ final class HeaderProcessor
return \preg_match('/^[\x20\x09\x21-\x7E\x80-\xFF]*(?:\r\n|\r|\n)?$/D', \trim($parts[1], " \t")) === 1;
}
/**
* Returns a normalized decimal Content-Length, or null when absent.
*
* @param string[] $values
*
* @throws \RuntimeException when Content-Length is malformed or conflicting.
*/
public static function parseContentLength(array $values): ?string
{
$length = null;
foreach ($values as $value) {
foreach (\explode(',', $value) as $part) {
$part = \trim($part, " \t");
if (\preg_match('/^[0-9]+$/D', $part) !== 1) {
throw new \RuntimeException('value is not a non-negative decimal integer');
}
$part = \ltrim($part, '0');
$part = $part === '' ? '0' : $part;
if ($length !== null && $part !== $length) {
throw new \RuntimeException('values conflict');
}
$length = $part;
}
}
if ($length === null) {
return null;
}
return $length;
}
public static function contentLengthToInt(?string $length): ?int
{
if ($length === null) {
return null;
}
$max = (string) \PHP_INT_MAX;
if (
\strlen($length) > \strlen($max)
|| (\strlen($length) === \strlen($max) && \strcmp($length, $max) > 0)
) {
return null;
}
return (int) $length;
}
public static function assertContentLengthWithinPlatformLimit(?string $length): void
{
if ($length === null || self::contentLengthToInt($length) !== null) {
return;
}
throw new \OverflowException('Content-Length exceeds the maximum integer size supported on this platform');
}
/**
* Validates response framing and returns its normalized Content-Length.
* Returns null when absent or when ordinary body framing does not apply.
*
* @param array<string, string[]> $headers
*
* @throws \RuntimeException when Content-Length is malformed, conflicting,
* or combined with Transfer-Encoding
*/
public static function validateResponseFraming(
string $method,
int $status,
array $headers
): ?string {
if (!self::responseCanHaveBody($method, $status)) {
return null;
}
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
$contentLength = self::removeHeader('Content-Length', $headers);
try {
$length = self::parseContentLength($contentLength);
} catch (\RuntimeException $e) {
throw new \RuntimeException('Invalid Content-Length response header: '.$e->getMessage(), 0, $e);
}
if ($length !== null && isset($normalizedKeys['transfer-encoding'])) {
throw new \RuntimeException('A response must not contain both Content-Length and Transfer-Encoding');
}
return $length;
}
/**
* Removes every case-insensitive occurrence of a header and returns all
* removed values in their original field order.
*
* @param array<string, string[]> $headers
*
* @return string[] Removed values across all header-name casings
*/
public static function removeHeader(string $name, array &$headers): array
{
$values = [];
foreach ($headers as $key => $headerValues) {
if (Psr7\Utils::caselessEquals((string) $key, $name)) {
\array_push($values, ...$headerValues);
unset($headers[$key]);
}
}
return $values;
}
/**
* Whether a response uses ordinary body framing. A response to HEAD, a
* response with a 1xx, 204, or 304 status code, or a 2xx response to
* CONNECT never has a body, whatever its framing headers claim. A 205
* remains subject to framing even though its semantics require no content.
*/
public static function responseCanHaveBody(string $method, int $status): bool
{
return $method !== 'HEAD'
&& !($method === 'CONNECT' && $status >= 200 && $status < 300)
&& $status >= 200
&& $status !== 204
&& $status !== 304;
}
/**
* @param non-empty-list<string> $headers
*

View file

@ -1,8 +1,11 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7;
use Psr\Http\Message\RequestInterface;
/**
@ -20,128 +23,67 @@ final class HostValidator
/**
* Asserts that a request names one unambiguous network host.
*
* The URI host and every Host header value must use printable ASCII without
* percent escapes. The URI host must also exclude authority delimiters and
* numeric-looking parts followed by trailing dots. Handlers reparse the URI
* but send the Host header as given, so ambiguous spellings can name
* different connection and request hosts.
* A handler reparses the URI but sends the Host header as given. The URI
* host must therefore be printable ASCII, free of percent escapes, a valid
* RFC 3986 host, and not numeric-looking parts followed by trailing dots.
* Every Host header value must be printable ASCII.
*
* @throws RequestException
*/
public static function assertRequestHost(RequestInterface $request): void
{
$host = $request->getUri()->getHost();
self::assertUriHostValue($host, $request);
self::assertNoAuthorityDelimiter($host, $request);
self::assertNotADottedAddress($host, $request);
public static function assertRequestHost(
#[\SensitiveParameter]
RequestInterface $request
): void {
self::assertUriHost($request->getUri()->getHost(), $request);
foreach ($request->getHeader('Host') as $value) {
self::assertHostHeaderValue((string) $value, $request);
self::assertPrintableAscii((string) $value, 'The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request);
}
}
/**
* @throws RequestException
*/
private static function assertUriHostValue(string $value, RequestInterface $request): void
{
if (!self::isPrintableAscii($value)) {
throw new RequestException(\sprintf('The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', self::escape($value)), $request);
}
if (\strpos($value, '%') !== false) {
throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler can decode it and then connect to a host that differs from the one the request names.', self::escape($value)), $request);
}
}
/**
* The Host header is sent rather than reparsed for the connection, so its
* diagnostics describe a request authority the caller did not write.
* Only the URI host is reparsed for the connection. A Host header is sent
* verbatim and may carry a port, brackets, and an RFC 6874 zone identifier.
*
* @throws RequestException
*/
private static function assertHostHeaderValue(string $value, RequestInterface $request): void
{
if (!self::isPrintableAscii($value)) {
throw new RequestException(\sprintf('The request Host header "%s" must contain only printable ASCII characters, because an intermediary or an origin server can otherwise read it as an authority that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', self::escape($value)), $request);
private static function assertUriHost(
string $host,
#[\SensitiveParameter]
RequestInterface $request
): void {
self::assertPrintableAscii($host, 'The request URI host "%s" must contain only printable ASCII characters, because a handler can otherwise connect to a host that differs from the one the request names. An internationalized host name has an A-label form that this rule accepts.', $request);
if (\strpos($host, '%') !== false) {
throw new RequestException(\sprintf('The request URI host "%s" must not contain a percent escape, because a handler decodes it and can then connect to a host that differs from the one the request names.', self::escape($host)), $request);
}
if (\strpos($value, '%') !== false) {
throw new RequestException(\sprintf('The request Host header "%s" must not contain a percent escape, because an intermediary or an origin server can decode it and then read it as an authority that differs from the one the request names.', self::escape($value)), $request);
// GuzzleHttp\Psr7\Uri already enforces this predicate, so it only
// rejects invalid third-party UriInterface values.
if (!Psr7\Rfc3986::isValidHost($host)) {
throw new RequestException(\sprintf('The request URI host "%s" must be a valid RFC 3986 host, because a handler reparses the URI and can then connect to a host that differs from the one the request names.', self::escape($host)), $request);
}
// libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric
// hosts before connecting, while other readers treat the input as a
// name. Test the shape rather than the range so malformed numeric
// values fail closed. rtrim() also covers multiple trailing dots if
// libcurl later relaxes its current guard. Plain shorthand stays
// accepted. HostIdentity uses a broader grammar for cookie matching.
//
// @see \GuzzleHttp\HostIdentity::canonicalHost()
if (\str_ends_with($host, '.') && self::isNumericIpv4Host(\rtrim($host, '.'))) {
throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request);
}
}
/**
* Matches the accepted shape positively so a PCRE failure rejects.
*/
private static function isPrintableAscii(string $value): bool
{
return \preg_match('/\A[\x21-\x7E]*\z/D', $value) === 1;
}
/**
* Rejects a delimiter the transport could treat as the end of the URI host.
*
* This mirrors GuzzleHttp\Psr7\Uri::assertValidHost() and only affects
* third-party UriInterface values. Host headers may carry a port and are
* sent verbatim.
*
* @throws RequestException
*/
private static function assertNoAuthorityDelimiter(string $host, RequestInterface $request): void
{
$message = 'The request URI host "%s" must not contain a URI authority delimiter, because a handler reparses the URI and can then connect to a host that differs from the one the request names.';
// Match the accepted shape positively so a PCRE engine failure rejects.
if (\preg_match('/\A[^\/?#@\\\\]*\z/D', $host) !== 1) {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
if (\strpos($host, '[') !== false || \strpos($host, ']') !== false) {
if (\strpos($host, '[') !== 0 || \substr($host, -1) !== ']') {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
return;
}
if (\strpos($host, ':') !== false) {
throw new RequestException(\sprintf($message, self::escape($host)), $request);
}
}
/**
* Rejects one to four numeric-looking parts followed by trailing dots.
*
* libcurl 8.21.0 drops a trailing dot from inet_aton-style numeric hosts
* before connecting, while other validators treat the input as a name.
* Testing the shape also rejects some out-of-range values that transports
* keep as names; isNumericIpv4Host() explains that fail-closed tradeoff.
* Plain numeric shorthand stays accepted.
*
* @throws RequestException
*/
private static function assertNotADottedAddress(string $host, RequestInterface $request): void
{
if (\substr($host, -1) !== '.') {
return;
}
if (!self::isNumericIpv4Host(\rtrim($host, '.'))) {
return;
}
throw new RequestException(\sprintf('The request URI host "%s" must not be written as one to four decimal, octal or hexadecimal parts followed by one or more trailing dots, because a handler can read that spelling as an IPv4 address and connect to that address while the rest of the process reads a name.', self::escape($host)), $request);
}
/**
* Reports whether a value has the transport's inet_aton-style shape: one
* to four decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts.
* Reports whether a host has libcurl's inet_aton-style shape: one to four
* decimal, 0-prefixed octal, or 0x-prefixed hexadecimal parts.
*
* Range and 32-bit overflow checks are deliberately omitted. This may
* reject a trailing-dot spelling the transport reads as a name, but avoids
* missing one it resolves as an address. No PCRE is used.
* missing one it resolves as an address.
*/
public static function isNumericIpv4Host(string $host): bool
{
@ -179,10 +121,26 @@ final class HostValidator
return \strspn($part, $digits) === \strlen($part);
}
/**
* @throws RequestException
*/
private static function assertPrintableAscii(
string $value,
string $message,
#[\SensitiveParameter]
RequestInterface $request
): void {
// Match positively so a PCRE failure rejects.
if (\preg_match('/\A[\x21-\x7E]*\z/D', $value) !== 1) {
throw new RequestException(\sprintf($message, self::escape($value)), $request);
}
}
/**
* Escapes non-printable bytes as uppercase \xNN for safe diagnostics.
* Printable delimiters and dots stay visible. The result is not a
* reversible encoding.
*
* Psr7\DiagnosticValue is not used because it preserves valid non-ASCII
* UTF-8, including invisible characters rejected here.
*/
private static function escape(string $value): string
{
@ -190,7 +148,13 @@ final class HostValidator
for ($offset = 0, $length = \strlen($value); $offset < $length; ++$offset) {
$byte = \ord($value[$offset]);
$escaped .= $byte >= 0x21 && $byte <= 0x7E ? $value[$offset] : \sprintf('\\x%02X', $byte);
if ($byte >= 0x20 && $byte <= 0x7E) {
$escaped .= $value[$offset];
continue;
}
$escaped .= \sprintf('\\x%02X', $byte);
}
return $escaped;

View file

@ -1,9 +1,13 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\InvalidArgumentException;
use GuzzleHttp\Exception\ResponseException;
use GuzzleHttp\HandlerStack;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Promise as P;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\TransferStats;
@ -12,34 +16,31 @@ use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
/**
* Handler that returns responses or throw exceptions from a queue.
*
* @final
* Handler that returns responses or rejection reasons from a queue.
*/
class MockHandler implements \Countable
final class MockHandler implements \Countable
{
/**
* @var array
*/
private $queue = [];
use NonSerializableTrait;
/**
* @var RequestInterface|null
* @var list<ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>
*/
private $lastRequest;
private array $queue = [];
private ?RequestInterface $lastRequest = null;
/**
* @var array
* @var array<array-key, mixed>
*/
private $lastOptions = [];
private array $lastOptions = [];
/**
* @var callable|null
* @var (callable(ResponseInterface|null): mixed)|null
*/
private $onFulfilled;
/**
* @var callable|null
* @var (callable(mixed): mixed)|null
*/
private $onRejected;
@ -47,26 +48,35 @@ class MockHandler implements \Countable
* Creates a new MockHandler that uses the default handler stack list of
* middlewares.
*
* @param array|null $queue Array of responses, callables, or exceptions.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
* @param array<array-key, ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>|null $queue Array of responses, promises, callables, or throwables.
* @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected.
*
* @return HandlerStack<callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed>>
*/
public static function createWithMiddleware(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null): HandlerStack
{
public static function createWithMiddleware(
#[\SensitiveParameter]
?array $queue = null,
?callable $onFulfilled = null,
?callable $onRejected = null
): HandlerStack {
return HandlerStack::create(new self($queue, $onFulfilled, $onRejected));
}
/**
* The passed in value must be an array of
* {@see ResponseInterface} objects, Exceptions,
* callables, or Promises.
* {@see ResponseInterface} objects, throwables, callables, or promises.
*
* @param array<int, mixed>|null $queue The parameters to be passed to the append function, as an indexed array.
* @param callable|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param callable|null $onRejected Callback to invoke when the return value is rejected.
* @param array<array-key, ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>|callable(RequestInterface, array<array-key, mixed>): (ResponseInterface|\Throwable|PromiseInterface<ResponseInterface, mixed>)>|null $queue The parameters to be passed to the append function, as an indexed array.
* @param (callable(ResponseInterface|null): mixed)|null $onFulfilled Callback to invoke when the return value is fulfilled.
* @param (callable(mixed): mixed)|null $onRejected Callback to invoke when the return value is rejected.
*/
public function __construct(?array $queue = null, ?callable $onFulfilled = null, ?callable $onRejected = null)
{
public function __construct(
#[\SensitiveParameter]
?array $queue = null,
?callable $onFulfilled = null,
?callable $onRejected = null
) {
$this->onFulfilled = $onFulfilled;
$this->onRejected = $onRejected;
@ -76,30 +86,41 @@ class MockHandler implements \Countable
}
}
public function __invoke(RequestInterface $request, array $options): PromiseInterface
{
/**
* @return PromiseInterface<ResponseInterface, mixed>
*/
public function __invoke(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options
): PromiseInterface {
if (!$this->queue) {
// Test-setup error (more requests made than responses queued);
// intentionally a bare SPL exception, not a GuzzleException.
throw new \OutOfBoundsException('Mock queue is empty');
}
if (isset($options['delay']) && \is_numeric($options['delay'])) {
\usleep((int) $options['delay'] * 1000);
\usleep((int) ($options['delay'] * 1000));
}
if (isset($options['on_stats']) && !\is_callable($options['on_stats'])) {
throw new InvalidArgumentException('on_stats must be callable');
}
$this->lastRequest = $request;
$this->lastOptions = $options;
$response = \array_shift($this->queue);
$onHeaders = null;
$onHeadersResponse = null;
if (isset($options['on_headers'])) {
if (!\is_callable($options['on_headers'])) {
throw new \InvalidArgumentException('on_headers must be callable');
}
try {
$options['on_headers']($response);
} catch (\Exception $e) {
$msg = 'An error was encountered during the on_headers event';
$response = new RequestException($msg, $request, $response, $e);
throw new InvalidArgumentException('on_headers must be callable');
}
$onHeaders = $options['on_headers'];
}
if (\is_callable($response)) {
@ -110,8 +131,36 @@ class MockHandler implements \Countable
? P\Create::rejectionFor($response)
: P\Create::promiseFor($response);
return $response->then(
function (?ResponseInterface $value) use ($request, $options) {
if (\is_callable($onHeaders)) {
$response = $response->then(
static function (
#[\SensitiveParameter]
$value
) use ($onHeaders, $request, &$onHeadersResponse) {
if (!$value instanceof ResponseInterface) {
return $value;
}
try {
$onHeaders($value, $request);
} catch (\Throwable $e) {
$msg = 'An error was encountered during the on_headers event';
$onHeadersResponse = $value;
throw new ResponseException($msg, $request, $value, $e);
}
return $value;
}
);
}
$promise = $response->then(
function (
#[\SensitiveParameter]
$value
) use ($request, $options): ?ResponseInterface {
/** @var ResponseInterface|null $value */
$this->invokeStats($request, $options, $value);
if ($this->onFulfilled) {
($this->onFulfilled)($value);
@ -132,8 +181,11 @@ class MockHandler implements \Countable
return $value;
},
function ($reason) use ($request, $options) {
$this->invokeStats($request, $options, null, $reason);
function (
#[\SensitiveParameter]
$reason
) use ($request, $options, &$onHeadersResponse): PromiseInterface {
$this->invokeStats($request, $options, $onHeadersResponse, $reason);
if ($this->onRejected) {
($this->onRejected)($reason);
}
@ -141,16 +193,21 @@ class MockHandler implements \Countable
return P\Create::rejectionFor($reason);
}
);
/** @var PromiseInterface<ResponseInterface, mixed> $promise */
return $promise;
}
/**
* Adds one or more variadic requests, exceptions, callables, or promises
* to the queue.
*
* @param mixed ...$values
* @param mixed ...$values Responses, promises, throwables, or request-aware callables.
*/
public function append(...$values): void
{
public function append(
#[\SensitiveParameter]
...$values
): void {
foreach ($values as $value) {
if ($value instanceof ResponseInterface
|| $value instanceof \Throwable
@ -197,14 +254,22 @@ class MockHandler implements \Countable
* @param mixed $reason Promise or reason.
*/
private function invokeStats(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options,
#[\SensitiveParameter]
?ResponseInterface $response = null,
#[\SensitiveParameter]
$reason = null
): void {
if (isset($options['on_stats'])) {
$transferTime = $options['transfer_time'] ?? 0;
$stats = new TransferStats($request, $response, $transferTime, $reason);
$transferTime = $options['transfer_time'] ?? 0.0;
if (!\is_int($transferTime) && !\is_float($transferTime) && (!\is_string($transferTime) || !\is_numeric($transferTime))) {
throw new InvalidArgumentException('transfer_time must be a number of seconds');
}
$stats = new TransferStats($request, $response, (float) $transferTime, $reason);
($options['on_stats'])($stats);
}
}

View file

@ -1,30 +1,40 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Promise\PromiseInterface;
use GuzzleHttp\RequestOptions;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
/**
* Provides basic proxies for handlers.
*
* @final
*/
class Proxy
final class Proxy
{
private function __construct()
{
}
/**
* Sends synchronous requests to a specific handler while sending all other
* requests to another handler.
*
* @param callable(RequestInterface, array): PromiseInterface $default Handler used for normal responses
* @param callable(RequestInterface, array): PromiseInterface $sync Handler used for synchronous responses.
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $default Handler used for normal responses
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $sync Handler used for synchronous responses.
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the composed handler.
*/
public static function wrapSync(callable $default, callable $sync): callable
{
return static function (RequestInterface $request, array $options) use ($default, $sync): PromiseInterface {
return static function (
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options
) use ($default, $sync): PromiseInterface {
return empty($options[RequestOptions::SYNCHRONOUS]) ? $default($request, $options) : $sync($request, $options);
};
}
@ -37,45 +47,20 @@ class Proxy
* performance benefits of curl while still supporting true streaming
* through the StreamHandler.
*
* @param callable(RequestInterface, array): PromiseInterface $default Handler used for non-streaming responses
* @param callable(RequestInterface, array): PromiseInterface $streaming Handler used for streaming responses
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $default Handler used for non-streaming responses
* @param callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> $streaming Handler used for streaming responses
*
* @return callable(RequestInterface, array): PromiseInterface Returns the composed handler.
* @return callable(RequestInterface, array<array-key, mixed>): PromiseInterface<ResponseInterface, mixed> Returns the composed handler.
*/
public static function wrapStreaming(callable $default, callable $streaming): callable
{
return static function (RequestInterface $request, array $options) use ($default, $streaming): PromiseInterface {
return static function (
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
array $options
) use ($default, $streaming): PromiseInterface {
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,159 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\ProxyOptions;
use GuzzleHttp\ProxySelection;
use GuzzleHttp\Psr7;
use Psr\Http\Message\UriInterface;
/**
* Resolves proxy configuration from the process environment with the same
* semantics libcurl applies, shared by the built-in handlers: the cURL
* handlers pin CURLOPT_PROXY and CURLOPT_NOPROXY explicitly so libcurl never
* reads the environment itself, and the stream handler resolves the same way.
*
* @internal
*/
final class ProxyEnv
{
private function __construct()
{
}
/**
* Resolves the proxy selection for a request, falling back to the proxy
* environment variables when the proxy request option makes no decision.
*
* The environment no_proxy list is tokenized the way libcurl tokenizes
* it and matched here with the same rules as the proxy option's "no"
* list, so behavior does not depend on the installed libcurl's matcher.
*
* @param mixed $proxyOption
*/
public static function resolveProxySelection(
UriInterface $uri,
#[\SensitiveParameter]
$proxyOption
): ProxySelection {
$selection = ProxyOptions::resolve($uri, $proxyOption);
// Any option decision (proxy, bypassed, or disabled) is final; only
// a none() selection leaves room for the environment.
if ($selection->hasProxy() || $selection->shouldDisableProxy()) {
return $selection;
}
$envProxy = self::getProxyForScheme($uri->getScheme());
if ($envProxy === null) {
return $selection;
}
$noProxy = self::getNoProxy();
if ($noProxy !== null && ProxyOptions::isUriInNoProxy($uri, self::splitNoProxy($noProxy))) {
return ProxySelection::bypassed();
}
// $envProxy is never '' (empty env values are treated as unset).
return ProxySelection::proxy($envProxy);
}
/**
* 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.
*
* Entries may be separated by commas or blanks, the way libcurl tokenizes
* the value.
*
* @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 !== '') {
$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

@ -0,0 +1,256 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\NonSerializableTrait;
use GuzzleHttp\Psr7;
use GuzzleHttp\Psr7\Exception\TimeoutException;
use Psr\Http\Message\RequestInterface;
/**
* Validates and normalizes request framing before a handler performs I/O.
*
* Body size describes the bytes available under handler rewind semantics.
* Content-Length is the selected transport boundary and may remain unknown.
*
* @internal
*/
final class RequestFraming
{
use NonSerializableTrait;
public RequestInterface $request;
/**
* Number of bytes available after applying handler rewind semantics, if
* known.
*/
public ?int $bodySize;
/** Canonical Content-Length boundary selected for transport, if any. */
public ?int $contentLength;
private function __construct(RequestInterface $request, ?int $bodySize, ?int $contentLength)
{
$this->request = $request;
$this->bodySize = $bodySize;
$this->contentLength = $contentLength;
}
/**
* Finalizes request framing for a handler dispatch.
*
* When $sendBody is false, body-dependent validation and size probing are
* skipped. Content-Length is still canonicalized and Transfer-Encoding is
* removed.
*
* @throws RequestException when framing or body metadata is unsafe
*/
public static function analyze(
#[\SensitiveParameter]
RequestInterface $request,
bool $sendBody = true
): self {
try {
$length = HeaderProcessor::parseContentLength($request->getHeader('Content-Length'));
} catch (\RuntimeException $e) {
throw new RequestException('Invalid Content-Length request header: '.$e->getMessage(), $request, 0, $e);
}
try {
HeaderProcessor::assertContentLengthWithinPlatformLimit($length);
} catch (\OverflowException $e) {
throw new RequestException($e->getMessage(), $request, 0, $e);
}
$contentLength = HeaderProcessor::contentLengthToInt($length);
if ($length !== null) {
$request = $request->withHeader('Content-Length', $length);
}
if (!$sendBody) {
return new self($request->withoutHeader('Transfer-Encoding'), null, $contentLength);
}
$transferEncoding = $request->getHeader('Transfer-Encoding');
if ($length !== null && $transferEncoding !== []) {
throw new RequestException(
'A request must not contain both Content-Length and Transfer-Encoding',
$request
);
}
if ($transferEncoding !== []) {
$tokens = [];
foreach ($transferEncoding as $value) {
foreach (\explode(',', $value) as $part) {
$tokens[] = \trim($part, " \t");
}
}
if (\count($tokens) !== 1 || !Psr7\Utils::caselessEquals($tokens[0], 'chunked') || $request->getProtocolVersion() !== '1.1') {
throw new RequestException('Unsupported Transfer-Encoding request header', $request);
}
}
$bodySize = self::bodySize($request);
if ($bodySize !== null && $contentLength !== null && $bodySize !== $contentLength) {
throw new RequestException('Content-Length does not match the request body size', $request);
}
if ($bodySize === null && $contentLength === null && $request->getProtocolVersion() === '1.0') {
throw new RequestException('An unknown-size HTTP/1.0 request body requires Content-Length', $request);
}
if ($length === null && $bodySize !== null && ($bodySize > 0 || \in_array($request->getMethod(), ['PUT', 'POST'], true))) {
$contentLength = $bodySize;
$request = $request->withHeader('Content-Length', (string) $bodySize);
}
return new self($request->withoutHeader('Transfer-Encoding'), $bodySize, $contentLength);
}
/**
* Returns the number of bytes available for dispatch, or null when unknown.
*
* Seekable bodies use their total size because handlers rewind them.
* Positioned non-seekable bodies use the total size minus their current
* position.
*
* @throws RequestException when body metadata cannot be read safely
*/
public static function bodySize(
#[\SensitiveParameter]
RequestInterface $request
): ?int {
$body = $request->getBody();
try {
$size = $body->getSize();
if ($size === null) {
return null;
}
if ($size < 0) {
throw new \RuntimeException('Request body size must not be negative');
}
$seekable = $body->isSeekable();
} catch (\Exception $e) {
throw self::bodyException(
$request,
$e,
'Timed out while determining the request body size',
'Failed to determine the request body size'
);
}
if ($seekable) {
return $size;
}
try {
$position = $body->tell();
} catch (\RuntimeException $e) {
return null;
}
if ($position < 0 || $position > $size) {
throw new RequestException('The request body position is outside the stream size', $request);
}
return $size - $position;
}
/**
* Materializes the body, stopping at the selected Content-Length when
* present.
*
* @throws RequestException when the body cannot be fully rewound or read
*/
public function materialize(): string
{
$body = $this->request->getBody();
if ($this->contentLength === null) {
try {
return (string) $body;
} catch (\Exception $e) {
throw self::bodyException(
$this->request,
$e,
'Timed out while reading the request body',
'Failed to read the request body'
);
}
}
if ($this->contentLength === 0) {
return '';
}
try {
if ($body->isSeekable()) {
$body->rewind();
}
} catch (\Exception $e) {
throw self::bodyException(
$this->request,
$e,
'Timed out while rewinding the request body',
'Failed to rewind the request body'
);
}
$contents = '';
$remaining = $this->contentLength;
while ($remaining > 0) {
$limit = \min(8192, $remaining);
try {
$chunk = $body->read($limit);
} catch (\Exception $e) {
throw self::bodyException(
$this->request,
$e,
'Timed out while reading the request body',
'Failed to read the request body'
);
}
if ($chunk === '') {
throw new RequestException(
'Request body ended before the declared Content-Length was reached',
$this->request
);
}
if (\strlen($chunk) > $limit) {
throw new RequestException('Request body stream returned more bytes than requested', $this->request);
}
$contents .= $chunk;
$remaining -= \strlen($chunk);
}
return $contents;
}
private static function bodyException(
#[\SensitiveParameter]
RequestInterface $request,
#[\SensitiveParameter]
\Exception $exception,
string $timeoutMessage,
string $fallbackMessage
): RequestException {
$message = $exception instanceof TimeoutException
? $timeoutMessage
: ($exception->getMessage() !== '' ? $exception->getMessage() : $fallbackMessage);
return new RequestException($message, $request, 0, $exception);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\InvalidArgumentException;
/**
* @internal
*/
final class Timeout
{
private function __construct()
{
}
/**
* Converts a request timeout option to integer milliseconds.
*
* @param mixed $value
*/
public static function toMilliseconds($value, string $option): int
{
if (!\is_int($value) && !\is_float($value) && (!\is_string($value) || !\is_numeric($value))) {
throw new InvalidArgumentException($option.' must be a number of seconds');
}
$seconds = (float) $value;
if (!\is_finite($seconds) || $seconds < 0) {
throw new InvalidArgumentException($option.' must be 0 or greater than or equal to 0.001 seconds');
}
$milliseconds = (int) ($seconds * 1000);
if ($seconds > 0 && $milliseconds === 0) {
throw new InvalidArgumentException($option.' must be 0 or greater than or equal to 0.001 seconds');
}
return $milliseconds;
}
}

View file

@ -1,7 +1,11 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
use GuzzleHttp\Exception\InvalidArgumentException;
/**
* @internal
*/
@ -21,11 +25,11 @@ final class TlsVersion
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) {
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return 13;
}
throw new \InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
throw new InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
}
/**
@ -39,7 +43,7 @@ final class TlsVersion
}
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');
throw new InvalidArgumentException('Invalid crypto_method_max request option: maximum TLS version must be greater than or equal to crypto_method');
}
}
@ -49,36 +53,18 @@ final class TlsVersion
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);
return \STREAM_CRYPTO_PROTO_TLSv1_0;
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_1', $option);
return \STREAM_CRYPTO_PROTO_TLSv1_1;
}
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_2', $option);
return \STREAM_CRYPTO_PROTO_TLSv1_2;
}
if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return self::requireStreamProto('STREAM_CRYPTO_PROTO_TLSv1_3', $option);
if ($value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
return \STREAM_CRYPTO_PROTO_TLSv1_3;
}
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
));
throw new InvalidArgumentException(\sprintf('Invalid %s request option: unknown version provided', $option));
}
}

View file

@ -0,0 +1,62 @@
<?php
declare(strict_types=1);
namespace GuzzleHttp\Handler;
/**
* @internal
*/
final class TransferByteCounter
{
private function __construct()
{
}
/**
* @param mixed $value
*/
public static function progressValueToInt($value): int
{
if (\is_int($value)) {
if ($value < 0) {
throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform');
}
return $value;
}
if (!\is_float($value)) {
throw new \UnexpectedValueException('Progress byte count must be an integer or float');
}
if (
!\is_finite($value)
|| $value < 0
|| $value > \PHP_INT_MAX
|| (\PHP_INT_SIZE === 8 && $value >= (float) \PHP_INT_MAX)
) {
throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform');
}
$intValue = (int) $value;
if ($intValue < 0) {
throw new \OverflowException('Progress byte count exceeds the maximum integer size supported on this platform');
}
return $intValue;
}
public static function add(int $current, int $delta, string $message): int
{
if ($current < 0 || $delta < 0) {
throw new \OverflowException($message);
}
if ($delta > \PHP_INT_MAX - $current) {
throw new \OverflowException($message);
}
return $current + $delta;
}
}