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

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