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

Open in your IDE?
  1. <?php
  2. /*
  3.  * This file is part of the Symfony package.
  4.  *
  5.  * (c) Fabien Potencier <[email protected]>
  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 <[email protected]>
  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 bool $performing false;
  31.     private $multi;
  32.     /**
  33.      * @var resource
  34.      */
  35.     private $debugBuffer;
  36.     /**
  37.      * @internal
  38.      */
  39.     public function __construct(CurlClientState $multi\CurlHandle|string $ch, array $options nullLoggerInterface $logger nullstring $method 'GET', callable $resolveRedirect nullint $curlVersion null)
  40.     {
  41.         $this->multi $multi;
  42.         if ($ch instanceof \CurlHandle) {
  43.             $this->handle $ch;
  44.             $this->debugBuffer fopen('php://temp''w+');
  45.             if (0x074000 === $curlVersion) {
  46.                 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.');
  47.             } else {
  48.                 curl_setopt($ch\CURLOPT_VERBOSEtrue);
  49.                 curl_setopt($ch\CURLOPT_STDERR$this->debugBuffer);
  50.             }
  51.         } else {
  52.             $this->info['url'] = $ch;
  53.             $ch $this->handle;
  54.         }
  55.         $this->id $id = (int) $ch;
  56.         $this->logger $logger;
  57.         $this->shouldBuffer $options['buffer'] ?? true;
  58.         $this->timeout $options['timeout'] ?? null;
  59.         $this->info['http_method'] = $method;
  60.         $this->info['user_data'] = $options['user_data'] ?? null;
  61.         $this->info['max_duration'] = $options['max_duration'] ?? null;
  62.         $this->info['start_time'] = $this->info['start_time'] ?? microtime(true);
  63.         $info = &$this->info;
  64.         $headers = &$this->headers;
  65.         $debugBuffer $this->debugBuffer;
  66.         if (!$info['response_headers']) {
  67.             // Used to keep track of what we're waiting for
  68.             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
  69.         }
  70.         curl_setopt($ch\CURLOPT_HEADERFUNCTION, static function ($chstring $data) use (&$info, &$headers$options$multi$id, &$location$resolveRedirect$logger): int {
  71.             if (!== substr_compare($data"\r\n", -2)) {
  72.                 return 0;
  73.             }
  74.             $len 0;
  75.             foreach (explode("\r\n"substr($data0, -2)) as $data) {
  76.                 $len += self::parseHeaderLine($ch$data$info$headers$options$multi$id$location$resolveRedirect$logger);
  77.             }
  78.             return $len;
  79.         });
  80.         if (null === $options) {
  81.             // Pushed response: buffer until requested
  82.             curl_setopt($ch\CURLOPT_WRITEFUNCTION, static function ($chstring $data) use ($multi$id): int {
  83.                 $multi->handlesActivity[$id][] = $data;
  84.                 curl_pause($ch\CURLPAUSE_RECV);
  85.                 return \strlen($data);
  86.             });
  87.             return;
  88.         }
  89.         $execCounter $multi->execCounter;
  90.         $this->info['pause_handler'] = static function (float $duration) use ($ch$multi$execCounter) {
  91.             if ($duration) {
  92.                 if ($execCounter === $multi->execCounter) {
  93.                     $multi->execCounter = !\is_float($execCounter) ? $execCounter \PHP_INT_MIN;
  94.                     curl_multi_remove_handle($multi->handle$ch);
  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->handle$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->handle$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.             curl_multi_remove_handle($multi->handle$ch);
  154.             curl_setopt_array($ch, [
  155.                 \CURLOPT_NOPROGRESS => true,
  156.                 \CURLOPT_PROGRESSFUNCTION => null,
  157.                 \CURLOPT_HEADERFUNCTION => null,
  158.                 \CURLOPT_WRITEFUNCTION => null,
  159.                 \CURLOPT_READFUNCTION => null,
  160.                 \CURLOPT_INFILE => null,
  161.             ]);
  162.             if (!$multi->openHandles) {
  163.                 // Schedule DNS cache eviction for the next request
  164.                 $multi->dnsCache->evictions $multi->dnsCache->evictions ?: $multi->dnsCache->removals;
  165.                 $multi->dnsCache->removals $multi->dnsCache->hostnames = [];
  166.             }
  167.         });
  168.     }
  169.     /**
  170.      * {@inheritdoc}
  171.      */
  172.     public function getInfo(string $type null): mixed
  173.     {
  174.         if (!$info $this->finalInfo) {
  175.             $info array_merge($this->infocurl_getinfo($this->handle));
  176.             $info['url'] = $this->info['url'] ?? $info['url'];
  177.             $info['redirect_url'] = $this->info['redirect_url'] ?? null;
  178.             // workaround curl not subtracting the time offset for pushed responses
  179.             if (isset($this->info['url']) && $info['start_time'] / 1000 $info['total_time']) {
  180.                 $info['total_time'] -= $info['starttransfer_time'] ?: $info['total_time'];
  181.                 $info['starttransfer_time'] = 0.0;
  182.             }
  183.             rewind($this->debugBuffer);
  184.             $info['debug'] = stream_get_contents($this->debugBuffer);
  185.             $waitFor curl_getinfo($this->handle\CURLINFO_PRIVATE);
  186.             if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) {
  187.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  188.                 rewind($this->debugBuffer);
  189.                 ftruncate($this->debugBuffer0);
  190.                 $this->finalInfo $info;
  191.             }
  192.         }
  193.         return null !== $type $info[$type] ?? null $info;
  194.     }
  195.     /**
  196.      * {@inheritdoc}
  197.      */
  198.     public function getContent(bool $throw true): string
  199.     {
  200.         $performing self::$performing;
  201.         self::$performing $performing || '_0' === curl_getinfo($this->handle\CURLINFO_PRIVATE);
  202.         try {
  203.             return $this->doGetContent($throw);
  204.         } finally {
  205.             self::$performing $performing;
  206.         }
  207.     }
  208.     public function __destruct()
  209.     {
  210.         try {
  211.             if (null === $this->timeout) {
  212.                 return; // Unused pushed response
  213.             }
  214.             $this->doDestruct();
  215.         } finally {
  216.             if (\is_resource($this->handle) || $this->handle instanceof \CurlHandle) {
  217.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  218.             }
  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->handle])) {
  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.             $active 0;
  256.             while (\CURLM_CALL_MULTI_PERFORM === ($err curl_multi_exec($multi->handle$active))) {
  257.             }
  258.             if (\CURLM_OK !== $err) {
  259.                 throw new TransportException(curl_multi_strerror($err));
  260.             }
  261.             while ($info curl_multi_info_read($multi->handle)) {
  262.                 if (\CURLMSG_DONE !== $info['msg']) {
  263.                     continue;
  264.                 }
  265.                 $result $info['result'];
  266.                 $id = (int) $ch $info['handle'];
  267.                 $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  268.                 if (\in_array($result, [\CURLE_SEND_ERROR\CURLE_RECV_ERROR/*CURLE_HTTP2*/ 16/*CURLE_HTTP2_STREAM*/ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
  269.                     curl_multi_remove_handle($multi->handle$ch);
  270.                     $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
  271.                     curl_setopt($ch\CURLOPT_PRIVATE$waitFor);
  272.                     curl_setopt($ch\CURLOPT_FORBID_REUSEtrue);
  273.                     if (=== curl_multi_add_handle($multi->handle$ch)) {
  274.                         continue;
  275.                     }
  276.                 }
  277.                 if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
  278.                     $multi->handlesActivity[$id][] = new FirstChunk();
  279.                 }
  280.                 $multi->handlesActivity[$id][] = null;
  281.                 $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)));
  282.             }
  283.         } finally {
  284.             self::$performing false;
  285.         }
  286.     }
  287.     /**
  288.      * {@inheritdoc}
  289.      *
  290.      * @param CurlClientState $multi
  291.      */
  292.     private static function select(ClientState $multifloat $timeout): int
  293.     {
  294.         if ($multi->pauseExpiries) {
  295.             $now microtime(true);
  296.             foreach ($multi->pauseExpiries as $id => $pauseExpiry) {
  297.                 if ($now $pauseExpiry) {
  298.                     $timeout min($timeout$pauseExpiry $now);
  299.                     break;
  300.                 }
  301.                 unset($multi->pauseExpiries[$id]);
  302.                 curl_pause($multi->openHandles[$id][0], \CURLPAUSE_CONT);
  303.                 curl_multi_add_handle($multi->handle$multi->openHandles[$id][0]);
  304.             }
  305.         }
  306.         if (!== $selected curl_multi_select($multi->handle$timeout)) {
  307.             return $selected;
  308.         }
  309.         if ($multi->pauseExpiries && $timeout -= microtime(true) - $now) {
  310.             usleep((int) (1E6 $timeout));
  311.         }
  312.         return 0;
  313.     }
  314.     /**
  315.      * Parses header lines as curl yields them to us.
  316.      */
  317.     private static function parseHeaderLine($chstring $data, array &$info, array &$headers, ?array $optionsCurlClientState $multiint $id, ?string &$location, ?callable $resolveRedirect, ?LoggerInterface $logger): int
  318.     {
  319.         $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  320.         if ('H' !== $waitFor[0]) {
  321.             return \strlen($data); // Ignore HTTP trailers
  322.         }
  323.         if ('' !== $data) {
  324.             // Regular header line: add it to the list
  325.             self::addResponseHeaders([$data], $info$headers);
  326.             if (!str_starts_with($data'HTTP/')) {
  327.                 if (=== stripos($data'Location:')) {
  328.                     $location trim(substr($data9));
  329.                 }
  330.                 return \strlen($data);
  331.             }
  332.             if (\function_exists('openssl_x509_read') && $certinfo curl_getinfo($ch\CURLINFO_CERTINFO)) {
  333.                 $info['peer_certificate_chain'] = array_map('openssl_x509_read'array_column($certinfo'Cert'));
  334.             }
  335.             if (300 <= $info['http_code'] && $info['http_code'] < 400) {
  336.                 if (curl_getinfo($ch\CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  337.                     curl_setopt($ch\CURLOPT_FOLLOWLOCATIONfalse);
  338.                 } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301302], true))) {
  339.                     curl_setopt($ch\CURLOPT_POSTFIELDS'');
  340.                 }
  341.             }
  342.             return \strlen($data);
  343.         }
  344.         // End of headers: handle informational responses, redirects, etc.
  345.         if (200 $statusCode curl_getinfo($ch\CURLINFO_RESPONSE_CODE)) {
  346.             $multi->handlesActivity[$id][] = new InformationalChunk($statusCode$headers);
  347.             $location null;
  348.             return \strlen($data);
  349.         }
  350.         $info['redirect_url'] = null;
  351.         if (300 <= $statusCode && $statusCode 400 && null !== $location) {
  352.             if ($noContent 303 === $statusCode || ('POST' === $info['http_method'] && \in_array($statusCode, [301302], true))) {
  353.                 $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' 'GET';
  354.                 curl_setopt($ch\CURLOPT_CUSTOMREQUEST$info['http_method']);
  355.             }
  356.             if (null === $info['redirect_url'] = $resolveRedirect($ch$location$noContent)) {
  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. }