v1.1.4
This commit is contained in:
parent
d6e6011c3d
commit
1dd5809016
7 changed files with 21760 additions and 3778 deletions
414
vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php
vendored
414
vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php
vendored
|
|
@ -9,6 +9,7 @@ use GuzzleHttp\Promise\FulfilledPromise;
|
|||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7\LazyOpenStream;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use GuzzleHttp\Utils;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\UriInterface;
|
||||
|
|
@ -38,17 +39,62 @@ class CurlFactory implements CurlFactoryInterface
|
|||
private $maxHandles;
|
||||
|
||||
/**
|
||||
* @param int $maxHandles Maximum number of idle handles.
|
||||
* @var resource|\CurlShareHandle|null
|
||||
*/
|
||||
public function __construct(int $maxHandles)
|
||||
private $shareHandle;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
private $shareMode;
|
||||
|
||||
/**
|
||||
* @param int $maxHandles Maximum number of idle handles.
|
||||
* @param resource|\CurlShareHandle|null $shareHandle
|
||||
*/
|
||||
public function __construct(int $maxHandles, string $shareMode = TransportSharing::NONE, $shareHandle = null)
|
||||
{
|
||||
$this->maxHandles = $maxHandles;
|
||||
$this->shareMode = CurlShareHandleState::normalizeMode($shareMode, 'transport_sharing');
|
||||
|
||||
if ($this->shareMode === TransportSharing::NONE && $shareHandle !== null) {
|
||||
throw new \InvalidArgumentException('A cURL share handle cannot be provided when transport sharing is disabled.');
|
||||
}
|
||||
|
||||
if ($this->shareMode !== TransportSharing::NONE && $shareHandle === null) {
|
||||
throw new \InvalidArgumentException('A cURL share handle is required when transport sharing is enabled.');
|
||||
}
|
||||
|
||||
if ($shareHandle !== null && !self::isCurlShareHandle($shareHandle)) {
|
||||
throw new \InvalidArgumentException('A cURL share handle must be an instance of CurlShareHandle or a curl_share resource.');
|
||||
}
|
||||
|
||||
$this->shareHandle = $shareHandle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value
|
||||
*/
|
||||
private static function isCurlShareHandle($value): bool
|
||||
{
|
||||
if (\PHP_VERSION_ID < 80000) {
|
||||
return \is_resource($value) && \get_resource_type($value) === 'curl_share';
|
||||
}
|
||||
|
||||
return $value instanceof \CurlShareHandle;
|
||||
}
|
||||
|
||||
public function create(RequestInterface $request, array $options): EasyHandle
|
||||
{
|
||||
$protocolVersion = $request->getProtocolVersion();
|
||||
|
||||
if ('' === $protocolVersion) {
|
||||
\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with an empty protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
|
||||
|
||||
$protocolVersion = '1.1';
|
||||
$request = \GuzzleHttp\Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
|
||||
}
|
||||
|
||||
if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
|
||||
if (!self::supportsHttp2()) {
|
||||
throw new ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
|
||||
|
|
@ -62,6 +108,10 @@ class CurlFactory implements CurlFactoryInterface
|
|||
unset($options['curl']['body_as_string']);
|
||||
}
|
||||
|
||||
self::triggerUnsupportedRequestOptionDeprecations($options);
|
||||
$this->rejectRequestLevelShareConflict($options);
|
||||
self::triggerConflictingCurlOptionDeprecations($options);
|
||||
|
||||
$easy = new EasyHandle();
|
||||
$easy->request = $request;
|
||||
$easy->options = $options;
|
||||
|
|
@ -77,12 +127,264 @@ class CurlFactory implements CurlFactoryInterface
|
|||
}
|
||||
|
||||
$conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
|
||||
$easy->handle = $this->handles ? \array_pop($this->handles) : \curl_init();
|
||||
curl_setopt_array($easy->handle, $conf);
|
||||
if ($this->shareHandle !== null) {
|
||||
if (!\defined('CURLOPT_SHARE')) {
|
||||
throw new \InvalidArgumentException('The configured cURL share handle requires CURLOPT_SHARE, but it is not available in the installed PHP cURL extension.');
|
||||
}
|
||||
|
||||
$conf[(int) \constant('CURLOPT_SHARE')] = $this->shareHandle;
|
||||
}
|
||||
|
||||
$handle = $this->handles ? \array_pop($this->handles) : \curl_init();
|
||||
if (false === $handle) {
|
||||
throw new \RuntimeException('Can not initialize cURL handle.');
|
||||
}
|
||||
$easy->handle = $handle;
|
||||
|
||||
try {
|
||||
$this->applyCurlOptions($handle, $conf);
|
||||
} catch (\Throwable $e) {
|
||||
if (PHP_VERSION_ID < 80000 && \is_resource($handle)) {
|
||||
\curl_close($handle);
|
||||
}
|
||||
unset($easy->handle);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return $easy;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource|\CurlHandle $handle
|
||||
* @param array<int|string, mixed> $conf
|
||||
*/
|
||||
private function applyCurlOptions($handle, array $conf): void
|
||||
{
|
||||
foreach ($conf as $option => $value) {
|
||||
if (!\is_int($option)) {
|
||||
throw new \InvalidArgumentException(\sprintf(
|
||||
'Invalid cURL option %s.',
|
||||
self::formatCurlOption($option)
|
||||
));
|
||||
}
|
||||
|
||||
try {
|
||||
$success = curl_setopt($handle, $option, $value);
|
||||
} catch (\Throwable $e) {
|
||||
throw new \InvalidArgumentException(
|
||||
\sprintf(
|
||||
'Unable to set cURL option %s: %s',
|
||||
self::formatCurlOption($option),
|
||||
$e->getMessage()
|
||||
),
|
||||
0,
|
||||
$e
|
||||
);
|
||||
}
|
||||
|
||||
if (!$success) {
|
||||
throw new \InvalidArgumentException(\sprintf(
|
||||
'Unable to set cURL option %s.',
|
||||
self::formatCurlOption($option)
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private function rejectRequestLevelShareConflict(array $options): void
|
||||
{
|
||||
if ($this->shareHandle === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (
|
||||
!\defined('CURLOPT_SHARE')
|
||||
|| !isset($options['curl'])
|
||||
|| !\is_array($options['curl'])
|
||||
|| !\array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl'])
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with configured transport sharing.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int|string $option
|
||||
*/
|
||||
private static function formatCurlOption($option): string
|
||||
{
|
||||
if (!\is_int($option)) {
|
||||
return \sprintf('"%s"', $option);
|
||||
}
|
||||
|
||||
static $names = null;
|
||||
|
||||
if (null === $names) {
|
||||
$names = [];
|
||||
foreach (\get_defined_constants(true)['curl'] ?? [] as $name => $value) {
|
||||
if (\is_int($value) && \strpos($name, 'CURLOPT_') === 0 && !isset($names[$value])) {
|
||||
$names[$value] = $name;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($names[$option])) {
|
||||
return \sprintf('%s (%d)', $names[$option], $option);
|
||||
}
|
||||
|
||||
return (string) $option;
|
||||
}
|
||||
|
||||
private static function triggerConflictingCurlOptionDeprecations(array $options): void
|
||||
{
|
||||
if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$conflictingOptions = self::conflictingCurlOptions();
|
||||
|
||||
foreach ($options['curl'] as $option => $_) {
|
||||
if (!\array_key_exists($option, $conflictingOptions)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = self::formatCurlOption($option);
|
||||
$replacement = $conflictingOptions[$option];
|
||||
if ($replacement !== null) {
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'7.11',
|
||||
\sprintf(
|
||||
'Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed request handling. Use %s instead.',
|
||||
$name,
|
||||
$replacement
|
||||
)
|
||||
);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
\trigger_deprecation(
|
||||
'guzzlehttp/guzzle',
|
||||
'7.11',
|
||||
\sprintf(
|
||||
'Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed cURL internals.',
|
||||
$name
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private static function triggerUnsupportedRequestOptionDeprecations(array $options): void
|
||||
{
|
||||
if (
|
||||
\array_key_exists('transport_sharing', $options)
|
||||
&& CurlShareHandleState::normalizeMode($options['transport_sharing'], 'transport_sharing') !== TransportSharing::NONE
|
||||
) {
|
||||
\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "transport_sharing" request option to a cURL handler is deprecated; guzzlehttp/guzzle 8.0 will reject this option because transport sharing must be configured when creating the Client, CurlHandler, or CurlMultiHandler.');
|
||||
}
|
||||
|
||||
if (\array_key_exists('stream_context', $options)) {
|
||||
\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "stream_context" request option to a cURL handler is deprecated; guzzlehttp/guzzle 8.0 will reject this option because cURL handlers ignore PHP stream context options.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string|null>
|
||||
*/
|
||||
private static function conflictingCurlOptions(): array
|
||||
{
|
||||
static $options = null;
|
||||
|
||||
if ($options !== null) {
|
||||
return $options;
|
||||
}
|
||||
|
||||
$options = [];
|
||||
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SHARE', 'the "transport_sharing" client option or cURL handler option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_URL', 'the request URI');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_PORT', 'the request URI');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_CUSTOMREQUEST', 'the request method');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_HTTPGET', 'the request method');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_POST', 'the request method and body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_PUT', 'the request method and body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_NOBODY', 'the request method');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_UPLOAD', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_POSTFIELDS', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_READFUNCTION', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_READDATA', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_INFILE', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE_LARGE', 'the request body');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_HTTPHEADER', 'the request headers');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_USERAGENT', 'the request headers');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_REFERER', 'the request headers');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_HEADERFUNCTION', 'the "on_headers" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_WRITEFUNCTION', 'the "sink" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_FILE', 'the "sink" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_RETURNTRANSFER', null);
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_HEADER', null);
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT', 'the "timeout" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT_MS', 'the "timeout" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT', 'the "connect_timeout" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT_MS', 'the "connect_timeout" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_NOSIGNAL', 'the "timeout" or "connect_timeout" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_NOPROGRESS', 'the "progress" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_PROGRESSFUNCTION', 'the "progress" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_XFERINFOFUNCTION', 'the "progress" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_VERBOSE', 'the "debug" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_STDERR', 'the "debug" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_PROXY', 'the "proxy" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_NOPROXY', 'the "proxy" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_MAXREDIRS', 'the "allow_redirects" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_POSTREDIR', 'the "allow_redirects" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS', 'the "allow_redirects" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS_STR', 'the "allow_redirects" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS', 'the "protocols" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS_STR', 'the "protocols" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_HTTP09_ALLOWED', null);
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_HTTP_VERSION', 'the request protocol version');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_IPRESOLVE', 'the "force_ip_resolve" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYPEER', 'the "verify" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYHOST', 'the "verify" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_CAINFO', 'the "verify" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_CAPATH', 'the "verify" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLVERSION', 'the "crypto_method" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLCERT', 'the "cert" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTPASSWD', 'the "cert" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTTYPE', 'the "cert_type" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLKEY', 'the "ssl_key" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYPASSWD', 'the "ssl_key" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_KEYPASSWD', 'the "ssl_key" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYTYPE', 'the "ssl_key_type" request option');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_COOKIE', 'the "Cookie" request header or Guzzle cookie middleware');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_COOKIEFILE', 'Guzzle cookie middleware');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_COOKIEJAR', 'Guzzle cookie middleware');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_COOKIELIST', 'Guzzle cookie middleware');
|
||||
self::addConflictingCurlOption($options, 'CURLOPT_COOKIESESSION', 'Guzzle cookie middleware');
|
||||
|
||||
return $options;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<int, string|null> $options
|
||||
*/
|
||||
private static function addConflictingCurlOption(array &$options, string $constant, ?string $replacement): void
|
||||
{
|
||||
if (!\defined($constant)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$value = \constant($constant);
|
||||
if (\is_int($value)) {
|
||||
$options[$value] = $replacement;
|
||||
}
|
||||
}
|
||||
|
||||
private static function supportsHttp2(): bool
|
||||
{
|
||||
static $supportsHttp2 = null;
|
||||
|
|
@ -233,7 +535,7 @@ class CurlFactory implements CurlFactoryInterface
|
|||
new RequestException(
|
||||
'An error was encountered while creating the response',
|
||||
$easy->request,
|
||||
$easy->response,
|
||||
null,
|
||||
$easy->createResponseException,
|
||||
$ctx
|
||||
)
|
||||
|
|
@ -312,8 +614,14 @@ class CurlFactory implements CurlFactoryInterface
|
|||
\CURLOPT_CONNECTTIMEOUT => 300,
|
||||
];
|
||||
|
||||
$protocols = Utils::normalizeProtocols($easy->options['protocols'] ?? ['http', 'https']);
|
||||
$scheme = $easy->request->getUri()->getScheme();
|
||||
if (!\in_array($scheme, $protocols, true)) {
|
||||
throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $easy->request);
|
||||
}
|
||||
|
||||
if (\defined('CURLOPT_PROTOCOLS')) {
|
||||
$conf[\CURLOPT_PROTOCOLS] = \CURLPROTO_HTTP | \CURLPROTO_HTTPS;
|
||||
$conf[\CURLOPT_PROTOCOLS] = self::curlProtocolMask($protocols);
|
||||
}
|
||||
|
||||
$version = $easy->request->getProtocolVersion();
|
||||
|
|
@ -329,6 +637,41 @@ class CurlFactory implements CurlFactoryInterface
|
|||
return $conf;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $protocols
|
||||
*/
|
||||
private static function curlProtocolMask(array $protocols): int
|
||||
{
|
||||
$mask = 0;
|
||||
|
||||
if (\in_array('http', $protocols, true)) {
|
||||
$mask |= \CURLPROTO_HTTP;
|
||||
}
|
||||
|
||||
if (\in_array('https', $protocols, true)) {
|
||||
$mask |= \CURLPROTO_HTTPS;
|
||||
}
|
||||
|
||||
return $mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $type
|
||||
*/
|
||||
private static function normalizeTlsFileType(string $option, $type): string
|
||||
{
|
||||
if (!\is_string($type) || $type === '') {
|
||||
throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
|
||||
}
|
||||
|
||||
return \strtoupper($type);
|
||||
}
|
||||
|
||||
private static function shouldValidateSslKeyFile(?string $type): bool
|
||||
{
|
||||
return $type !== 'ENG' && $type !== 'PROV';
|
||||
}
|
||||
|
||||
private function applyMethod(EasyHandle $easy, array &$conf): void
|
||||
{
|
||||
$body = $easy->request->getBody();
|
||||
|
|
@ -426,7 +769,7 @@ class CurlFactory implements CurlFactoryInterface
|
|||
private function removeHeader(string $name, array &$options): void
|
||||
{
|
||||
foreach (\array_keys($options['_headers']) as $key) {
|
||||
if (!\strcasecmp($key, $name)) {
|
||||
if (!\strcasecmp((string) $key, $name)) {
|
||||
unset($options['_headers'][$key]);
|
||||
|
||||
return;
|
||||
|
|
@ -532,8 +875,10 @@ class CurlFactory implements CurlFactoryInterface
|
|||
} else {
|
||||
$scheme = $easy->request->getUri()->getScheme();
|
||||
if (isset($options['proxy'][$scheme])) {
|
||||
$host = $easy->request->getUri()->getHost();
|
||||
if (isset($options['proxy']['no']) && Utils::isHostInNoProxy($host, $options['proxy']['no'])) {
|
||||
if (
|
||||
isset($options['proxy']['no'])
|
||||
&& Utils::isUriInNoProxy($easy->request->getUri(), $options['proxy']['no'])
|
||||
) {
|
||||
unset($conf[\CURLOPT_PROXY]);
|
||||
} else {
|
||||
$conf[\CURLOPT_PROXY] = $options['proxy'][$scheme];
|
||||
|
|
@ -580,36 +925,68 @@ class CurlFactory implements CurlFactoryInterface
|
|||
}
|
||||
}
|
||||
|
||||
$certType = null;
|
||||
if (isset($options['cert_type'])) {
|
||||
$certType = self::normalizeTlsFileType('cert_type', $options['cert_type']);
|
||||
$conf[\CURLOPT_SSLCERTTYPE] = $certType;
|
||||
}
|
||||
|
||||
if (isset($options['cert'])) {
|
||||
$cert = $options['cert'];
|
||||
if (\is_array($cert)) {
|
||||
$conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
|
||||
if (!isset($cert[0]) || !\is_string($cert[0])) {
|
||||
throw new \InvalidArgumentException('Invalid cert request option');
|
||||
}
|
||||
if (isset($cert[1])) {
|
||||
if (!\is_string($cert[1])) {
|
||||
throw new \InvalidArgumentException('Invalid cert request option');
|
||||
}
|
||||
$conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
|
||||
}
|
||||
$cert = $cert[0];
|
||||
}
|
||||
if (!\is_string($cert)) {
|
||||
throw new \InvalidArgumentException('Invalid cert request option');
|
||||
}
|
||||
if (!\file_exists($cert)) {
|
||||
throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
|
||||
}
|
||||
// OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
|
||||
// see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
|
||||
$ext = pathinfo($cert, \PATHINFO_EXTENSION);
|
||||
if (preg_match('#^(der|p12)$#i', $ext)) {
|
||||
if ($certType === null && preg_match('#^(der|p12)$#i', $ext)) {
|
||||
$conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext);
|
||||
}
|
||||
$conf[\CURLOPT_SSLCERT] = $cert;
|
||||
}
|
||||
|
||||
$sslKeyType = null;
|
||||
if (isset($options['ssl_key_type'])) {
|
||||
$sslKeyType = self::normalizeTlsFileType('ssl_key_type', $options['ssl_key_type']);
|
||||
$conf[\CURLOPT_SSLKEYTYPE] = $sslKeyType;
|
||||
}
|
||||
|
||||
if (isset($options['ssl_key'])) {
|
||||
if (\is_array($options['ssl_key'])) {
|
||||
if (\count($options['ssl_key']) === 2) {
|
||||
[$sslKey, $conf[\CURLOPT_SSLKEYPASSWD]] = $options['ssl_key'];
|
||||
} else {
|
||||
[$sslKey] = $options['ssl_key'];
|
||||
if (!isset($options['ssl_key'][0]) || !\is_string($options['ssl_key'][0])) {
|
||||
throw new \InvalidArgumentException('Invalid ssl_key request option');
|
||||
}
|
||||
if (isset($options['ssl_key'][1])) {
|
||||
if (!\is_string($options['ssl_key'][1])) {
|
||||
throw new \InvalidArgumentException('Invalid ssl_key request option');
|
||||
}
|
||||
$conf[\CURLOPT_SSLKEYPASSWD] = $options['ssl_key'][1];
|
||||
}
|
||||
$sslKey = $options['ssl_key'][0];
|
||||
}
|
||||
|
||||
$sslKey = $sslKey ?? $options['ssl_key'];
|
||||
|
||||
if (!\file_exists($sslKey)) {
|
||||
if (!\is_string($sslKey)) {
|
||||
throw new \InvalidArgumentException('Invalid ssl_key request option');
|
||||
}
|
||||
|
||||
if (self::shouldValidateSslKeyFile($sslKeyType) && !\file_exists($sslKey)) {
|
||||
throw new \InvalidArgumentException("SSL private key not found: {$sslKey}");
|
||||
}
|
||||
$conf[\CURLOPT_SSLKEY] = $sslKey;
|
||||
|
|
@ -701,7 +1078,8 @@ class CurlFactory implements CurlFactoryInterface
|
|||
$startingResponse = true;
|
||||
try {
|
||||
$easy->createResponse();
|
||||
} catch (\Exception $e) {
|
||||
} catch (\Throwable $e) {
|
||||
$easy->response = null;
|
||||
$easy->createResponseException = $e;
|
||||
|
||||
return -1;
|
||||
|
|
@ -709,7 +1087,7 @@ class CurlFactory implements CurlFactoryInterface
|
|||
if ($onHeaders !== null) {
|
||||
try {
|
||||
$onHeaders($easy->response);
|
||||
} catch (\Exception $e) {
|
||||
} catch (\Throwable $e) {
|
||||
// Associate the exception with the handle and trigger
|
||||
// a curl header write error by returning 0.
|
||||
$easy->onHeadersException = $e;
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@
|
|||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
/**
|
||||
|
|
@ -21,17 +22,39 @@ class CurlHandler
|
|||
*/
|
||||
private $factory;
|
||||
|
||||
/**
|
||||
* @var CurlShareHandleState|null
|
||||
*/
|
||||
private $shareHandleState;
|
||||
|
||||
/**
|
||||
* Accepts an associative array of options:
|
||||
*
|
||||
* - handle_factory: Optional curl factory used to create cURL handles.
|
||||
* - transport_sharing: Optional transport sharing mode.
|
||||
*
|
||||
* @param array{handle_factory?: ?CurlFactoryInterface} $options Array of options to use with the handler
|
||||
* @param array{handle_factory?: ?CurlFactoryInterface, transport_sharing?: mixed} $options Array of options to use with the handler
|
||||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
$this->factory = $options['handle_factory']
|
||||
?? new CurlFactory(3);
|
||||
CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlHandler');
|
||||
$transportSharing = $options['transport_sharing'] ?? null;
|
||||
$sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
|
||||
|
||||
if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
|
||||
$this->shareHandleState = null;
|
||||
$this->factory = $options['handle_factory'];
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->shareHandleState = $sharingMode !== TransportSharing::NONE
|
||||
? CurlShareHandleState::fromOption($transportSharing)
|
||||
: null;
|
||||
|
||||
$this->factory = $this->shareHandleState !== null
|
||||
? new CurlFactory(3, $this->shareHandleState->mode, $this->shareHandleState->handle)
|
||||
: new CurlFactory(3);
|
||||
}
|
||||
|
||||
public function __invoke(RequestInterface $request, array $options): PromiseInterface
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ use Closure;
|
|||
use GuzzleHttp\Promise as P;
|
||||
use GuzzleHttp\Promise\Promise;
|
||||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use GuzzleHttp\Utils;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
|
||||
|
|
@ -25,6 +26,11 @@ class CurlMultiHandler
|
|||
*/
|
||||
private $factory;
|
||||
|
||||
/**
|
||||
* @var CurlShareHandleState|null
|
||||
*/
|
||||
private $shareHandleState;
|
||||
|
||||
/**
|
||||
* @var int
|
||||
*/
|
||||
|
|
@ -57,10 +63,21 @@ class CurlMultiHandler
|
|||
/** @var resource|\CurlMultiHandle */
|
||||
private $_mh;
|
||||
|
||||
/**
|
||||
* @var bool
|
||||
*/
|
||||
private $executingMulti = false;
|
||||
|
||||
/**
|
||||
* @var array<int, EasyHandle>
|
||||
*/
|
||||
private $deferredCancels = [];
|
||||
|
||||
/**
|
||||
* This handler accepts the following options:
|
||||
*
|
||||
* - handle_factory: An optional factory used to create curl handles
|
||||
* - transport_sharing: Optional transport sharing mode.
|
||||
* - select_timeout: Optional timeout (in seconds) to block before timing
|
||||
* out while selecting curl handles. Defaults to 1 second.
|
||||
* - options: An associative array of CURLMOPT_* options and
|
||||
|
|
@ -68,12 +85,27 @@ class CurlMultiHandler
|
|||
*/
|
||||
public function __construct(array $options = [])
|
||||
{
|
||||
$this->factory = $options['handle_factory'] ?? new CurlFactory(50);
|
||||
CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlMultiHandler');
|
||||
$transportSharing = $options['transport_sharing'] ?? null;
|
||||
$sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
|
||||
|
||||
if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
|
||||
$this->shareHandleState = null;
|
||||
$this->factory = $options['handle_factory'];
|
||||
} else {
|
||||
$this->shareHandleState = $sharingMode !== TransportSharing::NONE
|
||||
? CurlShareHandleState::fromOption($transportSharing)
|
||||
: null;
|
||||
|
||||
$this->factory = $this->shareHandleState !== null
|
||||
? new CurlFactory(50, $this->shareHandleState->mode, $this->shareHandleState->handle)
|
||||
: new CurlFactory(50);
|
||||
}
|
||||
|
||||
if (isset($options['select_timeout'])) {
|
||||
$this->selectTimeout = $options['select_timeout'];
|
||||
} elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) {
|
||||
@trigger_error('Since guzzlehttp/guzzle 7.2.0: Using environment variable GUZZLE_CURL_SELECT_TIMEOUT is deprecated. Use option "select_timeout" instead.', \E_USER_DEPRECATED);
|
||||
\trigger_deprecation('guzzlehttp/guzzle', '7.2', 'The GUZZLE_CURL_SELECT_TIMEOUT environment variable is deprecated; use the "select_timeout" option instead.');
|
||||
$this->selectTimeout = (int) $selectTimeout;
|
||||
} else {
|
||||
$this->selectTimeout = 1;
|
||||
|
|
@ -119,8 +151,13 @@ class CurlMultiHandler
|
|||
public function __destruct()
|
||||
{
|
||||
if (isset($this->_mh)) {
|
||||
\curl_multi_close($this->_mh);
|
||||
unset($this->_mh);
|
||||
try {
|
||||
\curl_multi_close($this->_mh);
|
||||
} catch (\Throwable $e) {
|
||||
// Destructors must not throw.
|
||||
} finally {
|
||||
unset($this->_mh);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -172,10 +209,21 @@ class CurlMultiHandler
|
|||
\usleep(250);
|
||||
}
|
||||
|
||||
while (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
|
||||
do {
|
||||
$this->executingMulti = true;
|
||||
|
||||
try {
|
||||
$exec = \curl_multi_exec($this->_mh, $this->active);
|
||||
} finally {
|
||||
$this->executingMulti = false;
|
||||
$this->cleanupDeferredCancels();
|
||||
}
|
||||
|
||||
// Prevent busy looping for slow HTTP requests.
|
||||
\curl_multi_select($this->_mh, $this->selectTimeout);
|
||||
}
|
||||
if ($exec === \CURLM_CALL_MULTI_PERFORM) {
|
||||
\curl_multi_select($this->_mh, $this->selectTimeout);
|
||||
}
|
||||
} while ($exec === \CURLM_CALL_MULTI_PERFORM);
|
||||
|
||||
$this->processMessages();
|
||||
}
|
||||
|
|
@ -185,7 +233,16 @@ class CurlMultiHandler
|
|||
*/
|
||||
private function tickInQueue(): void
|
||||
{
|
||||
if (\curl_multi_exec($this->_mh, $this->active) === \CURLM_CALL_MULTI_PERFORM) {
|
||||
$this->executingMulti = true;
|
||||
|
||||
try {
|
||||
$exec = \curl_multi_exec($this->_mh, $this->active);
|
||||
} finally {
|
||||
$this->executingMulti = false;
|
||||
$this->cleanupDeferredCancels();
|
||||
}
|
||||
|
||||
if ($exec === \CURLM_CALL_MULTI_PERFORM) {
|
||||
\curl_multi_select($this->_mh, 0);
|
||||
P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
|
||||
}
|
||||
|
|
@ -229,7 +286,7 @@ class CurlMultiHandler
|
|||
private function cancel($id): bool
|
||||
{
|
||||
if (!is_int($id)) {
|
||||
trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an integer to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
|
||||
\trigger_deprecation('guzzlehttp/guzzle', '7.4', 'Not passing an int to %s::%s() is deprecated and will cause an error in 8.0.', __CLASS__, __FUNCTION__);
|
||||
}
|
||||
|
||||
// Cannot cancel if it has been processed.
|
||||
|
|
@ -237,15 +294,42 @@ class CurlMultiHandler
|
|||
return false;
|
||||
}
|
||||
|
||||
$handle = $this->handles[$id]['easy']->handle;
|
||||
$easy = $this->handles[$id]['easy'];
|
||||
unset($this->delays[$id], $this->handles[$id]);
|
||||
|
||||
if ($this->executingMulti) {
|
||||
$this->deferredCancels[$id] = $easy;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->cleanupCancelledHandle($easy);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function cleanupDeferredCancels(): void
|
||||
{
|
||||
if ($this->deferredCancels === []) {
|
||||
return;
|
||||
}
|
||||
|
||||
$entries = $this->deferredCancels;
|
||||
$this->deferredCancels = [];
|
||||
|
||||
foreach ($entries as $easy) {
|
||||
$this->cleanupCancelledHandle($easy);
|
||||
}
|
||||
}
|
||||
|
||||
private function cleanupCancelledHandle(EasyHandle $easy): void
|
||||
{
|
||||
$handle = $easy->handle;
|
||||
\curl_multi_remove_handle($this->_mh, $handle);
|
||||
|
||||
if (PHP_VERSION_ID < 80000) {
|
||||
\curl_close($handle);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function processMessages(): void
|
||||
|
|
@ -255,6 +339,12 @@ class CurlMultiHandler
|
|||
// if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216
|
||||
continue;
|
||||
}
|
||||
if (!isset($done['handle'])) {
|
||||
// Work around a PHP issue where cancelled transfers may omit the handle.
|
||||
// Remove this once we no longer support PHP versions before the fix in
|
||||
// https://github.com/php/php-src/pull/16302.
|
||||
continue;
|
||||
}
|
||||
$id = (int) $done['handle'];
|
||||
\curl_multi_remove_handle($this->_mh, $done['handle']);
|
||||
|
||||
|
|
@ -266,9 +356,16 @@ class CurlMultiHandler
|
|||
$entry = $this->handles[$id];
|
||||
unset($this->handles[$id], $this->delays[$id]);
|
||||
$entry['easy']->errno = $done['result'];
|
||||
$entry['deferred']->resolve(
|
||||
CurlFactory::finish($this, $entry['easy'], $this->factory)
|
||||
);
|
||||
|
||||
try {
|
||||
$result = CurlFactory::finish($this, $entry['easy'], $this->factory);
|
||||
} catch (\Throwable $e) {
|
||||
$entry['deferred']->reject($e);
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$entry['deferred']->resolve($result);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
172
vendor/guzzlehttp/guzzle/src/Handler/CurlShareHandleState.php
vendored
Normal file
172
vendor/guzzlehttp/guzzle/src/Handler/CurlShareHandleState.php
vendored
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
<?php
|
||||
|
||||
namespace GuzzleHttp\Handler;
|
||||
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use GuzzleHttp\Utils;
|
||||
|
||||
/**
|
||||
* @internal
|
||||
*/
|
||||
final class CurlShareHandleState
|
||||
{
|
||||
/**
|
||||
* @var resource|\CurlShareHandle|null
|
||||
*/
|
||||
public $handle;
|
||||
|
||||
/**
|
||||
* @var string
|
||||
*/
|
||||
public $mode;
|
||||
|
||||
/**
|
||||
* @param resource|\CurlShareHandle|null $handle
|
||||
*/
|
||||
private function __construct(string $mode, $handle)
|
||||
{
|
||||
$this->mode = $mode;
|
||||
$this->handle = $handle;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sharing
|
||||
*/
|
||||
public static function fromOption($sharing): ?self
|
||||
{
|
||||
if ($sharing instanceof self) {
|
||||
return $sharing;
|
||||
}
|
||||
|
||||
$mode = self::normalizeMode($sharing, 'transport_sharing');
|
||||
if ($mode === TransportSharing::NONE) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($mode === TransportSharing::HANDLER_PREFER) {
|
||||
return self::createHandlerShareOrNull($mode);
|
||||
}
|
||||
|
||||
return self::createHandlerShare($mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $sharing
|
||||
*/
|
||||
public static function normalizeMode($sharing, string $option): string
|
||||
{
|
||||
if ($sharing instanceof self) {
|
||||
return $sharing->mode;
|
||||
}
|
||||
|
||||
if ($sharing === null || $sharing === TransportSharing::NONE) {
|
||||
return TransportSharing::NONE;
|
||||
}
|
||||
|
||||
if ($sharing === TransportSharing::HANDLER_PREFER || $sharing === TransportSharing::HANDLER_REQUIRE) {
|
||||
return $sharing;
|
||||
}
|
||||
|
||||
throw new \InvalidArgumentException(\sprintf(
|
||||
'The "%s" option must be null or a GuzzleHttp\\TransportSharing::* constant; received %s.',
|
||||
$option,
|
||||
Utils::describeType($sharing)
|
||||
));
|
||||
}
|
||||
|
||||
public static function assertNoRequiredSharingCustomFactoryConflict(array $options, string $handlerName): void
|
||||
{
|
||||
if (!\array_key_exists('handle_factory', $options) || $options['handle_factory'] === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$mode = self::normalizeMode($options['transport_sharing'] ?? null, 'transport_sharing');
|
||||
if ($mode !== TransportSharing::HANDLER_REQUIRE) {
|
||||
return;
|
||||
}
|
||||
|
||||
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
|
||||
));
|
||||
}
|
||||
|
||||
private static function createHandlerShareOrNull(string $mode): ?self
|
||||
{
|
||||
try {
|
||||
return self::createHandlerShare($mode);
|
||||
} catch (\Throwable $e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
self::requireCurlConstant('CURLOPT_SHARE');
|
||||
$shareOption = self::requireCurlConstant('CURLSHOPT_SHARE');
|
||||
$locks = self::handlerLocks();
|
||||
$handle = curl_share_init();
|
||||
|
||||
try {
|
||||
foreach ($locks as $lock) {
|
||||
try {
|
||||
$success = curl_share_setopt($handle, $shareOption, $lock);
|
||||
} catch (\Throwable $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));
|
||||
}
|
||||
}
|
||||
} catch (\Throwable $e) {
|
||||
self::closeHandlerShareHandleOnPhp7($handle);
|
||||
|
||||
throw $e;
|
||||
}
|
||||
|
||||
return new self($mode, $handle);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return int[]
|
||||
*/
|
||||
private static function handlerLocks(): array
|
||||
{
|
||||
return [
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_DNS'),
|
||||
self::requireCurlConstant('CURL_LOCK_DATA_SSL_SESSION'),
|
||||
];
|
||||
}
|
||||
|
||||
private static function requireCurlConstant(string $constant): int
|
||||
{
|
||||
if (!\defined($constant)) {
|
||||
throw new \InvalidArgumentException(\sprintf(
|
||||
'The "transport_sharing" option requires %s, but it is not available in the installed PHP cURL extension.',
|
||||
$constant
|
||||
));
|
||||
}
|
||||
|
||||
$value = \constant($constant);
|
||||
if (!\is_int($value)) {
|
||||
throw new \InvalidArgumentException(\sprintf('The cURL constant %s must resolve to an integer.', $constant));
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource|\CurlShareHandle $handle
|
||||
*/
|
||||
private static function closeHandlerShareHandleOnPhp7($handle): void
|
||||
{
|
||||
if (\PHP_VERSION_ID < 80000 && \is_resource($handle)) {
|
||||
curl_share_close($handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -56,7 +56,7 @@ final class EasyHandle
|
|||
public $onHeadersException;
|
||||
|
||||
/**
|
||||
* @var \Exception|null Exception during createResponse (if any)
|
||||
* @var \Throwable|null Exception during createResponse (if any)
|
||||
*/
|
||||
public $createResponseException;
|
||||
|
||||
|
|
@ -68,6 +68,8 @@ final class EasyHandle
|
|||
*/
|
||||
public function createResponse(): void
|
||||
{
|
||||
$this->response = null;
|
||||
|
||||
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($this->headers);
|
||||
|
||||
$normalizedKeys = Utils::normalizeHeaderKeys($headers);
|
||||
|
|
@ -80,7 +82,7 @@ final class EasyHandle
|
|||
|
||||
$bodyLength = (int) $this->sink->getSize();
|
||||
if ($bodyLength) {
|
||||
$headers[$normalizedKeys['content-length']] = $bodyLength;
|
||||
$headers[$normalizedKeys['content-length']] = [(string) $bodyLength];
|
||||
} else {
|
||||
unset($headers[$normalizedKeys['content-length']]);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,7 +24,14 @@ final class HeaderProcessor
|
|||
throw new \RuntimeException('Expected a non-empty array of header data');
|
||||
}
|
||||
|
||||
$parts = \explode(' ', \array_shift($headers), 3);
|
||||
$headers = self::getLastHeaderBlock(\array_values($headers));
|
||||
|
||||
$statusLine = \array_shift($headers);
|
||||
if ($statusLine === null) {
|
||||
throw new \RuntimeException('Expected a non-empty array of header data');
|
||||
}
|
||||
|
||||
$parts = \explode(' ', $statusLine, 3);
|
||||
$version = \explode('/', $parts[0])[1] ?? null;
|
||||
|
||||
if ($version === null) {
|
||||
|
|
@ -37,6 +44,34 @@ final class HeaderProcessor
|
|||
throw new \RuntimeException('HTTP status code missing from header data');
|
||||
}
|
||||
|
||||
if (!\preg_match('/^\d{3}$/', $status)) {
|
||||
throw new \RuntimeException('HTTP status code 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)];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param non-empty-list<string> $headers
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
private static function getLastHeaderBlock(array $headers): array
|
||||
{
|
||||
$lastStatusLine = 0;
|
||||
|
||||
foreach ($headers as $index => $line) {
|
||||
if (\preg_match('/^HTTP\/\S+\s+/i', $line)) {
|
||||
$lastStatusLine = $index;
|
||||
}
|
||||
}
|
||||
|
||||
return \array_slice($headers, $lastStatusLine);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ use GuzzleHttp\Promise\FulfilledPromise;
|
|||
use GuzzleHttp\Promise\PromiseInterface;
|
||||
use GuzzleHttp\Psr7;
|
||||
use GuzzleHttp\TransferStats;
|
||||
use GuzzleHttp\TransportSharing;
|
||||
use GuzzleHttp\Utils;
|
||||
use Psr\Http\Message\RequestInterface;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
|
|
@ -22,6 +23,24 @@ use Psr\Http\Message\UriInterface;
|
|||
*/
|
||||
class StreamHandler
|
||||
{
|
||||
private const CONNECTION_ERRORS = [
|
||||
'php_network_getaddresses:',
|
||||
'getaddrinfo',
|
||||
'gethostbyname failed',
|
||||
'Connection refused',
|
||||
'No connection could be made because the target machine actively refused it',
|
||||
"couldn't connect to host", // error on HHVM
|
||||
'connection attempt failed',
|
||||
'connect() failed',
|
||||
'Connection timed out',
|
||||
'Operation timed out',
|
||||
'Network is unreachable',
|
||||
'No route to host',
|
||||
'Host is unreachable',
|
||||
'Host is down',
|
||||
'Cannot connect to HTTPS server through proxy',
|
||||
];
|
||||
|
||||
/**
|
||||
* @var array
|
||||
*/
|
||||
|
|
@ -42,12 +61,21 @@ class StreamHandler
|
|||
|
||||
$protocolVersion = $request->getProtocolVersion();
|
||||
|
||||
if ('' === $protocolVersion) {
|
||||
\trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with an empty protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
|
||||
|
||||
$protocolVersion = '1.1';
|
||||
$request = Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
|
||||
}
|
||||
|
||||
if ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
|
||||
throw new ConnectException(sprintf('HTTP/%s is not supported by the stream handler.', $protocolVersion), $request);
|
||||
}
|
||||
|
||||
$startTime = isset($options['on_stats']) ? Utils::currentTime() : null;
|
||||
|
||||
self::triggerUnsupportedRequestOptionDeprecations($request, $options);
|
||||
|
||||
try {
|
||||
// Does not support the expect header.
|
||||
$request = $request->withoutHeader('Expect');
|
||||
|
|
@ -74,16 +102,10 @@ class StreamHandler
|
|||
throw $e;
|
||||
} catch (\Exception $e) {
|
||||
// Determine if the error was a networking error.
|
||||
$message = $e->getMessage();
|
||||
// This list can probably get more comprehensive.
|
||||
if (false !== \strpos($message, 'getaddrinfo') // DNS lookup failed
|
||||
|| false !== \strpos($message, 'Connection refused')
|
||||
|| false !== \strpos($message, "couldn't connect to host") // error on HHVM
|
||||
|| false !== \strpos($message, 'connection attempt failed')
|
||||
) {
|
||||
if (self::isConnectionError($e->getMessage())) {
|
||||
$e = new ConnectException($e->getMessage(), $request, $e);
|
||||
} else {
|
||||
$e = RequestException::wrapException($request, $e);
|
||||
$e = $e instanceof RequestException ? $e : new RequestException($e->getMessage(), $request, null, $e);
|
||||
}
|
||||
$this->invokeStats($options, $request, $startTime, null, $e);
|
||||
|
||||
|
|
@ -91,6 +113,17 @@ class StreamHandler
|
|||
}
|
||||
}
|
||||
|
||||
private static function isConnectionError(string $message): bool
|
||||
{
|
||||
foreach (self::CONNECTION_ERRORS as $connectionError) {
|
||||
if (false !== \strpos($message, $connectionError)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function invokeStats(
|
||||
array $options,
|
||||
RequestInterface $request,
|
||||
|
|
@ -114,10 +147,8 @@ class StreamHandler
|
|||
|
||||
try {
|
||||
[$ver, $status, $reason, $headers] = HeaderProcessor::parseHeaders($hdrs);
|
||||
} catch (\Exception $e) {
|
||||
return P\Create::rejectionFor(
|
||||
new RequestException('An error was encountered while creating the response', $request, null, $e)
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->rejectResponseCreation($options, $request, $startTime, $e);
|
||||
}
|
||||
|
||||
[$stream, $headers] = $this->checkDecode($options, $headers, $stream);
|
||||
|
|
@ -130,16 +161,14 @@ class StreamHandler
|
|||
|
||||
try {
|
||||
$response = new Psr7\Response($status, $headers, $sink, $ver, $reason);
|
||||
} catch (\Exception $e) {
|
||||
return P\Create::rejectionFor(
|
||||
new RequestException('An error was encountered while creating the response', $request, null, $e)
|
||||
);
|
||||
} catch (\Throwable $e) {
|
||||
return $this->rejectResponseCreation($options, $request, $startTime, $e);
|
||||
}
|
||||
|
||||
if (isset($options['on_headers'])) {
|
||||
try {
|
||||
$options['on_headers']($response);
|
||||
} catch (\Exception $e) {
|
||||
} catch (\Throwable $e) {
|
||||
return P\Create::rejectionFor(
|
||||
new RequestException('An error was encountered during the on_headers event', $request, $response, $e)
|
||||
);
|
||||
|
|
@ -157,6 +186,24 @@ class StreamHandler
|
|||
return new FulfilledPromise($response);
|
||||
}
|
||||
|
||||
private function rejectResponseCreation(
|
||||
array $options,
|
||||
RequestInterface $request,
|
||||
?float $startTime,
|
||||
\Throwable $previous
|
||||
): PromiseInterface {
|
||||
$reason = new RequestException(
|
||||
'An error was encountered while creating the response',
|
||||
$request,
|
||||
null,
|
||||
$previous
|
||||
);
|
||||
|
||||
$this->invokeStats($options, $request, $startTime, null, $reason);
|
||||
|
||||
return P\Create::rejectionFor($reason);
|
||||
}
|
||||
|
||||
private function createSink(StreamInterface $stream, array $options): StreamInterface
|
||||
{
|
||||
if (!empty($options['stream'])) {
|
||||
|
|
@ -185,15 +232,12 @@ class StreamHandler
|
|||
// Remove content-encoding header
|
||||
unset($headers[$normalizedKeys['content-encoding']]);
|
||||
|
||||
// Fix content-length header
|
||||
// The decoded length cannot be known without inflating the
|
||||
// stream, so keep the original length for inspection and
|
||||
// drop the now-unknown Content-Length header.
|
||||
if (isset($normalizedKeys['content-length'])) {
|
||||
$headers['x-encoded-content-length'] = $headers[$normalizedKeys['content-length']];
|
||||
$length = (int) $stream->getSize();
|
||||
if ($length === 0) {
|
||||
unset($headers[$normalizedKeys['content-length']]);
|
||||
} else {
|
||||
$headers[$normalizedKeys['content-length']] = [$length];
|
||||
}
|
||||
unset($headers[$normalizedKeys['content-length']]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -279,8 +323,14 @@ class StreamHandler
|
|||
$methods = \array_flip(\get_class_methods(__CLASS__));
|
||||
}
|
||||
|
||||
if (!\in_array($request->getUri()->getScheme(), ['http', 'https'])) {
|
||||
throw new RequestException(\sprintf("The scheme '%s' is not supported.", $request->getUri()->getScheme()), $request);
|
||||
$scheme = $request->getUri()->getScheme();
|
||||
if (!\in_array($scheme, ['http', 'https'], true)) {
|
||||
throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
|
||||
}
|
||||
|
||||
$protocols = Utils::normalizeProtocols($options['protocols'] ?? ['http', 'https']);
|
||||
if (!\in_array($scheme, $protocols, true)) {
|
||||
throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $request);
|
||||
}
|
||||
|
||||
// HTTP/1.1 streams using the PHP stream wrapper require a
|
||||
|
|
@ -338,7 +388,6 @@ class StreamHandler
|
|||
|
||||
// See https://wiki.php.net/rfc/deprecations_php_8_5#deprecate_the_http_response_header_predefined_variable
|
||||
if (function_exists('http_get_last_response_headers')) {
|
||||
/** @var array|null */
|
||||
$http_response_header = \http_get_last_response_headers();
|
||||
}
|
||||
|
||||
|
|
@ -423,6 +472,122 @@ class StreamHandler
|
|||
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
|
||||
&& $options['curl'] !== []
|
||||
&& !self::isCurlOptionGeneratedByAuth($options)
|
||||
) {
|
||||
\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 isCurlOptionGeneratedByAuth(array $options): bool
|
||||
{
|
||||
if (!isset($options['curl']) || !\is_array($options['curl']) || !isset($options['auth'][2]) || !\is_string($options['auth'][2])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!\defined('CURLOPT_HTTPAUTH') || !\defined('CURLOPT_USERPWD')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$type = \strtolower($options['auth'][2]);
|
||||
if ($type === 'digest') {
|
||||
$httpAuth = \defined('CURLAUTH_DIGEST') ? \constant('CURLAUTH_DIGEST') : null;
|
||||
} elseif ($type === 'ntlm') {
|
||||
$httpAuth = \defined('CURLAUTH_NTLM') ? \constant('CURLAUTH_NTLM') : null;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $httpAuth !== null
|
||||
&& \count($options['curl']) === 2
|
||||
&& isset($options['curl'][\CURLOPT_HTTPAUTH], $options['curl'][\CURLOPT_USERPWD])
|
||||
&& $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.
|
||||
*
|
||||
* @return array{0: string, 1: string|null}
|
||||
*/
|
||||
private static function normalizeTlsFileOption(string $option, $value): array
|
||||
{
|
||||
$passphrase = null;
|
||||
|
||||
if (\is_array($value)) {
|
||||
if (!isset($value[0]) || !\is_string($value[0])) {
|
||||
throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
|
||||
}
|
||||
if (isset($value[1])) {
|
||||
if (!\is_string($value[1])) {
|
||||
throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
|
||||
}
|
||||
$passphrase = $value[1];
|
||||
}
|
||||
$value = $value[0];
|
||||
}
|
||||
|
||||
if (!\is_string($value)) {
|
||||
throw new \InvalidArgumentException(\sprintf('Invalid %s request option', $option));
|
||||
}
|
||||
|
||||
return [$value, $passphrase];
|
||||
}
|
||||
|
||||
private static function setTlsPassphrase(array &$options, ?string $passphrase, string $option): void
|
||||
{
|
||||
if ($passphrase === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isset($options['ssl']['passphrase']) && $options['ssl']['passphrase'] !== $passphrase) {
|
||||
throw new \InvalidArgumentException(\sprintf('Cannot use different passphrases for cert and ssl_key with the stream handler; %s conflicts with an existing TLS passphrase.', $option));
|
||||
}
|
||||
|
||||
$options['ssl']['passphrase'] = $passphrase;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value as passed via Request transfer options.
|
||||
*/
|
||||
private static function assertStreamTlsType(string $option, $value): void
|
||||
{
|
||||
if (!\is_string($value) || $value === '') {
|
||||
throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
|
||||
}
|
||||
|
||||
if (\strtoupper($value) !== 'PEM') {
|
||||
throw new \InvalidArgumentException(\sprintf('The stream handler only supports "PEM" for the %s request option.', $option));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value as passed via Request transfer options.
|
||||
*/
|
||||
|
|
@ -435,7 +600,10 @@ class StreamHandler
|
|||
} else {
|
||||
$scheme = $request->getUri()->getScheme();
|
||||
if (isset($value[$scheme])) {
|
||||
if (!isset($value['no']) || !Utils::isHostInNoProxy($request->getUri()->getHost(), $value['no'])) {
|
||||
if (
|
||||
!isset($value['no'])
|
||||
|| !Utils::isUriInNoProxy($request->getUri(), $value['no'])
|
||||
) {
|
||||
$uri = $value[$scheme];
|
||||
}
|
||||
}
|
||||
|
|
@ -544,23 +712,56 @@ class StreamHandler
|
|||
*/
|
||||
private function add_cert(RequestInterface $request, array &$options, $value, array &$params): void
|
||||
{
|
||||
if (\is_array($value)) {
|
||||
$options['ssl']['passphrase'] = $value[1];
|
||||
$value = $value[0];
|
||||
}
|
||||
[$value, $passphrase] = self::normalizeTlsFileOption('cert', $value);
|
||||
|
||||
if (!\file_exists($value)) {
|
||||
throw new \RuntimeException("SSL certificate not found: {$value}");
|
||||
}
|
||||
|
||||
self::setTlsPassphrase($options, $passphrase, 'cert');
|
||||
$options['ssl']['local_cert'] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value as passed via Request transfer options.
|
||||
*/
|
||||
private function add_cert_type(RequestInterface $request, array &$options, $value, array &$params): void
|
||||
{
|
||||
self::assertStreamTlsType('cert_type', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value as passed via Request transfer options.
|
||||
*/
|
||||
private function add_ssl_key(RequestInterface $request, array &$options, $value, array &$params): void
|
||||
{
|
||||
[$value, $passphrase] = self::normalizeTlsFileOption('ssl_key', $value);
|
||||
|
||||
if (!\file_exists($value)) {
|
||||
throw new \RuntimeException("SSL private key not found: {$value}");
|
||||
}
|
||||
|
||||
self::setTlsPassphrase($options, $passphrase, 'ssl_key');
|
||||
$options['ssl']['local_pk'] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value as passed via Request transfer options.
|
||||
*/
|
||||
private function add_ssl_key_type(RequestInterface $request, array &$options, $value, array &$params): void
|
||||
{
|
||||
self::assertStreamTlsType('ssl_key_type', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mixed $value as passed via Request transfer options.
|
||||
*/
|
||||
private function add_progress(RequestInterface $request, array &$options, $value, array &$params): void
|
||||
{
|
||||
if (!\is_callable($value)) {
|
||||
throw new \InvalidArgumentException('progress client option must be callable');
|
||||
}
|
||||
|
||||
self::addNotification(
|
||||
$params,
|
||||
static function ($code, $a, $b, $c, $transferred, $total) use ($value) {
|
||||
|
|
|
|||
Loading…
Reference in a new issue