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

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