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

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