框架升级及修复升级后的bug

This commit is contained in:
Dev
2026-10-16 18:13:09 +08:00
parent dafb0c96c0
commit 2d342bcbd7
537 changed files with 49836 additions and 40933 deletions
@@ -0,0 +1,148 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Internal;
use Amp\ByteStream\InputStream;
use Amp\ByteStream\ResourceInputStream;
use Amp\Http\Client\RequestBody;
use Amp\Promise;
use Amp\Success;
use Symfony\Component\HttpClient\Exception\TransportException;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class AmpBodyV4 implements RequestBody, InputStream
{
private ResourceInputStream|\Closure|string $body;
private array $info;
private ?int $offset = 0;
private int $length = -1;
private ?int $uploaded = null;
/**
* @param \Closure|resource|string $body
*/
public function __construct(
$body,
&$info,
private \Closure $onProgress,
) {
$this->info = &$info;
if (\is_resource($body)) {
$this->offset = ftell($body);
$this->length = fstat($body)['size'];
$this->body = new ResourceInputStream($body);
} elseif (\is_string($body)) {
$this->length = \strlen($body);
$this->body = $body;
} else {
$this->body = $body;
}
}
public function createBodyStream(): InputStream
{
if (null !== $this->uploaded) {
$this->uploaded = null;
if (\is_string($this->body)) {
$this->offset = 0;
} elseif ($this->body instanceof ResourceInputStream) {
fseek($this->body->getResource(), $this->offset);
}
}
return $this;
}
public function getHeaders(): Promise
{
return new Success([]);
}
public function getBodyLength(): Promise
{
return new Success($this->length - $this->offset);
}
public function read(): Promise
{
$this->info['size_upload'] += $this->uploaded;
$this->uploaded = 0;
($this->onProgress)();
$chunk = $this->doRead();
$chunk->onResolve(function ($e, $data) {
if (null !== $data) {
$this->uploaded = \strlen($data);
} else {
$this->info['upload_content_length'] = $this->info['size_upload'];
}
});
return $chunk;
}
public static function rewind(RequestBody $body): RequestBody
{
if (!$body instanceof self) {
return $body;
}
$body->uploaded = null;
if ($body->body instanceof ResourceInputStream) {
fseek($body->body->getResource(), $body->offset);
return new $body($body->body, $body->info, $body->onProgress);
}
if (\is_string($body->body)) {
$body->offset = 0;
}
return $body;
}
private function doRead(): Promise
{
if ($this->body instanceof ResourceInputStream) {
return $this->body->read();
}
if (null === $this->offset || !$this->length) {
return new Success();
}
if (\is_string($this->body)) {
$this->offset = null;
return new Success($this->body);
}
if ('' === $data = ($this->body)(16372)) {
$this->offset = null;
return new Success();
}
if (!\is_string($data)) {
throw new TransportException(\sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
}
return new Success($data);
}
}
@@ -24,7 +24,7 @@ use Symfony\Component\HttpClient\Exception\TransportException;
*
* @internal
*/
class AmpBody implements HttpContent, ReadableStream, \IteratorAggregate
class AmpBodyV5 implements HttpContent, ReadableStream, \IteratorAggregate
{
private ReadableStream $body;
private ?string $content;
@@ -0,0 +1,215 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Internal;
use Amp\CancellationToken;
use Amp\Deferred;
use Amp\Http\Client\Connection\ConnectionLimitingPool;
use Amp\Http\Client\Connection\DefaultConnectionFactory;
use Amp\Http\Client\InterceptedHttpClient;
use Amp\Http\Client\Interceptor\RetryRequests;
use Amp\Http\Client\PooledHttpClient;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Amp\Http\Tunnel\Http1TunnelConnector;
use Amp\Http\Tunnel\Https1TunnelConnector;
use Amp\Promise;
use Amp\Socket\Certificate;
use Amp\Socket\ClientTlsContext;
use Amp\Socket\ConnectContext;
use Amp\Socket\Connector;
use Amp\Socket\DnsConnector;
use Amp\Socket\SocketAddress;
use Amp\Success;
use Psr\Log\LoggerInterface;
/**
* Internal representation of the Amp client's state.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
final class AmpClientStateV4 extends ClientState
{
public array $dnsCache = [];
public int $responseCount = 0;
public array $pushedResponses = [];
private array $clients = [];
private \Closure $clientConfigurator;
public function __construct(
?callable $clientConfigurator,
private int $maxHostConnections,
private int $maxPendingPushes,
private ?LoggerInterface &$logger,
) {
$clientConfigurator ??= static fn (PooledHttpClient $client) => new InterceptedHttpClient($client, new RetryRequests(2));
$this->clientConfigurator = $clientConfigurator(...);
}
/**
* @return Promise<Response>
*/
public function request(array $options, Request $request, CancellationToken $cancellation, array &$info, \Closure $onProgress, &$handle): Promise
{
if ($options['proxy']) {
if ($request->hasHeader('proxy-authorization')) {
$options['proxy']['auth'] = $request->getHeader('proxy-authorization');
}
// Matching "no_proxy" should follow the behavior of curl
$host = $request->getUri()->getHost();
foreach ($options['proxy']['no_proxy'] as $rule) {
$dotRule = '.'.ltrim($rule, '.');
if ('*' === $rule || $host === $rule || str_ends_with($host, $dotRule)) {
$options['proxy'] = null;
break;
}
}
}
$request = clone $request;
if ($request->hasHeader('proxy-authorization')) {
$request->removeHeader('proxy-authorization');
}
if ($options['capture_peer_cert_chain']) {
$info['peer_certificate_chain'] = [];
}
$request->addEventListener(new AmpListenerV4($info, $options['peer_fingerprint']['pin-sha256'] ?? [], $onProgress, $handle));
$request->setPushHandler(fn ($request, $response): Promise => $this->handlePush($request, $response, $options));
($request->hasHeader('content-length') ? new Success((int) $request->getHeader('content-length')) : $request->getBody()->getBodyLength())
->onResolve(static function ($e, $bodySize) use (&$info) {
if (null !== $bodySize && 0 <= $bodySize) {
$info['upload_content_length'] = ((1 + $info['upload_content_length']) ?? 1) - 1 + $bodySize;
}
});
[$client, $connector] = $this->getClient($options);
$response = $client->request($request, $cancellation);
$response->onResolve(static function ($e) use ($connector, &$handle) {
if (null === $e) {
$handle = $connector->handle;
}
});
return $response;
}
private function getClient(array $options): array
{
$options = [
'bindto' => $options['bindto'] ?: '0',
'verify_peer' => $options['verify_peer'],
'capath' => $options['capath'],
'cafile' => $options['cafile'],
'local_cert' => $options['local_cert'],
'local_pk' => $options['local_pk'],
'ciphers' => $options['ciphers'],
'capture_peer_cert_chain' => $options['capture_peer_cert_chain'] || $options['peer_fingerprint'],
'proxy' => $options['proxy'],
'crypto_method' => $options['crypto_method'],
];
$key = hash('xxh128', serialize($options));
if (isset($this->clients[$key])) {
return $this->clients[$key];
}
$context = new ClientTlsContext('');
$options['verify_peer'] || $context = $context->withoutPeerVerification();
$options['cafile'] && $context = $context->withCaFile($options['cafile']);
$options['capath'] && $context = $context->withCaPath($options['capath']);
$options['local_cert'] && $context = $context->withCertificate(new Certificate($options['local_cert'], $options['local_pk']));
$options['ciphers'] && $context = $context->withCiphers($options['ciphers']);
$options['capture_peer_cert_chain'] && $context = $context->withPeerCapturing();
$options['crypto_method'] && $context = $context->withMinimumVersion($options['crypto_method']);
$connector = $handleConnector = new class implements Connector {
public DnsConnector $connector;
public string $uri;
/** @var resource|null */
public $handle;
public function connect(string $uri, ?ConnectContext $context = null, ?CancellationToken $token = null): Promise
{
$result = $this->connector->connect($this->uri ?? $uri, $context, $token);
$result->onResolve(function ($e, $socket) {
$this->handle = $socket?->getResource();
});
return $result;
}
};
$connector->connector = new DnsConnector(new AmpResolverV4($this->dnsCache));
$context = (new ConnectContext())
->withTcpNoDelay()
->withTlsContext($context);
if ($options['bindto']) {
if (file_exists($options['bindto'])) {
$connector->uri = 'unix://'.$options['bindto'];
} else {
$context = $context->withBindTo($options['bindto']);
}
}
if ($options['proxy']) {
$proxyUrl = parse_url($options['proxy']['url']);
$proxySocket = new SocketAddress($proxyUrl['host'], $proxyUrl['port']);
$proxyHeaders = $options['proxy']['auth'] ? ['Proxy-Authorization' => $options['proxy']['auth']] : [];
if ('ssl' === $proxyUrl['scheme']) {
$connector = new Https1TunnelConnector($proxySocket, $context->getTlsContext(), $proxyHeaders, $connector);
} else {
$connector = new Http1TunnelConnector($proxySocket, $proxyHeaders, $connector);
}
}
$maxHostConnections = 0 < $this->maxHostConnections ? $this->maxHostConnections : \PHP_INT_MAX;
$pool = new DefaultConnectionFactory($connector, $context);
$pool = ConnectionLimitingPool::byAuthority($maxHostConnections, $pool);
return $this->clients[$key] = [($this->clientConfigurator)(new PooledHttpClient($pool)), $handleConnector];
}
private function handlePush(Request $request, Promise $response, array $options): Promise
{
$deferred = new Deferred();
$authority = $request->getUri()->getAuthority();
if ($this->maxPendingPushes <= \count($this->pushedResponses[$authority] ?? [])) {
$fifoUrl = key($this->pushedResponses[$authority]);
unset($this->pushedResponses[$authority][$fifoUrl]);
$this->logger?->debug(\sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
}
$url = (string) $request->getUri();
$this->logger?->debug(\sprintf('Queueing pushed response: "%s"', $url));
$this->pushedResponses[$authority][] = [$url, $deferred, $request, $response, [
'proxy' => $options['proxy'],
'bindto' => $options['bindto'],
'local_cert' => $options['local_cert'],
'local_pk' => $options['local_pk'],
]];
return $deferred->promise();
}
}
@@ -13,7 +13,6 @@ namespace Symfony\Component\HttpClient\Internal;
use Amp\ByteStream\ResourceStream;
use Amp\Cancellation;
use Amp\DeferredCancellation;
use Amp\DeferredFuture;
use Amp\Future;
use Amp\Http\Client\Connection\ConnectionLimitingPool;
@@ -42,7 +41,7 @@ use Psr\Log\LoggerInterface;
*
* @internal
*/
final class AmpClientState extends ClientState
final class AmpClientStateV5 extends ClientState
{
public array $dnsCache = [];
public int $responseCount = 0;
@@ -61,7 +60,7 @@ final class AmpClientState extends ClientState
$this->clientConfigurator = $clientConfigurator(...);
}
public function request(array $options, Request $request, DeferredCancellation $canceller, array &$info, \Closure $onProgress, &$handle): Response
public function request(array $options, Request $request, Cancellation $cancellation, array &$info, \Closure $onProgress, &$handle): Response
{
if ($options['proxy']) {
if ($request->hasHeader('proxy-authorization')) {
@@ -88,7 +87,7 @@ final class AmpClientState extends ClientState
$info['peer_certificate_chain'] = [];
}
$request->addEventListener(new AmpListener($info, $options['peer_fingerprint']['pin-sha256'] ?? [], $onProgress, $handle, $options['max_connect_duration'], $canceller));
$request->addEventListener(new AmpListenerV5($info, $options['peer_fingerprint']['pin-sha256'] ?? [], $onProgress, $handle));
$request->setPushHandler(fn ($request, $response) => $this->handlePush($request, $response, $options));
if (0 <= $bodySize = $request->hasHeader('content-length') ? (int) $request->getHeader('content-length') : $request->getBody()->getContentLength() ?? -1) {
@@ -96,7 +95,7 @@ final class AmpClientState extends ClientState
}
[$client, $connector] = $this->getClient($options);
$response = $client->request($request, $canceller->getCancellation());
$response = $client->request($request, $cancellation);
$handle = $connector->handle;
return $response;
@@ -146,7 +145,7 @@ final class AmpClientState extends ClientState
return $socket;
}
};
$connector->connector = new DnsSocketConnector(new AmpResolver($this->dnsCache));
$connector->connector = new DnsSocketConnector(new AmpResolverV5($this->dnsCache));
$context = (new ConnectContext())
->withTcpNoDelay()
@@ -0,0 +1,184 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Internal;
use Amp\Http\Client\Connection\Stream;
use Amp\Http\Client\EventListener;
use Amp\Http\Client\Request;
use Amp\Promise;
use Amp\Success;
use Symfony\Component\HttpClient\Exception\TransportException;
/**
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class AmpListenerV4 implements EventListener
{
private array $info;
/**
* @param resource|null $handle
*/
public function __construct(
array &$info,
private array $pinSha256,
private \Closure $onProgress,
private &$handle,
) {
$info += [
'connect_time' => 0.0,
'pretransfer_time' => 0.0,
'starttransfer_time' => 0.0,
'total_time' => 0.0,
'namelookup_time' => 0.0,
'primary_ip' => '',
'primary_port' => 0,
];
$this->info = &$info;
}
public function startRequest(Request $request): Promise
{
$this->info['start_time'] ??= microtime(true);
($this->onProgress)();
return new Success();
}
public function startDnsResolution(Request $request): Promise
{
($this->onProgress)();
return new Success();
}
public function startConnectionCreation(Request $request): Promise
{
($this->onProgress)();
return new Success();
}
public function startTlsNegotiation(Request $request): Promise
{
($this->onProgress)();
return new Success();
}
public function startSendingRequest(Request $request, Stream $stream): Promise
{
$host = $stream->getRemoteAddress()->getHost();
$this->info['primary_ip'] = $host;
if (str_contains($host, ':')) {
$host = '['.$host.']';
}
$this->info['primary_port'] = $stream->getRemoteAddress()->getPort();
$this->info['pretransfer_time'] = microtime(true) - $this->info['start_time'];
$this->info['debug'] .= \sprintf("* Connected to %s (%s) port %d\n", $request->getUri()->getHost(), $host, $this->info['primary_port']);
if ((isset($this->info['peer_certificate_chain']) || $this->pinSha256) && null !== $tlsInfo = $stream->getTlsInfo()) {
foreach ($tlsInfo->getPeerCertificates() as $cert) {
$this->info['peer_certificate_chain'][] = openssl_x509_read($cert->toPem());
}
if ($this->pinSha256) {
$pin = openssl_pkey_get_public($this->info['peer_certificate_chain'][0]);
$pin = openssl_pkey_get_details($pin)['key'];
$pin = \array_slice(explode("\n", $pin), 1, -2);
$pin = base64_decode(implode('', $pin));
$pin = base64_encode(hash('sha256', $pin, true));
if (!\in_array($pin, $this->pinSha256, true)) {
throw new TransportException(\sprintf('SSL public key does not match pinned public key for "%s".', $this->info['url']));
}
}
}
($this->onProgress)();
$uri = $request->getUri();
$requestUri = $uri->getPath() ?: '/';
if ('' !== $query = $uri->getQuery()) {
$requestUri .= '?'.$query;
}
if ('CONNECT' === $method = $request->getMethod()) {
$requestUri = $uri->getHost().': '.($uri->getPort() ?? ('https' === $uri->getScheme() ? 443 : 80));
}
$this->info['debug'] .= \sprintf("> %s %s HTTP/%s \r\n", $method, $requestUri, $request->getProtocolVersions()[0]);
foreach ($request->getRawHeaders() as [$name, $value]) {
$this->info['debug'] .= $name.': '.$value."\r\n";
}
$this->info['debug'] .= "\r\n";
return new Success();
}
public function completeSendingRequest(Request $request, Stream $stream): Promise
{
($this->onProgress)();
return new Success();
}
public function startReceivingResponse(Request $request, Stream $stream): Promise
{
$this->info['starttransfer_time'] = microtime(true) - $this->info['start_time'];
($this->onProgress)();
return new Success();
}
public function completeReceivingResponse(Request $request, Stream $stream): Promise
{
$this->handle = null;
($this->onProgress)();
return new Success();
}
public function completeDnsResolution(Request $request): Promise
{
$this->info['namelookup_time'] = microtime(true) - $this->info['start_time'];
($this->onProgress)();
return new Success();
}
public function completeConnectionCreation(Request $request): Promise
{
$this->info['connect_time'] = microtime(true) - $this->info['start_time'];
($this->onProgress)();
return new Success();
}
public function completeTlsNegotiation(Request $request): Promise
{
($this->onProgress)();
return new Success();
}
public function abort(Request $request, \Throwable $cause): Promise
{
return new Success();
}
}
@@ -11,7 +11,6 @@
namespace Symfony\Component\HttpClient\Internal;
use Amp\DeferredCancellation;
use Amp\Http\Client\ApplicationInterceptor;
use Amp\Http\Client\Connection\Connection;
use Amp\Http\Client\Connection\Stream;
@@ -20,7 +19,6 @@ use Amp\Http\Client\NetworkInterceptor;
use Amp\Http\Client\Request;
use Amp\Http\Client\Response;
use Amp\Socket\InternetAddress;
use Revolt\EventLoop;
use Symfony\Component\HttpClient\Exception\TransportException;
/**
@@ -28,10 +26,9 @@ use Symfony\Component\HttpClient\Exception\TransportException;
*
* @internal
*/
class AmpListener implements EventListener
class AmpListenerV5 implements EventListener
{
private array $info;
private ?string $connectTimerId = null;
/**
* @param resource|null $handle
@@ -41,8 +38,6 @@ class AmpListener implements EventListener
private array $pinSha256,
private \Closure $onProgress,
private &$handle,
private float $maxConnectDuration,
private DeferredCancellation $canceller,
) {
$info += [
'connect_time' => 0.0,
@@ -60,23 +55,11 @@ class AmpListener implements EventListener
public function requestStart(Request $request): void
{
$this->info['start_time'] ??= microtime(true);
if (0 < $this->maxConnectDuration) {
$this->connectTimerId = EventLoop::delay($this->maxConnectDuration, function (): void {
$this->canceller->cancel(new TransportException(\sprintf('Max connect duration was reached for "%s".', $this->info['url'])));
});
}
($this->onProgress)();
}
public function connectionAcquired(Request $request, Connection $connection, int $streamCount): void
{
if (null !== $this->connectTimerId) {
EventLoop::cancel($this->connectTimerId);
$this->connectTimerId = null;
}
$this->info['namelookup_time'] = microtime(true) - $this->info['start_time']; // see https://github.com/amphp/socket/issues/114
$this->info['connect_time'] = microtime(true) - $this->info['start_time'];
($this->onProgress)();
@@ -154,11 +137,6 @@ class AmpListener implements EventListener
public function requestFailed(Request $request, \Throwable $exception): void
{
if (null !== $this->connectTimerId) {
EventLoop::cancel($this->connectTimerId);
$this->connectTimerId = null;
}
$this->handle = null;
($this->onProgress)();
}
@@ -223,11 +201,6 @@ class AmpListener implements EventListener
public function requestRejected(Request $request): void
{
if (null !== $this->connectTimerId) {
EventLoop::cancel($this->connectTimerId);
$this->connectTimerId = null;
}
$this->handle = null;
($this->onProgress)();
}
@@ -0,0 +1,62 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Internal;
use Amp\Dns;
use Amp\Dns\Record;
use Amp\Promise;
use Amp\Success;
/**
* Handles local overrides for the DNS resolver.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
class AmpResolverV4 implements Dns\Resolver
{
public function __construct(
private array &$dnsMap,
) {
}
public function resolve(string $name, ?int $typeRestriction = null): Promise
{
$recordType = Record::A;
$ip = $this->dnsMap[$name] ?? null;
if (null !== $ip && str_contains($ip, ':')) {
$recordType = Record::AAAA;
}
if (null === $ip || $recordType !== ($typeRestriction ?? $recordType)) {
return Dns\resolver()->resolve($name, $typeRestriction);
}
return new Success([new Record($ip, $recordType, null)]);
}
public function query(string $name, int $type): Promise
{
$recordType = Record::A;
$ip = $this->dnsMap[$name] ?? null;
if (null !== $ip && str_contains($ip, ':')) {
$recordType = Record::AAAA;
}
if (null === $ip || $recordType !== $type) {
return Dns\resolver()->query($name, $type);
}
return new Success([new Record($ip, $recordType, null)]);
}
}
@@ -23,7 +23,7 @@ use Amp\Dns\DnsResolver;
*
* @internal
*/
class AmpResolver implements DnsResolver
class AmpResolverV5 implements DnsResolver
{
public function __construct(
private array &$dnsMap,
@@ -25,7 +25,6 @@ final class CurlClientState extends ClientState
{
public ?\CurlMultiHandle $handle;
public ?\CurlShareHandle $share;
public \CurlShareHandle|\CurlSharePersistentHandle|null $persistentShare;
public bool $performing = false;
/** @var PushedResponse[] */
@@ -48,8 +47,8 @@ final class CurlClientState extends ClientState
self::$curlVersion ??= curl_version();
$this->dnsCache = new DnsCache();
// handle, share and persistentShare are initialized lazily in __get()
unset($this->handle, $this->share, $this->persistentShare);
// handle and share are initialized lazily in __get()
unset($this->handle, $this->share);
}
public static function originKey(string $scheme, string $host, ?int $port = null): string
@@ -78,20 +77,9 @@ final class CurlClientState extends ClientState
public function __get(string $name): mixed
{
if ('persistentShare' === $name) {
if (\PHP_VERSION_ID < 80500) {
return $this->persistentShare = $this->share;
}
return $this->persistentShare = curl_share_init_persistent([
\CURL_LOCK_DATA_DNS,
\CURL_LOCK_DATA_SSL_SESSION,
\CURL_LOCK_DATA_CONNECT,
]);
}
if ('share' === $name) {
$this->share = curl_share_init();
curl_share_setopt($this->share, \CURLSHOPT_SHARE, \CURL_LOCK_DATA_DNS);
curl_share_setopt($this->share, \CURLSHOPT_SHARE, \CURL_LOCK_DATA_SSL_SESSION);
@@ -124,7 +112,6 @@ final class CurlClientState extends ClientState
$multi = clone $this;
$multi->handle = null;
$multi->share = null;
$multi->persistentShare = null;
$multi->pushedResponses = &$this->pushedResponses;
$multi->logger = &$this->logger;
$multi->handlesActivity = &$this->handlesActivity;
@@ -1,98 +0,0 @@
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpClient\Internal;
use Symfony\Component\HttpClient\Response\AsyncContext;
use Symfony\Component\HttpClient\Response\AsyncResponse;
use Symfony\Contracts\HttpClient\ChunkInterface;
/**
* Follows redirections in userland so that decorators can inspect each hop.
*
* @author Nicolas Grekas <p@tchwork.com>
*
* @internal
*/
trait FollowRedirectsTrait
{
/**
* @param string $url An already prepared, absolute URL
* @param string $host The host name found in $url
* @param \Closure(string $host, string $url, array &$options): void $onRedirect Called before each followed redirect
*/
private function followRedirects(string $method, string $url, string $host, array $options, \Closure $onRedirect): AsyncResponse
{
if (0 >= $maxRedirects = $options['max_redirects']) {
return new AsyncResponse($this->client, $method, $url, $options);
}
$options['max_redirects'] = 0;
$redirectHeaders = [
'scheme' => parse_url($url, \PHP_URL_SCHEME),
'host' => $host,
'port' => parse_url($url, \PHP_URL_PORT),
'with_auth' => $options['headers'],
'no_auth' => $options['headers'],
];
if (isset($options['normalized_headers']['host']) || isset($options['normalized_headers']['authorization']) || isset($options['normalized_headers']['cookie'])) {
$redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], static fn ($h) => 0 !== stripos($h, 'Host:') && 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:'));
}
return new AsyncResponse($this->client, $method, $url, $options, static function (ChunkInterface $chunk, AsyncContext $context) use (&$method, &$options, $maxRedirects, &$redirectHeaders, $onRedirect): \Generator {
if (null !== $chunk->getError() || $chunk->isTimeout() || !$chunk->isFirst()) {
yield $chunk;
return;
}
$statusCode = $context->getStatusCode();
if ($statusCode < 300 || 400 <= $statusCode || null === $url = $context->getInfo('redirect_url')) {
$context->passthru();
yield $chunk;
return;
}
$host = parse_url($url, \PHP_URL_HOST);
$onRedirect($host, $url, $options);
// Do like curl and browsers: turn POST to GET on 301, 302 and 303
if (303 === $statusCode || 'POST' === $method && \in_array($statusCode, [301, 302], true)) {
$method = 'HEAD' === $method ? 'HEAD' : 'GET';
unset($options['body'], $options['json']);
if (isset($options['normalized_headers']['content-length']) || isset($options['normalized_headers']['content-type']) || isset($options['normalized_headers']['transfer-encoding'])) {
$filterContentHeaders = static fn ($h) => 0 !== stripos($h, 'Content-Length:') && 0 !== stripos($h, 'Content-Type:') && 0 !== stripos($h, 'Transfer-Encoding:');
$options['headers'] = array_filter($options['headers'], $filterContentHeaders);
$redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], $filterContentHeaders);
$redirectHeaders['with_auth'] = array_filter($redirectHeaders['with_auth'], $filterContentHeaders);
}
}
// Authorization and Cookie headers MUST NOT follow except for the initial scheme, host and port
$port = parse_url($url, \PHP_URL_PORT);
$options['headers'] = parse_url($url, \PHP_URL_SCHEME) === $redirectHeaders['scheme'] && $redirectHeaders['host'] === $host && ($redirectHeaders['port'] ?? null) === $port ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth'];
static $redirectCount = 0;
$context->setInfo('redirect_count', ++$redirectCount);
$context->replaceRequest($method, $url, $options);
if ($redirectCount >= $maxRedirects) {
$context->passthru();
}
});
}
}