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

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
));
}
}