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

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