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

Open in your IDE?
  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'] = $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.     /**
  171.      * {@inheritdoc}
  172.      */
  173.     public function getInfo(string $type null): mixed
  174.     {
  175.         if (!$info $this->finalInfo) {
  176.             $info array_merge($this->infocurl_getinfo($this->handle));
  177.             $info['url'] = $this->info['url'] ?? $info['url'];
  178.             $info['redirect_url'] = $this->info['redirect_url'] ?? null;
  179.             // workaround curl not subtracting the time offset for pushed responses
  180.             if (isset($this->info['url']) && $info['start_time'] / 1000 $info['total_time']) {
  181.                 $info['total_time'] -= $info['starttransfer_time'] ?: $info['total_time'];
  182.                 $info['starttransfer_time'] = 0.0;
  183.             }
  184.             rewind($this->debugBuffer);
  185.             $info['debug'] = stream_get_contents($this->debugBuffer);
  186.             $waitFor curl_getinfo($this->handle\CURLINFO_PRIVATE);
  187.             if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) {
  188.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  189.                 rewind($this->debugBuffer);
  190.                 ftruncate($this->debugBuffer0);
  191.                 $this->finalInfo $info;
  192.             }
  193.         }
  194.         return null !== $type $info[$type] ?? null $info;
  195.     }
  196.     /**
  197.      * {@inheritdoc}
  198.      */
  199.     public function getContent(bool $throw true): string
  200.     {
  201.         $performing self::$performing;
  202.         self::$performing $performing || '_0' === curl_getinfo($this->handle\CURLINFO_PRIVATE);
  203.         try {
  204.             return $this->doGetContent($throw);
  205.         } finally {
  206.             self::$performing $performing;
  207.         }
  208.     }
  209.     public function __destruct()
  210.     {
  211.         try {
  212.             if (null === $this->timeout) {
  213.                 return; // Unused pushed response
  214.             }
  215.             $this->doDestruct();
  216.         } finally {
  217.             if (\is_resource($this->handle) || $this->handle instanceof \CurlHandle) {
  218.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  219.             }
  220.         }
  221.     }
  222.     /**
  223.      * {@inheritdoc}
  224.      */
  225.     private static function schedule(self $response, array &$runningResponses): void
  226.     {
  227.         if (isset($runningResponses[$i = (int) $response->multi->handle])) {
  228.             $runningResponses[$i][1][$response->id] = $response;
  229.         } else {
  230.             $runningResponses[$i] = [$response->multi, [$response->id => $response]];
  231.         }
  232.         if ('_0' === curl_getinfo($ch $response->handle\CURLINFO_PRIVATE)) {
  233.             // Response already completed
  234.             $response->multi->handlesActivity[$response->id][] = null;
  235.             $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
  236.         }
  237.     }
  238.     /**
  239.      * {@inheritdoc}
  240.      *
  241.      * @param CurlClientState $multi
  242.      */
  243.     private static function perform(ClientState $multi, array &$responses null): void
  244.     {
  245.         if (self::$performing) {
  246.             if ($responses) {
  247.                 $response current($responses);
  248.                 $multi->handlesActivity[(int) $response->handle][] = null;
  249.                 $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)));
  250.             }
  251.             return;
  252.         }
  253.         try {
  254.             self::$performing true;
  255.             ++$multi->execCounter;
  256.             $active 0;
  257.             while (\CURLM_CALL_MULTI_PERFORM === ($err curl_multi_exec($multi->handle$active))) {
  258.             }
  259.             if (\CURLM_OK !== $err) {
  260.                 throw new TransportException(curl_multi_strerror($err));
  261.             }
  262.             while ($info curl_multi_info_read($multi->handle)) {
  263.                 if (\CURLMSG_DONE !== $info['msg']) {
  264.                     continue;
  265.                 }
  266.                 $result $info['result'];
  267.                 $id = (int) $ch $info['handle'];
  268.                 $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  269.                 if (\in_array($result, [\CURLE_SEND_ERROR\CURLE_RECV_ERROR/* CURLE_HTTP2 */ 16/* CURLE_HTTP2_STREAM */ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
  270.                     curl_multi_remove_handle($multi->handle$ch);
  271.                     $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
  272.                     curl_setopt($ch\CURLOPT_PRIVATE$waitFor);
  273.                     curl_setopt($ch\CURLOPT_FORBID_REUSEtrue);
  274.                     if (=== curl_multi_add_handle($multi->handle$ch)) {
  275.                         continue;
  276.                     }
  277.                 }
  278.                 if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
  279.                     $multi->handlesActivity[$id][] = new FirstChunk();
  280.                 }
  281.                 $multi->handlesActivity[$id][] = null;
  282.                 $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)));
  283.             }
  284.         } finally {
  285.             self::$performing false;
  286.         }
  287.     }
  288.     /**
  289.      * {@inheritdoc}
  290.      *
  291.      * @param CurlClientState $multi
  292.      */
  293.     private static function select(ClientState $multifloat $timeout): int
  294.     {
  295.         if ($multi->pauseExpiries) {
  296.             $now microtime(true);
  297.             foreach ($multi->pauseExpiries as $id => $pauseExpiry) {
  298.                 if ($now $pauseExpiry) {
  299.                     $timeout min($timeout$pauseExpiry $now);
  300.                     break;
  301.                 }
  302.                 unset($multi->pauseExpiries[$id]);
  303.                 curl_pause($multi->openHandles[$id][0], \CURLPAUSE_CONT);
  304.                 curl_multi_add_handle($multi->handle$multi->openHandles[$id][0]);
  305.             }
  306.         }
  307.         if (!== $selected curl_multi_select($multi->handle$timeout)) {
  308.             return $selected;
  309.         }
  310.         if ($multi->pauseExpiries && $timeout -= microtime(true) - $now) {
  311.             usleep((int) (1E6 $timeout));
  312.         }
  313.         return 0;
  314.     }
  315.     /**
  316.      * Parses header lines as curl yields them to us.
  317.      */
  318.     private static function parseHeaderLine($chstring $data, array &$info, array &$headers, ?array $optionsCurlClientState $multiint $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger): int
  319.     {
  320.         $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  321.         if ('H' !== $waitFor[0]) {
  322.             return \strlen($data); // Ignore HTTP trailers
  323.         }
  324.         if ('' !== $data) {
  325.             // Regular header line: add it to the list
  326.             self::addResponseHeaders([$data], $info$headers);
  327.             if (!str_starts_with($data'HTTP/')) {
  328.                 if (=== stripos($data'Location:')) {
  329.                     $location trim(substr($data9));
  330.                 }
  331.                 return \strlen($data);
  332.             }
  333.             if (\function_exists('openssl_x509_read') && $certinfo curl_getinfo($ch\CURLINFO_CERTINFO)) {
  334.                 $info['peer_certificate_chain'] = array_map('openssl_x509_read'array_column($certinfo'Cert'));
  335.             }
  336.             if (300 <= $info['http_code'] && $info['http_code'] < 400) {
  337.                 if (curl_getinfo($ch\CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  338.                     curl_setopt($ch\CURLOPT_FOLLOWLOCATIONfalse);
  339.                 } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301302], true))) {
  340.                     curl_setopt($ch\CURLOPT_POSTFIELDS'');
  341.                 }
  342.             }
  343.             return \strlen($data);
  344.         }
  345.         // End of headers: handle informational responses, redirects, etc.
  346.         if (200 $statusCode curl_getinfo($ch\CURLINFO_RESPONSE_CODE)) {
  347.             $multi->handlesActivity[$id][] = new InformationalChunk($statusCode$headers);
  348.             $location null;
  349.             return \strlen($data);
  350.         }
  351.         $info['redirect_url'] = null;
  352.         if (300 <= $statusCode && $statusCode 400 && null !== $location) {
  353.             if ($noContent 303 === $statusCode || ('POST' === $info['http_method'] && \in_array($statusCode, [301302], true))) {
  354.                 $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' 'GET';
  355.                 curl_setopt($ch\CURLOPT_CUSTOMREQUEST$info['http_method']);
  356.             }
  357.             if (null === $info['redirect_url'] = $resolveRedirect($ch$location$noContent)) {
  358.                 $options['max_redirects'] = curl_getinfo($ch\CURLINFO_REDIRECT_COUNT);
  359.                 curl_setopt($ch\CURLOPT_FOLLOWLOCATIONfalse);
  360.                 curl_setopt($ch\CURLOPT_MAXREDIRS$options['max_redirects']);
  361.             } else {
  362.                 $url parse_url($location ?? ':');
  363.                 if (isset($url['host']) && null !== $ip $multi->dnsCache->hostnames[$url['host'] = strtolower($url['host'])] ?? null) {
  364.                     // Populate DNS cache for redirects if needed
  365.                     $port $url['port'] ?? ('http' === ($url['scheme'] ?? parse_url(curl_getinfo($ch\CURLINFO_EFFECTIVE_URL), \PHP_URL_SCHEME)) ? 80 443);
  366.                     curl_setopt($ch\CURLOPT_RESOLVE, ["{$url['host']}:$port:$ip"]);
  367.                     $multi->dnsCache->removals["-{$url['host']}:$port"] = "-{$url['host']}:$port";
  368.                 }
  369.             }
  370.         }
  371.         if (401 === $statusCode && isset($options['auth_ntlm']) && === strncasecmp($headers['www-authenticate'][0] ?? '''NTLM '5)) {
  372.             // Continue with NTLM auth
  373.         } elseif ($statusCode 300 || 400 <= $statusCode || null === $location || curl_getinfo($ch\CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  374.             // Headers and redirects completed, time to get the response's content
  375.             $multi->handlesActivity[$id][] = new FirstChunk();
  376.             if ('HEAD' === $info['http_method'] || \in_array($statusCode, [204304], true)) {
  377.                 $waitFor '_0'// no content expected
  378.                 $multi->handlesActivity[$id][] = null;
  379.                 $multi->handlesActivity[$id][] = null;
  380.             } else {
  381.                 $waitFor[0] = 'C'// C = content
  382.             }
  383.             curl_setopt($ch\CURLOPT_PRIVATE$waitFor);
  384.         } elseif (null !== $info['redirect_url'] && $logger) {
  385.             $logger->info(sprintf('Redirecting: "%s %s"'$info['http_code'], $info['redirect_url']));
  386.         }
  387.         $location null;
  388.         return \strlen($data);
  389.     }
  390. }