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

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