vendor/symfony/http-client/Response/CurlResponse.php line 109

  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <fabien@symfony.com>
  6.  *
  7.  * For the full copyright and license information, please view the LICENSE
  8.  * file that was distributed with this source code.
  9.  */
  10. namespace Symfony\Component\HttpClient\Response;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpClient\Chunk\FirstChunk;
  13. use Symfony\Component\HttpClient\Chunk\InformationalChunk;
  14. use Symfony\Component\HttpClient\Exception\TransportException;
  15. use Symfony\Component\HttpClient\Internal\Canary;
  16. use Symfony\Component\HttpClient\Internal\ClientState;
  17. use Symfony\Component\HttpClient\Internal\CurlClientState;
  18. use Symfony\Contracts\HttpClient\ResponseInterface;
  19. /**
  20.  * @author Nicolas Grekas <p@tchwork.com>
  21.  *
  22.  * @internal
  23.  */
  24. final class CurlResponse implements ResponseInterfaceStreamableInterface
  25. {
  26.     use CommonResponseTrait {
  27.         getContent as private doGetContent;
  28.     }
  29.     use TransportResponseTrait;
  30.     private static bool $performing false;
  31.     private CurlClientState $multi;
  32.     /**
  33.      * @var resource
  34.      */
  35.     private $debugBuffer;
  36.     /**
  37.      * @internal
  38.      */
  39.     public function __construct(CurlClientState $multi\CurlHandle|string $ch, array $options nullLoggerInterface $logger nullstring $method 'GET', callable $resolveRedirect nullint $curlVersion nullstring $originalUrl null)
  40.     {
  41.         $this->multi $multi;
  42.         if ($ch instanceof \CurlHandle) {
  43.             $this->handle $ch;
  44.             $this->debugBuffer fopen('php://temp''w+');
  45.             if (0x074000 === $curlVersion) {
  46.                 fwrite($this->debugBuffer'Due to a bug in curl 7.64.0, the debug log is disabled; use another version to work around the issue.');
  47.             } else {
  48.                 curl_setopt($ch\CURLOPT_VERBOSEtrue);
  49.                 curl_setopt($ch\CURLOPT_STDERR$this->debugBuffer);
  50.             }
  51.         } else {
  52.             $this->info['url'] = $ch;
  53.             $ch $this->handle;
  54.         }
  55.         $this->id $id = (int) $ch;
  56.         $this->logger $logger;
  57.         $this->shouldBuffer $options['buffer'] ?? true;
  58.         $this->timeout $options['timeout'] ?? null;
  59.         $this->info['http_method'] = $method;
  60.         $this->info['user_data'] = $options['user_data'] ?? null;
  61.         $this->info['max_duration'] = $options['max_duration'] ?? null;
  62.         $this->info['start_time'] ??= microtime(true);
  63.         $this->info['original_url'] = $originalUrl ?? $this->info['url'] ?? curl_getinfo($ch\CURLINFO_EFFECTIVE_URL);
  64.         $info = &$this->info;
  65.         $headers = &$this->headers;
  66.         $debugBuffer $this->debugBuffer;
  67.         if (!$info['response_headers']) {
  68.             // Used to keep track of what we're waiting for
  69.             curl_setopt($ch\CURLOPT_PRIVATE\in_array($method, ['GET''HEAD''OPTIONS''TRACE'], true) && 1.0 < (float) ($options['http_version'] ?? 1.1) ? 'H2' 'H0'); // H = headers + retry counter
  70.         }
  71.         curl_setopt($ch\CURLOPT_HEADERFUNCTION, static function ($chstring $data) use (&$info, &$headers$options$multi$id, &$location$resolveRedirect$logger): int {
  72.             if (!== substr_compare($data"\r\n", -2)) {
  73.                 return 0;
  74.             }
  75.             $len 0;
  76.             foreach (explode("\r\n"substr($data0, -2)) as $data) {
  77.                 $len += self::parseHeaderLine($ch$data$info$headers$options$multi$id$location$resolveRedirect$logger);
  78.             }
  79.             return $len;
  80.         });
  81.         if (null === $options) {
  82.             // Pushed response: buffer until requested
  83.             curl_setopt($ch\CURLOPT_WRITEFUNCTION, static function ($chstring $data) use ($multi$id): int {
  84.                 $multi->handlesActivity[$id][] = $data;
  85.                 curl_pause($ch\CURLPAUSE_RECV);
  86.                 return \strlen($data);
  87.             });
  88.             return;
  89.         }
  90.         $execCounter $multi->execCounter;
  91.         $this->info['pause_handler'] = static function (float $duration) use ($ch$multi$execCounter) {
  92.             if ($duration) {
  93.                 if ($execCounter === $multi->execCounter) {
  94.                     $multi->execCounter = !\is_float($execCounter) ? $execCounter \PHP_INT_MIN;
  95.                     curl_multi_remove_handle($multi->handle$ch);
  96.                 }
  97.                 $lastExpiry end($multi->pauseExpiries);
  98.                 $multi->pauseExpiries[(int) $ch] = $duration += microtime(true);
  99.                 if (false !== $lastExpiry && $lastExpiry $duration) {
  100.                     asort($multi->pauseExpiries);
  101.                 }
  102.                 curl_pause($ch\CURLPAUSE_ALL);
  103.             } else {
  104.                 unset($multi->pauseExpiries[(int) $ch]);
  105.                 curl_pause($ch\CURLPAUSE_CONT);
  106.                 curl_multi_add_handle($multi->handle$ch);
  107.             }
  108.         };
  109.         $this->inflate = !isset($options['normalized_headers']['accept-encoding']);
  110.         curl_pause($ch\CURLPAUSE_CONT);
  111.         if ($onProgress $options['on_progress']) {
  112.             $url = isset($info['url']) ? ['url' => $info['url']] : [];
  113.             curl_setopt($ch\CURLOPT_NOPROGRESSfalse);
  114.             curl_setopt($ch\CURLOPT_PROGRESSFUNCTION, static function ($ch$dlSize$dlNow) use ($onProgress, &$info$url$multi$debugBuffer) {
  115.                 try {
  116.                     rewind($debugBuffer);
  117.                     $debug = ['debug' => stream_get_contents($debugBuffer)];
  118.                     $onProgress($dlNow$dlSize$url curl_getinfo($ch) + $info $debug);
  119.                 } catch (\Throwable $e) {
  120.                     $multi->handlesActivity[(int) $ch][] = null;
  121.                     $multi->handlesActivity[(int) $ch][] = $e;
  122.                     return 1// Abort the request
  123.                 }
  124.                 return null;
  125.             });
  126.         }
  127.         curl_setopt($ch\CURLOPT_WRITEFUNCTION, static function ($chstring $data) use ($multi$id): int {
  128.             if ('H' === (curl_getinfo($ch\CURLINFO_PRIVATE)[0] ?? null)) {
  129.                 $multi->handlesActivity[$id][] = null;
  130.                 $multi->handlesActivity[$id][] = new TransportException(sprintf('Unsupported protocol for "%s"'curl_getinfo($ch\CURLINFO_EFFECTIVE_URL)));
  131.                 return 0;
  132.             }
  133.             curl_setopt($ch\CURLOPT_WRITEFUNCTION, static function ($chstring $data) use ($multi$id): int {
  134.                 $multi->handlesActivity[$id][] = $data;
  135.                 return \strlen($data);
  136.             });
  137.             $multi->handlesActivity[$id][] = $data;
  138.             return \strlen($data);
  139.         });
  140.         $this->initializer = static function (self $response) {
  141.             $waitFor curl_getinfo($ch $response->handle\CURLINFO_PRIVATE);
  142.             return 'H' === $waitFor[0];
  143.         };
  144.         // Schedule the request in a non-blocking way
  145.         $multi->lastTimeout null;
  146.         $multi->openHandles[$id] = [$ch$options];
  147.         curl_multi_add_handle($multi->handle$ch);
  148.         $this->canary = new Canary(static function () use ($ch$multi$id) {
  149.             unset($multi->pauseExpiries[$id], $multi->openHandles[$id], $multi->handlesActivity[$id]);
  150.             curl_setopt($ch\CURLOPT_PRIVATE'_0');
  151.             if (self::$performing) {
  152.                 return;
  153.             }
  154.             curl_multi_remove_handle($multi->handle$ch);
  155.             curl_setopt_array($ch, [
  156.                 \CURLOPT_NOPROGRESS => true,
  157.                 \CURLOPT_PROGRESSFUNCTION => null,
  158.                 \CURLOPT_HEADERFUNCTION => null,
  159.                 \CURLOPT_WRITEFUNCTION => null,
  160.                 \CURLOPT_READFUNCTION => null,
  161.                 \CURLOPT_INFILE => null,
  162.             ]);
  163.             if (!$multi->openHandles) {
  164.                 // Schedule DNS cache eviction for the next request
  165.                 $multi->dnsCache->evictions $multi->dnsCache->evictions ?: $multi->dnsCache->removals;
  166.                 $multi->dnsCache->removals $multi->dnsCache->hostnames = [];
  167.             }
  168.         });
  169.     }
  170.     public function getInfo(string $type null): mixed
  171.     {
  172.         if (!$info $this->finalInfo) {
  173.             $info array_merge($this->infocurl_getinfo($this->handle));
  174.             $info['url'] = $this->info['url'] ?? $info['url'];
  175.             $info['redirect_url'] = $this->info['redirect_url'] ?? null;
  176.             // workaround curl not subtracting the time offset for pushed responses
  177.             if (isset($this->info['url']) && $info['start_time'] / 1000 $info['total_time']) {
  178.                 $info['total_time'] -= $info['starttransfer_time'] ?: $info['total_time'];
  179.                 $info['starttransfer_time'] = 0.0;
  180.             }
  181.             rewind($this->debugBuffer);
  182.             $info['debug'] = stream_get_contents($this->debugBuffer);
  183.             $waitFor curl_getinfo($this->handle\CURLINFO_PRIVATE);
  184.             if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) {
  185.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  186.                 rewind($this->debugBuffer);
  187.                 ftruncate($this->debugBuffer0);
  188.                 $this->finalInfo $info;
  189.             }
  190.         }
  191.         return null !== $type $info[$type] ?? null $info;
  192.     }
  193.     public function getContent(bool $throw true): string
  194.     {
  195.         $performing self::$performing;
  196.         self::$performing $performing || '_0' === curl_getinfo($this->handle\CURLINFO_PRIVATE);
  197.         try {
  198.             return $this->doGetContent($throw);
  199.         } finally {
  200.             self::$performing $performing;
  201.         }
  202.     }
  203.     public function __destruct()
  204.     {
  205.         try {
  206.             if (null === $this->timeout) {
  207.                 return; // Unused pushed response
  208.             }
  209.             $this->doDestruct();
  210.         } finally {
  211.             if (\is_resource($this->handle) || $this->handle instanceof \CurlHandle) {
  212.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  213.             }
  214.         }
  215.     }
  216.     private static function schedule(self $response, array &$runningResponses): void
  217.     {
  218.         if (isset($runningResponses[$i = (int) $response->multi->handle])) {
  219.             $runningResponses[$i][1][$response->id] = $response;
  220.         } else {
  221.             $runningResponses[$i] = [$response->multi, [$response->id => $response]];
  222.         }
  223.         if ('_0' === curl_getinfo($ch $response->handle\CURLINFO_PRIVATE)) {
  224.             // Response already completed
  225.             $response->multi->handlesActivity[$response->id][] = null;
  226.             $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
  227.         }
  228.     }
  229.     /**
  230.      * @param CurlClientState $multi
  231.      */
  232.     private static function perform(ClientState $multi, array &$responses null): void
  233.     {
  234.         if (self::$performing) {
  235.             if ($responses) {
  236.                 $response current($responses);
  237.                 $multi->handlesActivity[(int) $response->handle][] = null;
  238.                 $multi->handlesActivity[(int) $response->handle][] = new TransportException(sprintf('Userland callback cannot use the client nor the response while processing "%s".'curl_getinfo($response->handle\CURLINFO_EFFECTIVE_URL)));
  239.             }
  240.             return;
  241.         }
  242.         try {
  243.             self::$performing true;
  244.             ++$multi->execCounter;
  245.             $active 0;
  246.             while (\CURLM_CALL_MULTI_PERFORM === ($err curl_multi_exec($multi->handle$active))) {
  247.             }
  248.             if (\CURLM_OK !== $err) {
  249.                 throw new TransportException(curl_multi_strerror($err));
  250.             }
  251.             while ($info curl_multi_info_read($multi->handle)) {
  252.                 if (\CURLMSG_DONE !== $info['msg']) {
  253.                     continue;
  254.                 }
  255.                 $result $info['result'];
  256.                 $id = (int) $ch $info['handle'];
  257.                 $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  258.                 if (\in_array($result, [\CURLE_SEND_ERROR\CURLE_RECV_ERROR/* CURLE_HTTP2 */ 16/* CURLE_HTTP2_STREAM */ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
  259.                     curl_multi_remove_handle($multi->handle$ch);
  260.                     $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
  261.                     curl_setopt($ch\CURLOPT_PRIVATE$waitFor);
  262.                     curl_setopt($ch\CURLOPT_FORBID_REUSEtrue);
  263.                     if (=== curl_multi_add_handle($multi->handle$ch)) {
  264.                         continue;
  265.                     }
  266.                 }
  267.                 if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
  268.                     $multi->handlesActivity[$id][] = new FirstChunk();
  269.                 }
  270.                 $multi->handlesActivity[$id][] = null;
  271.                 $multi->handlesActivity[$id][] = \in_array($result, [\CURLE_OK\CURLE_TOO_MANY_REDIRECTS], true) || '_0' === $waitFor || curl_getinfo($ch\CURLINFO_SIZE_DOWNLOAD) === curl_getinfo($ch\CURLINFO_CONTENT_LENGTH_DOWNLOAD) ? null : new TransportException(ucfirst(curl_error($ch) ?: curl_strerror($result)).sprintf(' for "%s".'curl_getinfo($ch\CURLINFO_EFFECTIVE_URL)));
  272.             }
  273.         } finally {
  274.             self::$performing false;
  275.         }
  276.     }
  277.     /**
  278.      * @param CurlClientState $multi
  279.      */
  280.     private static function select(ClientState $multifloat $timeout): int
  281.     {
  282.         if ($multi->pauseExpiries) {
  283.             $now microtime(true);
  284.             foreach ($multi->pauseExpiries as $id => $pauseExpiry) {
  285.                 if ($now $pauseExpiry) {
  286.                     $timeout min($timeout$pauseExpiry $now);
  287.                     break;
  288.                 }
  289.                 unset($multi->pauseExpiries[$id]);
  290.                 curl_pause($multi->openHandles[$id][0], \CURLPAUSE_CONT);
  291.                 curl_multi_add_handle($multi->handle$multi->openHandles[$id][0]);
  292.             }
  293.         }
  294.         if (!== $selected curl_multi_select($multi->handle$timeout)) {
  295.             return $selected;
  296.         }
  297.         if ($multi->pauseExpiries && $timeout -= microtime(true) - $now) {
  298.             usleep((int) (1E6 $timeout));
  299.         }
  300.         return 0;
  301.     }
  302.     /**
  303.      * Parses header lines as curl yields them to us.
  304.      */
  305.     private static function parseHeaderLine($chstring $data, array &$info, array &$headers, ?array $optionsCurlClientState $multiint $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger): int
  306.     {
  307.         $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  308.         if ('H' !== $waitFor[0]) {
  309.             return \strlen($data); // Ignore HTTP trailers
  310.         }
  311.         if ('' !== $data) {
  312.             // Regular header line: add it to the list
  313.             self::addResponseHeaders([$data], $info$headers);
  314.             if (!str_starts_with($data'HTTP/')) {
  315.                 if (=== stripos($data'Location:')) {
  316.                     $location trim(substr($data9));
  317.                 }
  318.                 return \strlen($data);
  319.             }
  320.             if (\function_exists('openssl_x509_read') && $certinfo curl_getinfo($ch\CURLINFO_CERTINFO)) {
  321.                 $info['peer_certificate_chain'] = array_map('openssl_x509_read'array_column($certinfo'Cert'));
  322.             }
  323.             if (300 <= $info['http_code'] && $info['http_code'] < 400) {
  324.                 if (curl_getinfo($ch\CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  325.                     curl_setopt($ch\CURLOPT_FOLLOWLOCATIONfalse);
  326.                 } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301302], true))) {
  327.                     curl_setopt($ch\CURLOPT_POSTFIELDS'');
  328.                 }
  329.             }
  330.             return \strlen($data);
  331.         }
  332.         // End of headers: handle informational responses, redirects, etc.
  333.         if (200 $statusCode curl_getinfo($ch\CURLINFO_RESPONSE_CODE)) {
  334.             $multi->handlesActivity[$id][] = new InformationalChunk($statusCode$headers);
  335.             $location null;
  336.             return \strlen($data);
  337.         }
  338.         $info['redirect_url'] = null;
  339.         if (300 <= $statusCode && $statusCode 400 && null !== $location) {
  340.             if ($noContent 303 === $statusCode || ('POST' === $info['http_method'] && \in_array($statusCode, [301302], true))) {
  341.                 $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' 'GET';
  342.                 curl_setopt($ch\CURLOPT_CUSTOMREQUEST$info['http_method']);
  343.             }
  344.             if (null === $info['redirect_url'] = $resolveRedirect($ch$location$noContent)) {
  345.                 $options['max_redirects'] = curl_getinfo($ch\CURLINFO_REDIRECT_COUNT);
  346.                 curl_setopt($ch\CURLOPT_FOLLOWLOCATIONfalse);
  347.                 curl_setopt($ch\CURLOPT_MAXREDIRS$options['max_redirects']);
  348.             } else {
  349.                 $url parse_url($location ?? ':');
  350.                 if (isset($url['host']) && null !== $ip $multi->dnsCache->hostnames[$url['host'] = strtolower($url['host'])] ?? null) {
  351.                     // Populate DNS cache for redirects if needed
  352.                     $port $url['port'] ?? ('http' === ($url['scheme'] ?? parse_url(curl_getinfo($ch\CURLINFO_EFFECTIVE_URL), \PHP_URL_SCHEME)) ? 80 443);
  353.                     curl_setopt($ch\CURLOPT_RESOLVE, ["{$url['host']}:$port:$ip"]);
  354.                     $multi->dnsCache->removals["-{$url['host']}:$port"] = "-{$url['host']}:$port";
  355.                 }
  356.             }
  357.         }
  358.         if (401 === $statusCode && isset($options['auth_ntlm']) && === strncasecmp($headers['www-authenticate'][0] ?? '''NTLM '5)) {
  359.             // Continue with NTLM auth
  360.         } elseif ($statusCode 300 || 400 <= $statusCode || null === $location || curl_getinfo($ch\CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  361.             // Headers and redirects completed, time to get the response's content
  362.             $multi->handlesActivity[$id][] = new FirstChunk();
  363.             if ('HEAD' === $info['http_method'] || \in_array($statusCode, [204304], true)) {
  364.                 $waitFor '_0'// no content expected
  365.                 $multi->handlesActivity[$id][] = null;
  366.                 $multi->handlesActivity[$id][] = null;
  367.             } else {
  368.                 $waitFor[0] = 'C'// C = content
  369.             }
  370.             curl_setopt($ch\CURLOPT_PRIVATE$waitFor);
  371.         } elseif (null !== $info['redirect_url'] && $logger) {
  372.             $logger->info(sprintf('Redirecting: "%s %s"'$info['http_code'], $info['redirect_url']));
  373.         }
  374.         $location null;
  375.         return \strlen($data);
  376.     }
  377. }