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