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