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