vendor/guzzlehttp/guzzle/src/Handler/CurlMultiHandler.php

1452 lines · 58047 bytes

   1<?php
   2
   3namespace GuzzleHttp\Handler;
   4
   5use Closure;
   6use GuzzleHttp\Exception\RequestException;
   7use GuzzleHttp\Multiplexing;
   8use GuzzleHttp\Promise as P;
   9use GuzzleHttp\Promise\Promise;
  10use GuzzleHttp\Promise\PromiseInterface;
  11use GuzzleHttp\Psr7;
  12use GuzzleHttp\TransportSharing;
  13use GuzzleHttp\Utils;
  14use Psr\Http\Message\RequestInterface;
  15
  16/**
  17 * Returns an asynchronous response using curl_multi_* functions.
  18 *
  19 * When using the CurlMultiHandler, custom curl options can be specified as an
  20 * associative array of curl option constants mapping to values in the
  21 * **curl** key of the provided request options.
  22 *
  23 * @final
  24 */
  25class CurlMultiHandler
  26{
  27    private const KNOWN_CONSTRUCTOR_OPTIONS = [
  28        'handle_factory' => true,
  29        'max_host_connections' => true,
  30        'max_total_connections' => true,
  31        'multiplex' => true,
  32        'options' => true,
  33        'select_timeout' => true,
  34        'transport_sharing' => true,
  35    ];
  36
  37    private const CONNECTION_CAP_OPTIONS = [
  38        'max_host_connections' => 'CURLMOPT_MAX_HOST_CONNECTIONS',
  39        'max_total_connections' => 'CURLMOPT_MAX_TOTAL_CONNECTIONS',
  40    ];
  41
  42    /**
  43     * cURL options that isolate a transfer from foreign proxy tunnel
  44     * connections. Failing to apply either one would fall open into
  45     * credential-bearing connection reuse.
  46     */
  47    private const PROXY_TUNNEL_ISOLATION_OPTIONS = [
  48        'CURLOPT_FRESH_CONNECT',
  49        'CURLOPT_FORBID_REUSE',
  50    ];
  51
  52    /**
  53     * @var CurlFactoryInterface
  54     */
  55    private $factory;
  56
  57    /**
  58     * @var CurlShareHandleState|null
  59     */
  60    private $shareHandleState;
  61
  62    /**
  63     * @var int
  64     */
  65    private $selectTimeout;
  66
  67    /**
  68     * @var int Will be higher than 0 when `curl_multi_exec` is still running.
  69     */
  70    private $active = 0;
  71
  72    /**
  73     * @var array Request entry handles, indexed by handle id in `addRequest`.
  74     *
  75     * @see CurlMultiHandler::addRequest
  76     */
  77    private $handles = [];
  78
  79    /**
  80     * @var array<int, float> An array of delay times, indexed by handle id in `addRequest`.
  81     *
  82     * @see CurlMultiHandler::addRequest
  83     */
  84    private $delays = [];
  85
  86    /**
  87     * @var array<mixed> An associative array of CURLMOPT_* options and corresponding values for curl_multi_setopt()
  88     */
  89    private $options = [];
  90
  91    /**
  92     * @var array<int, true> Native options derived from first-class
  93     *                       constructor options; failing to apply one is an
  94     *                       error rather than a compatibility warning.
  95     */
  96    private $requiredOptions = [];
  97
  98    /**
  99     * @var bool Whether any connection cap constructor option was applied
 100     */
 101    private $connectionCapsApplied = false;
 102
 103    /**
 104     * @var bool Whether the "multiplex" constructor option disabled
 105     *           multiplexing on this handler's multi handle
 106     */
 107    private $multiplexDisabled = false;
 108
 109    /**
 110     * @var bool Whether a custom "handle_factory" constructor option supplies
 111     *           the easy handles
 112     */
 113    private $customHandleFactory = false;
 114
 115    /** @var resource|\CurlMultiHandle */
 116    private $_mh;
 117
 118    /**
 119     * @var int Depth of nested guarded native operations (execution and
 120     *          handle removal, both of which can run user callbacks). A
 121     *          callback can re-enter tick(), and the nested frame must not
 122     *          clear the outer frame's guard; deferred work stays parked
 123     *          until the outermost frame unwinds.
 124     */
 125    private $multiExecDepth = 0;
 126
 127    /**
 128     * @var bool Guards finishDeferredWork() against re-entry from the
 129     *           guarded native removals it performs while flushing.
 130     */
 131    private $finishingDeferredWork = false;
 132
 133    /**
 134     * @var array<int, array{easy: EasyHandle, attached: bool}>
 135     */
 136    private $deferredCancels = [];
 137
 138    /**
 139     * @var array<int, object|null> Wait tokens of requests created from inside
 140     *                              a cURL callback, keyed by handle id; native
 141     *                              attachment is deferred until the outermost
 142     *                              native execution unwinds.
 143     */
 144    private $deferredAdds = [];
 145
 146    /**
 147     * @var string|null Owner signature of the proxy tunnels the multi handle's
 148     *                  connection cache may hold
 149     */
 150    private $proxyTunnelOwner;
 151
 152    /** @var array<string, int> Count of attached transfers per proxy tunnel signature. */
 153    private $activeProxyTunnelSignatures = [];
 154
 155    /** @var array<int, string> Maps an attached handle id to its proxy tunnel signature. */
 156    private $activeProxyTunnelHandles = [];
 157
 158    /**
 159     * @var int Depth of nested processMessages() calls. Guards against
 160     *          multi-handle recreation re-entrancy from processMessages (a
 161     *          retried transfer re-invokes the handler); a depth is tracked
 162     *          because a completion callback can re-enter tick().
 163     */
 164    private $messageProcessingDepth = 0;
 165
 166    /**
 167     * This handler accepts the following options:
 168     *
 169     * - handle_factory: An optional factory  used to create curl handles
 170     * - transport_sharing: Optional transport sharing mode.
 171     * - select_timeout: Optional timeout (in seconds) to block before timing
 172     *   out while selecting curl handles. Defaults to 1 second.
 173     * - max_host_connections: Optional maximum concurrent connections per host.
 174     * - max_total_connections: Optional maximum concurrent connections overall.
 175     * - multiplex: Optional Multiplexing::NONE to disallow multiplexing on
 176     *   this handler's multi handle. The eager, wait, and required modes are
 177     *   request options, not handler options; Multiplexing::NONE is also
 178     *   conditionally accepted as a request option value.
 179     * - options: An associative array of CURLMOPT_* options and
 180     *   corresponding values for curl_multi_setopt()
 181     */
 182    public function __construct(array $options = [])
 183    {
 184        foreach ($options as $name => $_) {
 185            if (!isset(self::KNOWN_CONSTRUCTOR_OPTIONS[$name])) {
 186                \trigger_deprecation('guzzlehttp/guzzle', '7.14', \sprintf('The "%s" CurlMultiHandler constructor option is unknown; guzzlehttp/guzzle 8.0 will reject unknown constructor options.', (string) $name));
 187            }
 188        }
 189
 190        $handlerMultiplex = $options['multiplex'] ?? null;
 191        if (null !== $handlerMultiplex && Multiplexing::NONE !== $handlerMultiplex) {
 192            if (\in_array($handlerMultiplex, [Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
 193                throw new \InvalidArgumentException('The "multiplex" CurlMultiHandler option only accepts Multiplexing::NONE; the eager, wait, and required modes are request options.');
 194            }
 195
 196            throw new \InvalidArgumentException(\sprintf('The "multiplex" CurlMultiHandler option must be null or Multiplexing::NONE; received %s.', \get_debug_type($handlerMultiplex)));
 197        }
 198        $this->multiplexDisabled = null !== $handlerMultiplex;
 199
 200        if ($this->multiplexDisabled && !\defined('CURLMOPT_PIPELINING')) {
 201            // ext-curl only defines the constant when built against libcurl
 202            // 7.16 or newer headers, and such builds compile out the matching
 203            // curl_multi_setopt() case, so the guarantee cannot be applied.
 204            throw new \InvalidArgumentException('The "multiplex" CurlMultiHandler option requires CURLMOPT_PIPELINING, but it is not available in the installed PHP cURL extension.');
 205        }
 206
 207        CurlShareHandleState::assertNoRequiredSharingCustomFactoryConflict($options, 'CurlMultiHandler');
 208        $transportSharing = $options['transport_sharing'] ?? null;
 209        $sharingMode = CurlShareHandleState::normalizeMode($transportSharing, 'transport_sharing');
 210
 211        if (\array_key_exists('handle_factory', $options) && $options['handle_factory'] !== null) {
 212            $this->shareHandleState = null;
 213            $this->factory = $options['handle_factory'];
 214            $this->customHandleFactory = true;
 215        } else {
 216            $this->shareHandleState = $sharingMode !== TransportSharing::NONE
 217                ? CurlShareHandleState::fromOption($transportSharing)
 218                : null;
 219
 220            $this->factory = $this->shareHandleState !== null
 221                ? new CurlFactory(50, $this->shareHandleState->mode, $this->shareHandleState)
 222                : new CurlFactory(50);
 223        }
 224
 225        if (isset($options['select_timeout'])) {
 226            $selectTimeout = $options['select_timeout'];
 227            if (!\is_int($selectTimeout) && !\is_float($selectTimeout) && (!\is_string($selectTimeout) || !\is_numeric($selectTimeout))) {
 228                \trigger_deprecation('guzzlehttp/guzzle', '7.14', 'Passing a non-numeric "select_timeout" CurlMultiHandler option is deprecated; guzzlehttp/guzzle 8.0 will reject it.');
 229            } else {
 230                $seconds = (float) $selectTimeout;
 231                if (!\is_finite($seconds) || $seconds < 0 || ($seconds > 0 && (int) ($seconds * 1000) === 0)) {
 232                    \trigger_deprecation('guzzlehttp/guzzle', '7.14', 'Passing a "select_timeout" CurlMultiHandler option that is not 0 or greater than or equal to 0.001 seconds is deprecated; guzzlehttp/guzzle 8.0 will reject it.');
 233                }
 234            }
 235
 236            $this->selectTimeout = $selectTimeout;
 237        } elseif ($selectTimeout = Utils::getenv('GUZZLE_CURL_SELECT_TIMEOUT')) {
 238            \trigger_deprecation('guzzlehttp/guzzle', '7.2', 'The GUZZLE_CURL_SELECT_TIMEOUT environment variable is deprecated; use the "select_timeout" option instead.');
 239            $this->selectTimeout = (int) $selectTimeout;
 240        } else {
 241            $this->selectTimeout = 1;
 242        }
 243
 244        $multiOptions = $options['options'] ?? [];
 245        if (\is_array($multiOptions)) {
 246            self::rejectConnectionCapOptionConflicts($options, $multiOptions);
 247
 248            if ($this->multiplexDisabled && \array_key_exists(\CURLMOPT_PIPELINING, $multiOptions)) {
 249                // Key presence alone conflicts, even with an agreeing value:
 250                // the named option is the single multiplexing authority.
 251                throw new \InvalidArgumentException('multiplex conflicts with a CURLMOPT_PIPELINING entry in the "options" array.');
 252            }
 253
 254            self::triggerConflictingCurlMultiOptionDeprecations($multiOptions);
 255        } elseif (self::hasConnectionCapOption($options)) {
 256            throw new \InvalidArgumentException('options must be an array of cURL multi options when using connection cap options.');
 257        } elseif ($this->multiplexDisabled) {
 258            throw new \InvalidArgumentException('options must be an array of cURL multi options when using the "multiplex" option.');
 259        }
 260
 261        $this->options = $multiOptions;
 262
 263        if (\is_array($multiOptions)) {
 264            $this->addConnectionCapOptions($options);
 265
 266            if ($this->multiplexDisabled) {
 267                // CURLPIPE_NOTHING; the constant itself needs libcurl 7.43
 268                // headers, newer than the oldest supported runtimes. The
 269                // option is required: a handler-wide guarantee must fail
 270                // closed rather than warn like the deprecated raw options.
 271                $this->options[\CURLMOPT_PIPELINING] = 0;
 272                $this->requiredOptions[\CURLMOPT_PIPELINING] = true;
 273            }
 274        }
 275
 276        // unsetting the property forces the first access to go through
 277        // __get().
 278        unset($this->_mh);
 279    }
 280
 281    /**
 282     * @param string $name
 283     *
 284     * @return resource|\CurlMultiHandle
 285     *
 286     * @throws \BadMethodCallException   when another field as `_mh` will be gotten
 287     * @throws \RuntimeException         when curl can not initialize a multi handle
 288     * @throws \InvalidArgumentException when a required cURL multi option cannot be applied
 289     */
 290    public function __get($name)
 291    {
 292        if ($name !== '_mh') {
 293            throw new \BadMethodCallException("Can not get other property as '_mh'.");
 294        }
 295
 296        $multiHandle = \curl_multi_init();
 297
 298        if (false === $multiHandle) {
 299            throw new \RuntimeException('Can not initialize curl multi handle.');
 300        }
 301
 302        try {
 303            foreach ($this->options as $option => $value) {
 304                if (true === @curl_multi_setopt($multiHandle, $option, $value)) {
 305                    continue;
 306                }
 307
 308                if (isset($this->requiredOptions[$option])) {
 309                    // A first-class option such as a connection cap must
 310                    // never be silently dropped.
 311                    throw new \InvalidArgumentException(\sprintf('Unable to apply the cURL multi option %s; it was rejected by the runtime libcurl.', self::formatCurlMultiOption($option)));
 312                }
 313
 314                \trigger_error(\sprintf('Unable to apply the cURL multi option %s; it was ignored by the runtime libcurl.', self::formatCurlMultiOption($option)), \E_USER_WARNING);
 315            }
 316        } catch (\Throwable $e) {
 317            // Do not publish a partially configured handle; a later access
 318            // retries the initialization from scratch.
 319            try {
 320                \curl_multi_close($multiHandle);
 321            } catch (\Throwable $ignored) {
 322                // Preserve the original failure.
 323            }
 324
 325            throw $e;
 326        }
 327
 328        $this->_mh = $multiHandle;
 329
 330        return $this->_mh;
 331    }
 332
 333    public function __destruct()
 334    {
 335        if (isset($this->_mh)) {
 336            try {
 337                \curl_multi_close($this->_mh);
 338            } catch (\Throwable $e) {
 339                // Destructors must not throw.
 340            } finally {
 341                unset($this->_mh);
 342            }
 343        }
 344    }
 345
 346    public function __invoke(RequestInterface $request, array $options): PromiseInterface
 347    {
 348        HostValidator::assertRequestHost($request);
 349
 350        if ($this->connectionCapsApplied
 351            && \defined('CURLOPT_SHARE')
 352            && isset($options['curl'])
 353            && \is_array($options['curl'])
 354            && \array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl'])
 355        ) {
 356            // Key presence alone conflicts: Guzzle cannot verify that a
 357            // caller-managed shared connection pool honors the caps.
 358            throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with CurlMultiHandler connection cap options because Guzzle cannot verify that an external shared connection pool honors cURL multi connection caps.');
 359        }
 360
 361        $easy = $this->factory->create($request, $options);
 362
 363        try {
 364            $this->rejectMultiplexPipeliningConflict($easy, $options);
 365            $this->applyMultiplexNone($easy, $options);
 366            $this->applyProxyTunnelOwnership($easy);
 367        } catch (\Throwable $e) {
 368            try {
 369                $this->factory->release($easy);
 370            } catch (\Throwable $releaseFailure) {
 371                // Preserve the original failure.
 372            }
 373
 374            throw $e;
 375        }
 376
 377        $id = (int) $easy->handle;
 378
 379        $waitToken = new \stdClass();
 380
 381        $promise = null;
 382        $promise = new Promise(
 383            function () use ($id, $waitToken, $easy, &$promise): void {
 384                // Waiting cannot drive native cURL while a callback has the
 385                // multi handle busy; fail the wait promptly instead of
 386                // self-deadlocking.
 387                $idReused = $this->multiExecDepth > 0
 388                    ? $this->failNestedWait($id, $waitToken)
 389                    : $this->executeUntil($id, $waitToken);
 390
 391                // Settling can be queued, and guzzlehttp/promises drains the
 392                // queue before deciding a wait function achieved nothing.
 393                P\Utils::queue()->run();
 394
 395                // Never null: assigned below before any wait can invoke this.
 396                /** @var Promise $promise */
 397                if (!P\State::isPending($promise)) {
 398                    return;
 399                }
 400
 401                // Neither path guarantees the transfer settled, and returning
 402                // while pending makes guzzlehttp/promises reject with a bare
 403                // string naming nothing.
 404                $stalled = $idReused
 405                    ? 'its native cURL handle ID was reused by another request'
 406                    : 'its entry was removed without settling';
 407
 408                $message = \sprintf('Waiting on cURL multi handler transfer %d cannot make progress (%s).', $id, $stalled);
 409
 410                // The entry is gone or belongs to another request, so
 411                // attribute from this easy handle.
 412                $promise->reject(new RequestException($message, $easy->request, $easy->response));
 413            },
 414            function () use ($id, $waitToken) {
 415                return $this->cancel($id, $waitToken);
 416            }
 417        );
 418
 419        $entry = ['easy' => $easy, 'deferred' => $promise, 'wait_token' => $waitToken];
 420
 421        try {
 422            $this->addRequest($entry);
 423        } catch (\Throwable $e) {
 424            throw $this->discardPendingRequest($id, $entry, $e);
 425        }
 426
 427        return $promise;
 428    }
 429
 430    /**
 431     * The "multiplex" request option sets CURLOPT_PIPEWAIT, which libcurl
 432     * ignores entirely when the multi handle's CURLMOPT_PIPELINING option
 433     * disables multiplexing, so an explicit request for multiplexing on a
 434     * handler configured against it is a configuration error. The required
 435     * family conflicts marker-independently: a required guarantee on a handler
 436     * that disables multiplexing is contradictory even when the transfer would
 437     * not wait. A raw CURLOPT_PIPEWAIT cURL option conflicts with every
 438     * explicit mode on this handler, where waiting is operationally
 439     * meaningful: whatever its value, it is a second wait/eager authority
 440     * applied after the mode's own decision.
 441     */
 442    private function rejectMultiplexPipeliningConflict(EasyHandle $easy, array $options): void
 443    {
 444        $multiplex = $options['multiplex'] ?? null;
 445
 446        if (null === $multiplex) {
 447            return;
 448        }
 449
 450        if (\defined('CURLOPT_PIPEWAIT')
 451            && isset($options['curl'])
 452            && \is_array($options['curl'])
 453            && \array_key_exists((int) \constant('CURLOPT_PIPEWAIT'), $options['curl'])
 454        ) {
 455            // Key presence alone conflicts, and it must be rejected before
 456            // the marker below is consulted: the marker reflects the final
 457            // merged configuration, which the raw value has falsified.
 458            throw new \InvalidArgumentException('The "multiplex" request option cannot be combined with the raw CURLOPT_PIPEWAIT cURL option on the cURL multi handler; remove the raw option.');
 459        }
 460
 461        if (Multiplexing::WAIT === $multiplex && !$easy->usesPipewait) {
 462            // Explicit wait only conflicts when the transfer would actually
 463            // wait; an HTTP/1.1 wait request never sets the marker.
 464            return;
 465        }
 466
 467        if (!\in_array($multiplex, [Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
 468            return;
 469        }
 470
 471        if ($this->multiplexDisabled) {
 472            // Checked before the raw option: the handler wrote its own
 473            // CURLMOPT_PIPELINING value when "multiplex" disabled it.
 474            throw new \InvalidArgumentException('The "multiplex" request option cannot be combined with a CurlMultiHandler whose "multiplex" option is Multiplexing::NONE; remove the handler option or set the request option to "eager".');
 475        }
 476
 477        if (!\is_array($this->options) || !\array_key_exists(\CURLMOPT_PIPELINING, $this->options)) {
 478            // A legacy non-array "options" value is tolerated by the
 479            // constructor and cannot contain the option.
 480            return;
 481        }
 482
 483        $pipelining = $this->options[\CURLMOPT_PIPELINING];
 484        if (!\is_scalar($pipelining)) {
 485            // ext-curl derives the integer mask from non-scalar values with
 486            // type-dependent zval semantics, so the effective mask cannot be
 487            // predicted here; require an explicit integer instead.
 488            throw new \InvalidArgumentException('The CurlMultiHandler CURLMOPT_PIPELINING option must be an integer when combined with the "multiplex" request option.');
 489        }
 490
 491        $multiplexBit = \defined('CURLPIPE_MULTIPLEX') ? \CURLPIPE_MULTIPLEX : 2;
 492        if (((int) $pipelining & $multiplexBit) !== 0) {
 493            return;
 494        }
 495
 496        throw new \InvalidArgumentException('The "multiplex" request option cannot be combined with a CurlMultiHandler CURLMOPT_PIPELINING option that disables multiplexing; set CURLMOPT_PIPELINING to CURLPIPE_MULTIPLEX, remove the option, or set the "multiplex" option to "eager".');
 497    }
 498
 499    /**
 500     * A Multiplexing::NONE request option is a sole-use guarantee: the
 501     * transfer must not share its connection with any concurrent transfer.
 502     * It holds structurally on a handler whose "multiplex" option is
 503     * Multiplexing::NONE, and for HTTP/1.x transfers, which never join a
 504     * multiplexed connection and open connections nothing can join. An
 505     * HTTP/2 request on a handler that multiplexes is rejected, as is any
 506     * configuration under which the guarantee cannot be verified (custom
 507     * handle factories control the native handle) or cannot be hardened
 508     * (challenge-response authentication retries and Expect 417 retries
 509     * re-enter connection selection as internal follows, which disarm
 510     * CURLOPT_FRESH_CONNECT). A raw CURLMOPT_PIPELINING multi option, and
 511     * deprecated-but-applied raw cURL options that can defeat the declared
 512     * protocol version, retry through internal follows, or replace the
 513     * managed header list, are rejected by key presence. On runtimes whose
 514     * matcher can hand an HTTP/1.x transfer an idle multiplexed connection
 515     * (below libcurl 7.77.0, and 8.11.0-8.12.1), accepted transfers force
 516     * a fresh connection.
 517     */
 518    private function applyMultiplexNone(EasyHandle $easy, array $options): void
 519    {
 520        if (Multiplexing::NONE !== ($options['multiplex'] ?? null) || $this->multiplexDisabled) {
 521            return;
 522        }
 523
 524        if (\defined('CURLMOPT_PIPELINING') && \is_array($this->options) && \array_key_exists(\CURLMOPT_PIPELINING, $this->options)) {
 525            // Key presence alone conflicts, matching the constructor's rule
 526            // for the named option: raw multi options that fail to apply only
 527            // warn (they are not in requiredOptions), so even an agreeing
 528            // zero mask cannot prove the guarantee. is_array: legacy non-array
 529            // "options" values are deprecated but still stored.
 530            throw new \InvalidArgumentException('The "multiplex" request option cannot be Multiplexing::NONE alongside a raw CURLMOPT_PIPELINING cURL multi option; replace the raw option with the "multiplex" cURL multi handler option.');
 531        }
 532
 533        if ($this->customHandleFactory) {
 534            throw new \InvalidArgumentException('The "multiplex" request option can only be Multiplexing::NONE on a CurlMultiHandler with a custom "handle_factory" when the handler\'s own "multiplex" option is Multiplexing::NONE, because the guarantee is enforced against the native easy handle the factory controls.');
 535        }
 536
 537        $version = $easy->request->getProtocolVersion();
 538        if ('2' === $version || '2.0' === $version) {
 539            throw new \InvalidArgumentException('The "multiplex" request option can only be Multiplexing::NONE for an HTTP/1.x request on a CurlMultiHandler that permits multiplexing; set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE to disable multiplexing for every transfer, or send the request with its "version" option set to "1.1".');
 540        }
 541
 542        if (isset($options['curl']) && \is_array($options['curl'])) {
 543            foreach (['CURLOPT_HTTP_VERSION', 'CURLOPT_HTTPAUTH', 'CURLOPT_PROXYAUTH', 'CURLOPT_FOLLOWLOCATION', 'CURLOPT_HTTPHEADER', 'CURLOPT_ALTSVC', 'CURLOPT_ALTSVC_CTRL', 'CURLOPT_PROXYTYPE'] as $constant) {
 544                if (\defined($constant) && \array_key_exists((int) \constant($constant), $options['curl'])) {
 545                    // Key presence alone conflicts. A raw CURLOPT_HTTP_VERSION
 546                    // overrides the declared version after the factory
 547                    // mapping, and raw alt-svc options or an HTTPS2 proxy
 548                    // type can put a declared-HTTP/1.x transfer on a joinable
 549                    // HTTP/2 connection; raw challenge-response
 550                    // authentication (origin 401 or proxy 407) and native
 551                    // redirects re-enter connection selection as internal
 552                    // follows, which disarm CURLOPT_FRESH_CONNECT, so the
 553                    // hardening below cannot cover them; a raw
 554                    // CURLOPT_HTTPHEADER replaces the managed header list,
 555                    // including the Expect suppression the check below
 556                    // relies on.
 557                    throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be Multiplexing::NONE combined with the raw %s cURL option on a CurlMultiHandler that permits multiplexing; remove the raw option, or set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE.', $constant));
 558                }
 559            }
 560        }
 561
 562        if (Psr7\Utils::caselessContains($easy->request->getHeaderLine('Expect'), '100-continue')) {
 563            // libcurl arms its Expect handling by a caseless substring scan
 564            // of the header value (Curl_compareheader), so any value
 565            // containing 100-continue can make a 417 response retry as an
 566            // internal follow, which disarms CURLOPT_FRESH_CONNECT; requests
 567            // without the header are safe because the factory suppresses
 568            // libcurl's automatic Expect.
 569            throw new \InvalidArgumentException('The "multiplex" request option cannot be Multiplexing::NONE for a request carrying an "Expect: 100-continue" header on a CurlMultiHandler that permits multiplexing; remove the explicitly supplied "Expect" header, set the "expect" request option to false to prevent it being added automatically, or set the "multiplex" client or CurlMultiHandler constructor option to Multiplexing::NONE.');
 570        }
 571
 572        if (CurlVersion::supportsHttpVersionReuseMatching()) {
 573            return;
 574        }
 575
 576        // Unqualified curl_setopt so the test bootstrap shadow records it.
 577        if (true !== curl_setopt($easy->handle, \CURLOPT_FRESH_CONNECT, true)) {
 578            // The hardening is the guarantee on these runtimes; failing to
 579            // apply it must fail closed, mirroring applyCurlOptions().
 580            throw new \InvalidArgumentException('Unable to set cURL option CURLOPT_FRESH_CONNECT.');
 581        }
 582    }
 583
 584    /**
 585     * @param array<mixed> $options
 586     */
 587    private static function triggerConflictingCurlMultiOptionDeprecations(array $options): void
 588    {
 589        if ($options === []) {
 590            return;
 591        }
 592
 593        $conflictingOptions = self::conflictingCurlMultiOptions();
 594        $sinceOverrides = self::conflictingCurlMultiOptionSinceOverrides();
 595        foreach ($options as $option => $_) {
 596            if (\array_key_exists($option, $conflictingOptions)) {
 597                \trigger_deprecation('guzzlehttp/guzzle', $sinceOverrides[$option] ?? '7.14', \sprintf('Passing %s in the cURL multi handler "options" is deprecated; guzzlehttp/guzzle 8.0 will reject this option. Use %s instead.', self::formatCurlMultiOption($option), $conflictingOptions[$option]));
 598            }
 599        }
 600    }
 601
 602    /**
 603     * @return array<int, string>
 604     */
 605    private static function conflictingCurlMultiOptionSinceOverrides(): array
 606    {
 607        if (!\defined('CURLMOPT_PIPELINING')) {
 608            // Matches conflictingCurlMultiOptions(): ext-curl builds against
 609            // pre-7.16 libcurl headers do not define the constant.
 610            return [];
 611        }
 612
 613        return [\CURLMOPT_PIPELINING => '7.15'];
 614    }
 615
 616    /**
 617     * @param array<mixed> $options
 618     */
 619    private static function hasConnectionCapOption(array $options): bool
 620    {
 621        foreach (self::CONNECTION_CAP_OPTIONS as $name => $_) {
 622            if (($options[$name] ?? null) !== null) {
 623                return true;
 624            }
 625        }
 626
 627        return false;
 628    }
 629
 630    /**
 631     * @param array<mixed> $constructorOptions
 632     * @param array<mixed> $multiOptions
 633     */
 634    private static function rejectConnectionCapOptionConflicts(array $constructorOptions, array $multiOptions): void
 635    {
 636        foreach (self::CONNECTION_CAP_OPTIONS as $name => $constant) {
 637            if (($constructorOptions[$name] ?? null) === null || !\defined($constant)) {
 638                continue;
 639            }
 640
 641            $option = \constant($constant);
 642            if (\array_key_exists($option, $multiOptions)) {
 643                throw new \InvalidArgumentException(\sprintf('%s conflicts with a %s entry in the "options" array.', $name, $constant));
 644            }
 645        }
 646    }
 647
 648    /**
 649     * @param array<mixed> $options
 650     */
 651    private function addConnectionCapOptions(array $options): void
 652    {
 653        foreach (self::CONNECTION_CAP_OPTIONS as $name => $constant) {
 654            $value = $options[$name] ?? null;
 655            if ($value === null) {
 656                continue;
 657            }
 658
 659            if (!\is_int($value) || $value < 1) {
 660                throw new \InvalidArgumentException(\sprintf('%s must be a positive integer.', $name));
 661            }
 662
 663            CurlVersion::ensureConnectionCapsSupported($name);
 664
 665            $option = \constant($constant);
 666            if (\array_key_exists($option, $this->options)) {
 667                throw new \InvalidArgumentException(\sprintf('%s conflicts with a %s entry in the "options" array.', $name, $constant));
 668            }
 669
 670            $this->options[$option] = $value;
 671            $this->requiredOptions[$option] = true;
 672            $this->connectionCapsApplied = true;
 673        }
 674    }
 675
 676    /**
 677     * @param int|string $option
 678     */
 679    private static function formatCurlMultiOption($option): string
 680    {
 681        if (!\is_int($option)) {
 682            return \sprintf('"%s"', $option);
 683        }
 684
 685        static $names = null;
 686
 687        if (null === $names) {
 688            $names = [];
 689            foreach (\get_defined_constants(true)['curl'] ?? [] as $name => $value) {
 690                if (\is_int($value) && \strpos($name, 'CURLMOPT_') === 0 && !isset($names[$value])) {
 691                    $names[$value] = $name;
 692                }
 693            }
 694        }
 695
 696        if (isset($names[$option])) {
 697            return \sprintf('%s (%d)', $names[$option], $option);
 698        }
 699
 700        return (string) $option;
 701    }
 702
 703    /**
 704     * @return array<int, string>
 705     */
 706    private static function conflictingCurlMultiOptions(): array
 707    {
 708        static $options = null;
 709
 710        if ($options !== null) {
 711            return $options;
 712        }
 713
 714        $options = [];
 715
 716        self::addConflictingCurlMultiOption($options, 'CURLMOPT_MAX_HOST_CONNECTIONS', 'the "max_host_connections" client option or cURL multi handler option');
 717        self::addConflictingCurlMultiOption($options, 'CURLMOPT_MAX_TOTAL_CONNECTIONS', 'the "max_total_connections" client option or cURL multi handler option');
 718        self::addConflictingCurlMultiOption($options, 'CURLMOPT_PIPELINING', 'Multiplexing::NONE via the "multiplex" cURL multi handler or client option to disable multiplexing, or remove the raw option for the runtime default (multiplexing defaults on from libcurl 7.62, except 7.65.0 and 7.65.1)');
 719
 720        return $options;
 721    }
 722
 723    /**
 724     * @param array<int, string> $options
 725     */
 726    private static function addConflictingCurlMultiOption(array &$options, string $constant, string $replacement): void
 727    {
 728        if (!\defined($constant)) {
 729            return;
 730        }
 731
 732        $value = \constant($constant);
 733        if (\is_int($value)) {
 734            $options[$value] = $replacement;
 735        }
 736    }
 737
 738    /**
 739     * Isolates the connection cache when the request's proxy tunnel section
 740     * differs from the one the multi handle's cache may already hold.
 741     */
 742    private function applyProxyTunnelOwnership(EasyHandle $easy): void
 743    {
 744        $signature = $easy->proxyTunnelSignature;
 745        if ($signature === null || $signature === $this->proxyTunnelOwner) {
 746            return;
 747        }
 748
 749        if ($this->proxyTunnelOwner === null) {
 750            // No in-domain transfer has ever run on this multi handle: latch
 751            // the owner without destroying pooled direct connections.
 752            $this->proxyTunnelOwner = $signature;
 753
 754            return;
 755        }
 756
 757        if (
 758            $this->handles === []
 759            && 0 === $this->multiExecDepth
 760            && 0 === $this->messageProcessingDepth
 761            && $this->deferredCancels === []
 762        ) {
 763            // Idle: hand the connection cache over by recreating the multi
 764            // handle (unsetting re-arms the lazy __get initializer, which
 765            // re-applies the CURLMOPT_* options).
 766            if (isset($this->_mh)) {
 767                \curl_multi_close($this->_mh);
 768                unset($this->_mh);
 769            }
 770            $this->proxyTunnelOwner = $signature;
 771
 772            return;
 773        }
 774
 775        // Busy: isolate this transfer from the owner's pooled tunnels.
 776        $this->isolateProxyTunnelTransfer($easy);
 777    }
 778
 779    private function addCurlHandle(EasyHandle $easy): void
 780    {
 781        $this->isolateFromForeignActiveProxyTunnel($easy);
 782
 783        // Unqualified curl_multi_add_handle so the test bootstrap shadow can
 784        // override the result.
 785        $result = curl_multi_add_handle($this->_mh, $easy->handle);
 786
 787        if (\CURLM_OK !== $result) {
 788            if (\PHP_VERSION_ID < 80226 || (\PHP_VERSION_ID >= 80300 && \PHP_VERSION_ID < 80314)) {
 789                // Before PHP 8.2.26 and 8.3.14, ext-curl kept the easy handle
 790                // in its multi bookkeeping even when the native add failed
 791                // (https://github.com/php/php-src/pull/16302); remove it so
 792                // the handle can be pooled or closed safely.
 793                \curl_multi_remove_handle($this->_mh, $easy->handle);
 794            }
 795
 796            throw new RequestException(\sprintf('Unable to add the cURL handle to the cURL multi handler: %s (%d).', (string) \curl_multi_strerror($result), $result), $easy->request);
 797        }
 798
 799        $this->markProxyTunnelActive($easy);
 800
 801        $id = (int) $easy->handle;
 802        if (isset($this->handles[$id])) {
 803            $this->handles[$id]['attached'] = true;
 804        }
 805    }
 806
 807    /**
 808     * @param resource|\CurlHandle $handle
 809     */
 810    private function removeCompletedHandleFromMulti(int $id, $handle): void
 811    {
 812        $this->removeHandleFromMulti($handle);
 813        $this->unmarkProxyTunnelActiveById($id);
 814    }
 815
 816    /**
 817     * Removes a transfer from the multi handle under the native execution
 818     * guard: removing a still-running transfer performs a final progress
 819     * update that can run a user progress callback.
 820     *
 821     * @param resource|\CurlHandle $handle
 822     */
 823    private function removeHandleFromMulti($handle): void
 824    {
 825        ++$this->multiExecDepth;
 826
 827        try {
 828            \curl_multi_remove_handle($this->_mh, $handle);
 829        } finally {
 830            --$this->multiExecDepth;
 831            $this->finishDeferredWork();
 832        }
 833    }
 834
 835    private function isolateFromForeignActiveProxyTunnel(EasyHandle $easy): void
 836    {
 837        $signature = $easy->proxyTunnelSignature;
 838
 839        if ($signature === null || $this->activeProxyTunnelSignatures === []) {
 840            return;
 841        }
 842
 843        if (\count($this->activeProxyTunnelSignatures) === 1 && isset($this->activeProxyTunnelSignatures[$signature])) {
 844            return;
 845        }
 846
 847        $this->isolateProxyTunnelTransfer($easy);
 848    }
 849
 850    private function isolateProxyTunnelTransfer(EasyHandle $easy): void
 851    {
 852        foreach (self::PROXY_TUNNEL_ISOLATION_OPTIONS as $name) {
 853            try {
 854                // Unqualified curl_setopt so the test bootstrap shadow records it.
 855                $applied = curl_setopt($easy->handle, (int) \constant($name), true);
 856            } catch (\Throwable $e) {
 857                throw new RequestException(self::proxyTunnelIsolationFailureMessage($name), $easy->request, null, $e);
 858            }
 859
 860            if (true !== $applied) {
 861                throw new RequestException(self::proxyTunnelIsolationFailureMessage($name), $easy->request);
 862            }
 863        }
 864    }
 865
 866    private static function proxyTunnelIsolationFailureMessage(string $name): string
 867    {
 868        return \sprintf('Unable to apply the %s cURL option required to isolate the transfer from foreign proxy tunnel connections.', $name);
 869    }
 870
 871    private function markProxyTunnelActive(EasyHandle $easy): void
 872    {
 873        $signature = $easy->proxyTunnelSignature;
 874        if ($signature === null) {
 875            return;
 876        }
 877
 878        $id = (int) $easy->handle;
 879        if (isset($this->activeProxyTunnelHandles[$id])) {
 880            if ($this->activeProxyTunnelHandles[$id] === $signature) {
 881                return;
 882            }
 883
 884            $this->unmarkProxyTunnelActiveById($id);
 885        }
 886
 887        $this->activeProxyTunnelHandles[$id] = $signature;
 888        $this->activeProxyTunnelSignatures[$signature] = ($this->activeProxyTunnelSignatures[$signature] ?? 0) + 1;
 889    }
 890
 891    private function unmarkProxyTunnelActive(EasyHandle $easy): void
 892    {
 893        $this->unmarkProxyTunnelActiveById((int) $easy->handle);
 894    }
 895
 896    private function unmarkProxyTunnelActiveById(int $id): void
 897    {
 898        if (!isset($this->activeProxyTunnelHandles[$id])) {
 899            return;
 900        }
 901
 902        $signature = $this->activeProxyTunnelHandles[$id];
 903        unset($this->activeProxyTunnelHandles[$id]);
 904
 905        if (!isset($this->activeProxyTunnelSignatures[$signature])) {
 906            return;
 907        }
 908
 909        --$this->activeProxyTunnelSignatures[$signature];
 910
 911        if ($this->activeProxyTunnelSignatures[$signature] <= 0) {
 912            unset($this->activeProxyTunnelSignatures[$signature]);
 913        }
 914    }
 915
 916    /**
 917     * Ticks the curl event loop.
 918     */
 919    public function tick(): void
 920    {
 921        $this->tickFor(null, null);
 922    }
 923
 924    /**
 925     * Ticks the curl event loop, returning before the blocking select if the
 926     * targeted transfer has settled, been canceled, or been replaced by a
 927     * request that reused its native handle ID.
 928     */
 929    private function tickFor(?int $targetId, ?object $waitToken): void
 930    {
 931        // Add any delayed handles if needed. Attachment is skipped while a
 932        // callback has native execution busy; the outer frame attaches due
 933        // transfers once it unwinds.
 934        if ($this->delays && 0 === $this->multiExecDepth) {
 935            $currentTime = Utils::currentTime();
 936            foreach ($this->delays as $id => $delay) {
 937                if ($currentTime >= $delay) {
 938                    $entry = $this->handles[$id];
 939                    unset($this->delays[$id]);
 940
 941                    try {
 942                        $this->addCurlHandle($entry['easy']);
 943                    } catch (\Throwable $e) {
 944                        // The promise has already escaped, so reject it
 945                        // rather than throw.
 946                        $rejection = $this->discardPendingRequest($id, $entry, $e);
 947                        if (P\State::isPending($entry['deferred'])) {
 948                            $entry['deferred']->reject($rejection);
 949                        }
 950                    }
 951                }
 952            }
 953        }
 954
 955        // Run curl_multi_exec in the queue to enable other async tasks to
 956        // run, surface completions, and drain any work they queued so a
 957        // ready cancellation or new transfer is not held behind the select.
 958        do {
 959            P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
 960
 961            // Step through the task queue which may add additional requests.
 962            P\Utils::queue()->run();
 963
 964            if ($this->multiExecDepth > 0) {
 965                // A cURL callback re-entered the handler while native
 966                // execution is running; the outer frame drives native cURL
 967                // once it unwinds.
 968                return;
 969            }
 970
 971            if (isset($this->_mh)) {
 972                $this->processMessages();
 973            }
 974        } while (!P\Utils::queue()->isEmpty());
 975
 976        if (!isset($this->_mh)) {
 977            // Nothing is attached natively (or initialization just failed);
 978            // there is nothing to run and nothing to recreate the handle for.
 979            return;
 980        }
 981
 982        if ($targetId !== null && !$this->hasRequest($targetId, $waitToken)) {
 983            return;
 984        }
 985
 986        if ($this->active && \curl_multi_select($this->_mh, $this->effectiveSelectTimeout()) === -1) {
 987            // Perform a usleep if a select returns -1.
 988            // See: https://bugs.php.net/bug.php?id=61141
 989            \usleep(250);
 990        }
 991
 992        do {
 993            $exec = $this->executeMulti();
 994
 995            // Prevent busy looping for slow HTTP requests.
 996            if ($exec === \CURLM_CALL_MULTI_PERFORM) {
 997                \curl_multi_select($this->_mh, $this->effectiveSelectTimeout());
 998            }
 999        } while ($exec === \CURLM_CALL_MULTI_PERFORM);
1000
1001        $this->processMessages();
1002    }
1003
1004    /**
1005     * Runs \curl_multi_exec() inside the event loop, to prevent busy looping
1006     */
1007    private function tickInQueue(): void
1008    {
1009        if ($this->multiExecDepth > 0) {
1010            // A cURL callback re-entered the handler while native execution
1011            // is running; the outer frame drives native cURL once it unwinds.
1012            return;
1013        }
1014
1015        if (!isset($this->_mh)) {
1016            // Nothing is attached natively (or initialization just failed);
1017            // there is nothing to run and nothing to recreate the handle for.
1018            return;
1019        }
1020
1021        $exec = $this->executeMulti();
1022
1023        if ($exec === \CURLM_CALL_MULTI_PERFORM) {
1024            \curl_multi_select($this->_mh, 0);
1025            P\Utils::queue()->add(Closure::fromCallable([$this, 'tickInQueue']));
1026        }
1027    }
1028
1029    /**
1030     * @phpstan-impure
1031     */
1032    private function executeMulti(): int
1033    {
1034        ++$this->multiExecDepth;
1035
1036        try {
1037            return \curl_multi_exec($this->_mh, $this->active);
1038        } finally {
1039            --$this->multiExecDepth;
1040            $this->finishDeferredWork();
1041        }
1042    }
1043
1044    /**
1045     * Flushes cancels and attachments deferred while the multi handle was
1046     * busy executing transfers or removing a handle.
1047     */
1048    private function finishDeferredWork(): void
1049    {
1050        if ($this->multiExecDepth > 0 || $this->finishingDeferredWork) {
1051            // A nested frame (a cURL callback re-entered the handler) must
1052            // not flush while an outer frame is still using the multi
1053            // handle; the outermost frame flushes once it unwinds.
1054            return;
1055        }
1056
1057        $this->finishingDeferredWork = true;
1058
1059        try {
1060            $failure = null;
1061
1062            // Removing a cancelled transfer runs its final progress update,
1063            // whose callback can cancel other transfers or create requests;
1064            // drain until no deferred work remains.
1065            do {
1066                $this->cleanupDeferredCancels($failure);
1067                $this->flushDeferredAdds();
1068            } while ($this->deferredCancels !== [] || $this->deferredAdds !== []);
1069
1070            if ($failure !== null) {
1071                throw $failure;
1072            }
1073        } finally {
1074            $this->finishingDeferredWork = false;
1075        }
1076    }
1077
1078    /**
1079     * Runs until all outstanding connections have completed.
1080     */
1081    public function execute(): void
1082    {
1083        if ($this->multiExecDepth > 0) {
1084            // Native cURL cannot be driven while a callback has it busy, so
1085            // the loop would spin without ever progressing.
1086            throw new \LogicException('Cannot run the cURL multi event loop from inside a cURL callback; the callback must return before transfers can progress.');
1087        }
1088
1089        $queue = P\Utils::queue();
1090
1091        while ($this->handles || !$queue->isEmpty()) {
1092            // If there are no transfers, then sleep for the next delay,
1093            // unless ready queue work could change what is pending.
1094            if (!$this->active && $this->delays && $queue->isEmpty()) {
1095                \usleep($this->timeToNext());
1096            }
1097            $this->tick();
1098        }
1099    }
1100
1101    /**
1102     * Runs the event loop until the given transfer has finished, so waiting
1103     * on a promise does not wait for every other transfer on the handler
1104     * like execute() does.
1105     *
1106     * The native cURL handle ID can be reused by a request created from a
1107     * completion callback, so the wait token guards against waiting on an
1108     * unrelated transfer that inherited the ID.
1109     *
1110     * @return bool Whether another request had reused the native cURL handle
1111     *              ID by the time the loop stopped
1112     */
1113    private function executeUntil(int $id, object $waitToken): bool
1114    {
1115        $queue = P\Utils::queue();
1116
1117        while ($this->hasRequest($id, $waitToken)) {
1118            // If the transfer is delayed, then sleep until it is due, unless
1119            // ready queue work could cancel or replace it first.
1120            if (!$this->active && isset($this->delays[$id]) && $queue->isEmpty()) {
1121                \usleep($this->timeToNext());
1122            }
1123            $this->tickFor($id, $waitToken);
1124        }
1125
1126        // Sample before the drain below, which can add or remove an entry
1127        // under this ID and so rewrite the answer.
1128        $idReused = isset($this->handles[$id]);
1129
1130        if (!$queue->isEmpty()) {
1131            $queue->run();
1132        }
1133
1134        return $idReused;
1135    }
1136
1137    /**
1138     * Checks that the request with the given handle ID is still pending and,
1139     * when a wait token is given, has not been replaced by a request that
1140     * reused the ID.
1141     */
1142    private function hasRequest(int $id, ?object $waitToken = null): bool
1143    {
1144        if (!isset($this->handles[$id])) {
1145            return false;
1146        }
1147
1148        return $waitToken === null || ($this->handles[$id]['wait_token'] ?? null) === $waitToken;
1149    }
1150
1151    private function addRequest(array $entry): void
1152    {
1153        $easy = $entry['easy'];
1154        $id = (int) $easy->handle;
1155        $entry['attached'] = false;
1156
1157        $displaced = $this->handles[$id] ?? null;
1158        if ($displaced !== null) {
1159            // Never silently discard a tracked entry; settle it first.
1160            unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]);
1161            if (P\State::isPending($displaced['deferred'])) {
1162                $message = \sprintf('cURL multi handler transfer %d was displaced by another request that reused its native cURL handle ID.', $id);
1163                $displaced['deferred']->reject(new RequestException($message, $displaced['easy']->request, $displaced['easy']->response));
1164            }
1165        }
1166
1167        $this->handles[$id] = $entry;
1168
1169        if (!empty($easy->options['delay'])) {
1170            $this->delays[$id] = Utils::currentTime() + ($easy->options['delay'] / 1000);
1171        } elseif ($this->multiExecDepth > 0) {
1172            // A request created from inside a cURL callback cannot be added
1173            // natively while curl_multi_exec() is running; libcurl 7.59+
1174            // rejects the recursive call. Attach it once the outermost
1175            // native execution unwinds.
1176            $this->deferredAdds[$id] = $entry['wait_token'] ?? null;
1177        } else {
1178            $this->addCurlHandle($easy);
1179        }
1180    }
1181
1182    /**
1183     * Rolls back a request that can no longer be attached, releasing the
1184     * easy handle exactly once and preserving the original failure.
1185     *
1186     * @param array{easy: EasyHandle, deferred: Promise, wait_token?: object|null, attached?: bool} $entry
1187     */
1188    private function discardPendingRequest(int $id, array $entry, \Throwable $failure): \Throwable
1189    {
1190        unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]);
1191
1192        try {
1193            $this->factory->release($entry['easy']);
1194        } catch (\Throwable $e) {
1195            // Preserve the original failure.
1196        }
1197
1198        return $failure;
1199    }
1200
1201    /**
1202     * Fails a synchronous wait attempted from inside a cURL callback, where
1203     * native execution cannot progress until the callback returns.
1204     *
1205     * @return bool Whether another request had reused the native cURL handle
1206     *              ID, which only matters when no transfer was left to fail
1207     */
1208    private function failNestedWait(int $id, object $token): bool
1209    {
1210        if (!$this->hasRequest($id, $token)) {
1211            // Nothing left to fail, so report which way the entry went.
1212            return isset($this->handles[$id]);
1213        }
1214
1215        $entry = $this->handles[$id];
1216        $failure = new RequestException('Cannot synchronously wait for a transfer from inside a cURL callback on the same cURL multi handler; the callback must return before the transfer can progress.', $entry['easy']->request, $entry['easy']->response);
1217
1218        if (!empty($entry['attached'])) {
1219            // Native removal must wait until the outermost execution unwinds.
1220            unset($this->handles[$id], $this->delays[$id], $this->deferredAdds[$id]);
1221            $this->deferredCancels[$id] = ['easy' => $entry['easy'], 'attached' => true];
1222        } else {
1223            $this->discardPendingRequest($id, $entry, $failure);
1224        }
1225
1226        $entry['deferred']->reject($failure);
1227
1228        return false;
1229    }
1230
1231    /**
1232     * Attaches requests whose native attachment was deferred because they
1233     * were created from inside a cURL callback.
1234     */
1235    private function flushDeferredAdds(): void
1236    {
1237        if ($this->deferredAdds === []) {
1238            return;
1239        }
1240
1241        $adds = $this->deferredAdds;
1242        $this->deferredAdds = [];
1243
1244        foreach ($adds as $id => $token) {
1245            if (!$this->hasRequest($id, $token)) {
1246                // Cancelled or replaced while the attachment was deferred.
1247                continue;
1248            }
1249
1250            $entry = $this->handles[$id];
1251
1252            try {
1253                $this->addCurlHandle($entry['easy']);
1254            } catch (\Throwable $e) {
1255                // The promise has already escaped, so reject it rather than
1256                // throw. User code may have settled it directly; a settled
1257                // promise must not abort the rest of the snapshot.
1258                $rejection = $this->discardPendingRequest($id, $entry, $e);
1259                if (P\State::isPending($entry['deferred'])) {
1260                    $entry['deferred']->reject($rejection);
1261                }
1262            }
1263        }
1264    }
1265
1266    /**
1267     * Cancels a handle from sending and removes references to it.
1268     *
1269     * @param int         $id        Handle ID to cancel and remove.
1270     * @param object|null $waitToken Identity token that must still match the
1271     *                               entry when given.
1272     *
1273     * @return bool True on success, false on failure.
1274     */
1275    private function cancel($id, ?object $waitToken = null): bool
1276    {
1277        if (!is_int($id)) {
1278            \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__);
1279        }
1280
1281        // Cannot cancel if it has been processed or replaced by a request
1282        // that reused the native handle ID.
1283        if (!isset($this->handles[$id]) || ($waitToken !== null && ($this->handles[$id]['wait_token'] ?? null) !== $waitToken)) {
1284            return false;
1285        }
1286
1287        $entry = $this->handles[$id];
1288        $easy = $entry['easy'];
1289        $attached = !empty($entry['attached']);
1290        unset($this->delays[$id], $this->deferredAdds[$id], $this->handles[$id]);
1291
1292        if ($this->multiExecDepth > 0) {
1293            $this->deferredCancels[$id] = ['easy' => $easy, 'attached' => $attached];
1294
1295            return true;
1296        }
1297
1298        $this->cleanupCancelledHandle($easy, $attached);
1299
1300        return true;
1301    }
1302
1303    private function cleanupDeferredCancels(?\Throwable &$failure): void
1304    {
1305        if ($this->deferredCancels === []) {
1306            return;
1307        }
1308
1309        $entries = $this->deferredCancels;
1310        $this->deferredCancels = [];
1311
1312        foreach ($entries as $entry) {
1313            try {
1314                $this->cleanupCancelledHandle($entry['easy'], $entry['attached']);
1315            } catch (\Throwable $e) {
1316                // A final progress update can run a throwing user callback;
1317                // clean the remaining entries and surface the first failure
1318                // once the drain completes.
1319                if ($failure === null) {
1320                    $failure = $e;
1321                }
1322            }
1323        }
1324    }
1325
1326    private function cleanupCancelledHandle(EasyHandle $easy, bool $attached): void
1327    {
1328        $handle = $easy->handle;
1329        $failure = null;
1330
1331        if ($attached) {
1332            try {
1333                $this->removeHandleFromMulti($handle);
1334            } catch (\Throwable $e) {
1335                // The native detach completes even when its final progress
1336                // callback throws; finish this entry before rethrowing.
1337                $failure = $e;
1338            }
1339        }
1340
1341        $this->unmarkProxyTunnelActive($easy);
1342
1343        if (PHP_VERSION_ID < 80000) {
1344            try {
1345                \curl_close($handle);
1346            } catch (\Throwable $e) {
1347                // An error handler can promote the close warning; keep the
1348                // first failure.
1349                if ($failure === null) {
1350                    $failure = $e;
1351                }
1352            }
1353        }
1354
1355        if ($failure !== null) {
1356            throw $failure;
1357        }
1358    }
1359
1360    private function processMessages(): void
1361    {
1362        // CurlFactory::finish can retry a transfer by re-invoking this handler
1363        // from inside this loop; the guard keeps that re-entry from recreating
1364        // the multi handle mid-iteration (see applyProxyTunnelOwnership). A
1365        // depth is tracked because a completion callback can re-enter tick(),
1366        // and the nested frame must not clear the outer loop's guard.
1367        ++$this->messageProcessingDepth;
1368
1369        try {
1370            while ($done = \curl_multi_info_read($this->_mh)) {
1371                if ($done['msg'] !== \CURLMSG_DONE) {
1372                    // if it's not done, then it would be premature to remove the handle. ref https://github.com/guzzle/guzzle/pull/2892#issuecomment-945150216
1373                    continue;
1374                }
1375                if (!isset($done['handle'])) {
1376                    // Work around a PHP issue where cancelled transfers may omit the handle.
1377                    // Remove this once we no longer support PHP versions before the fix in
1378                    // https://github.com/php/php-src/pull/16302.
1379                    continue;
1380                }
1381                $id = (int) $done['handle'];
1382                $this->removeCompletedHandleFromMulti($id, $done['handle']);
1383
1384                if (!isset($this->handles[$id])) {
1385                    // Probably was cancelled.
1386                    continue;
1387                }
1388
1389                $entry = $this->handles[$id];
1390                unset($this->handles[$id], $this->delays[$id]);
1391                $entry['easy']->errno = $done['result'];
1392
1393                // finish() can run completion callbacks that cancel this
1394                // promise; a settled promise must not be settled again.
1395                try {
1396                    $result = CurlFactory::finish($this, $entry['easy'], $this->factory);
1397                } catch (\Throwable $e) {
1398                    if (P\State::isPending($entry['deferred'])) {
1399                        $entry['deferred']->reject($e);
1400                    }
1401
1402                    continue;
1403                }
1404
1405                if (P\State::isPending($entry['deferred'])) {
1406                    $entry['deferred']->resolve($result);
1407                }
1408            }
1409        } finally {
1410            --$this->messageProcessingDepth;
1411        }
1412    }
1413
1414    /**
1415     * Bounds a blocking select by the earliest pending request delay so a
1416     * delayed transfer becoming due does not wait out an unrelated
1417     * transfer's full select timeout.
1418     *
1419     * @return float|int
1420     */
1421    private function effectiveSelectTimeout()
1422    {
1423        if ($this->delays === []) {
1424            return $this->selectTimeout;
1425        }
1426
1427        return \min($this->selectTimeout, $this->secondsToNext());
1428    }
1429
1430    /**
1431     * @return float Seconds until the earliest pending delay is due
1432     */
1433    private function secondsToNext(): float
1434    {
1435        $currentTime = Utils::currentTime();
1436        $nextTime = \PHP_FLOAT_MAX;
1437        foreach ($this->delays as $time) {
1438            if ($time < $nextTime) {
1439                $nextTime = $time;
1440            }
1441        }
1442
1443        return \max(0.0, $nextTime - $currentTime);
1444    }
1445
1446    private function timeToNext(): int
1447    {
1448        // PHP_INT_MAX first: min() then returns the int operand whenever the
1449        // microseconds exceed it, so the cast never sees an oversized float.
1450        return (int) \min(\PHP_INT_MAX, $this->secondsToNext() * 1000000);
1451    }
1452}