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 $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.             $resolve = static function (string $host, ?string $ip null) use ($multi): ?string {
  102.                 if (null !== $ip) {
  103.                     $multi->dnsCache->hostnames[$host] = $ip;
  104.                 }
  105.                 return $multi->dnsCache->hostnames[$host] ?? null;
  106.             };
  107.             $url = isset($info['url']) ? ['url' => $info['url']] : [];
  108.             curl_setopt($ch\CURLOPT_NOPROGRESSfalse);
  109.             curl_setopt($ch\CURLOPT_PROGRESSFUNCTION, static function ($ch$dlSize$dlNow) use ($onProgress, &$info$url$multi$debugBuffer$resolve) {
  110.                 try {
  111.                     rewind($debugBuffer);
  112.                     $debug = ['debug' => stream_get_contents($debugBuffer)];
  113.                     $onProgress($dlNow$dlSize$url curl_getinfo($ch) + $info $debug$resolve);
  114.                 } catch (\Throwable $e) {
  115.                     $multi->handlesActivity[(int) $ch][] = null;
  116.                     $multi->handlesActivity[(int) $ch][] = $e;
  117.                     return 1// Abort the request
  118.                 }
  119.                 return null;
  120.             });
  121.         }
  122.         curl_setopt($ch\CURLOPT_WRITEFUNCTION, static function ($chstring $data) use ($multi$id): int {
  123.             if ('H' === (curl_getinfo($ch\CURLINFO_PRIVATE)[0] ?? null)) {
  124.                 $multi->handlesActivity[$id][] = null;
  125.                 $multi->handlesActivity[$id][] = new TransportException(sprintf('Unsupported protocol for "%s"'curl_getinfo($ch\CURLINFO_EFFECTIVE_URL)));
  126.                 return 0;
  127.             }
  128.             curl_setopt($ch\CURLOPT_WRITEFUNCTION, static function ($chstring $data) use ($multi$id): int {
  129.                 $multi->handlesActivity[$id][] = $data;
  130.                 return \strlen($data);
  131.             });
  132.             $multi->handlesActivity[$id][] = $data;
  133.             return \strlen($data);
  134.         });
  135.         $this->initializer = static function (self $response) {
  136.             $waitFor curl_getinfo($ch $response->handle\CURLINFO_PRIVATE);
  137.             return 'H' === $waitFor[0];
  138.         };
  139.         // Schedule the request in a non-blocking way
  140.         $multi->lastTimeout null;
  141.         $multi->openHandles[$id] = [$ch$options];
  142.         curl_multi_add_handle($multi->handle$ch);
  143.         $this->canary = new Canary(static function () use ($ch$multi$id) {
  144.             unset($multi->pauseExpiries[$id], $multi->openHandles[$id], $multi->handlesActivity[$id]);
  145.             curl_setopt($ch\CURLOPT_PRIVATE'_0');
  146.             if ($multi->performing) {
  147.                 return;
  148.             }
  149.             curl_multi_remove_handle($multi->handle$ch);
  150.             curl_setopt_array($ch, [
  151.                 \CURLOPT_NOPROGRESS => true,
  152.                 \CURLOPT_PROGRESSFUNCTION => null,
  153.                 \CURLOPT_HEADERFUNCTION => null,
  154.                 \CURLOPT_WRITEFUNCTION => null,
  155.                 \CURLOPT_READFUNCTION => null,
  156.                 \CURLOPT_INFILE => null,
  157.             ]);
  158.             if (!$multi->openHandles) {
  159.                 // Schedule DNS cache eviction for the next request
  160.                 $multi->dnsCache->evictions $multi->dnsCache->evictions ?: $multi->dnsCache->removals;
  161.                 $multi->dnsCache->removals $multi->dnsCache->hostnames = [];
  162.             }
  163.         });
  164.     }
  165.     /**
  166.      * {@inheritdoc}
  167.      */
  168.     public function getInfo(?string $type null)
  169.     {
  170.         if (!$info $this->finalInfo) {
  171.             $info array_merge($this->infocurl_getinfo($this->handle));
  172.             $info['url'] = $this->info['url'] ?? $info['url'];
  173.             $info['redirect_url'] = $this->info['redirect_url'] ?? null;
  174.             // workaround curl not subtracting the time offset for pushed responses
  175.             if (isset($this->info['url']) && $info['start_time'] / 1000 $info['total_time']) {
  176.                 $info['total_time'] -= $info['starttransfer_time'] ?: $info['total_time'];
  177.                 $info['starttransfer_time'] = 0.0;
  178.             }
  179.             rewind($this->debugBuffer);
  180.             $info['debug'] = stream_get_contents($this->debugBuffer);
  181.             $waitFor curl_getinfo($this->handle\CURLINFO_PRIVATE);
  182.             if ('H' !== $waitFor[0] && 'C' !== $waitFor[0]) {
  183.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  184.                 rewind($this->debugBuffer);
  185.                 ftruncate($this->debugBuffer0);
  186.                 $this->finalInfo $info;
  187.             }
  188.         }
  189.         return null !== $type $info[$type] ?? null $info;
  190.     }
  191.     /**
  192.      * {@inheritdoc}
  193.      */
  194.     public function getContent(bool $throw true): string
  195.     {
  196.         $performing $this->multi->performing;
  197.         $this->multi->performing $performing || '_0' === curl_getinfo($this->handle\CURLINFO_PRIVATE);
  198.         try {
  199.             return $this->doGetContent($throw);
  200.         } finally {
  201.             $this->multi->performing $performing;
  202.         }
  203.     }
  204.     public function __destruct()
  205.     {
  206.         try {
  207.             if (null === $this->timeout) {
  208.                 return; // Unused pushed response
  209.             }
  210.             $this->doDestruct();
  211.         } finally {
  212.             if (\is_resource($this->handle) || $this->handle instanceof \CurlHandle) {
  213.                 curl_setopt($this->handle\CURLOPT_VERBOSEfalse);
  214.             }
  215.         }
  216.     }
  217.     /**
  218.      * {@inheritdoc}
  219.      */
  220.     private static function schedule(self $response, array &$runningResponses): void
  221.     {
  222.         if (isset($runningResponses[$i = (int) $response->multi->handle])) {
  223.             $runningResponses[$i][1][$response->id] = $response;
  224.         } else {
  225.             $runningResponses[$i] = [$response->multi, [$response->id => $response]];
  226.         }
  227.         if ('_0' === curl_getinfo($ch $response->handle\CURLINFO_PRIVATE)) {
  228.             // Response already completed
  229.             $response->multi->handlesActivity[$response->id][] = null;
  230.             $response->multi->handlesActivity[$response->id][] = null !== $response->info['error'] ? new TransportException($response->info['error']) : null;
  231.         }
  232.     }
  233.     /**
  234.      * {@inheritdoc}
  235.      *
  236.      * @param CurlClientState $multi
  237.      */
  238.     private static function perform(ClientState $multi, ?array &$responses null): void
  239.     {
  240.         if ($multi->performing) {
  241.             if ($responses) {
  242.                 $response current($responses);
  243.                 $multi->handlesActivity[(int) $response->handle][] = null;
  244.                 $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)));
  245.             }
  246.             return;
  247.         }
  248.         try {
  249.             $multi->performing true;
  250.             ++$multi->execCounter;
  251.             $active 0;
  252.             while (\CURLM_CALL_MULTI_PERFORM === ($err curl_multi_exec($multi->handle$active))) {
  253.             }
  254.             if (\CURLM_OK !== $err) {
  255.                 throw new TransportException(curl_multi_strerror($err));
  256.             }
  257.             while ($info curl_multi_info_read($multi->handle)) {
  258.                 if (\CURLMSG_DONE !== $info['msg']) {
  259.                     continue;
  260.                 }
  261.                 $result $info['result'];
  262.                 $id = (int) $ch $info['handle'];
  263.                 $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  264.                 if (\in_array($result, [\CURLE_SEND_ERROR\CURLE_RECV_ERROR/* CURLE_HTTP2 */ 16/* CURLE_HTTP2_STREAM */ 92], true) && $waitFor[1] && 'C' !== $waitFor[0]) {
  265.                     curl_multi_remove_handle($multi->handle$ch);
  266.                     $waitFor[1] = (string) ((int) $waitFor[1] - 1); // decrement the retry counter
  267.                     curl_setopt($ch\CURLOPT_PRIVATE$waitFor);
  268.                     curl_setopt($ch\CURLOPT_FORBID_REUSEtrue);
  269.                     if (=== curl_multi_add_handle($multi->handle$ch)) {
  270.                         continue;
  271.                     }
  272.                 }
  273.                 if (\CURLE_RECV_ERROR === $result && 'H' === $waitFor[0] && 400 <= ($responses[(int) $ch]->info['http_code'] ?? 0)) {
  274.                     $multi->handlesActivity[$id][] = new FirstChunk();
  275.                 }
  276.                 $multi->handlesActivity[$id][] = null;
  277.                 $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)));
  278.             }
  279.         } finally {
  280.             $multi->performing false;
  281.         }
  282.     }
  283.     /**
  284.      * {@inheritdoc}
  285.      *
  286.      * @param CurlClientState $multi
  287.      */
  288.     private static function select(ClientState $multifloat $timeout): int
  289.     {
  290.         if (\PHP_VERSION_ID 70211) {
  291.             // workaround https://bugs.php.net/76480
  292.             $timeout min($timeout0.01);
  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.         if (!str_ends_with($data"\r\n")) {
  320.             return 0;
  321.         }
  322.         $waitFor = @curl_getinfo($ch\CURLINFO_PRIVATE) ?: '_0';
  323.         if ('H' !== $waitFor[0]) {
  324.             return \strlen($data); // Ignore HTTP trailers
  325.         }
  326.         $statusCode curl_getinfo($ch\CURLINFO_RESPONSE_CODE);
  327.         if ($statusCode !== $info['http_code'] && !preg_match("#^HTTP/\d+(?:\.\d+)? {$statusCode}(?: |\r\n$)#"$data)) {
  328.             return \strlen($data); // Ignore headers from responses to CONNECT requests
  329.         }
  330.         if ("\r\n" !== $data) {
  331.             // Regular header line: add it to the list
  332.             self::addResponseHeaders([substr($data0, -2)], $info$headers);
  333.             if (!str_starts_with($data'HTTP/')) {
  334.                 if (=== stripos($data'Location:')) {
  335.                     $location trim(substr($data9, -2));
  336.                 }
  337.                 return \strlen($data);
  338.             }
  339.             if (\function_exists('openssl_x509_read') && $certinfo curl_getinfo($ch\CURLINFO_CERTINFO)) {
  340.                 $info['peer_certificate_chain'] = array_map('openssl_x509_read'array_column($certinfo'Cert'));
  341.             }
  342.             if (300 <= $info['http_code'] && $info['http_code'] < 400) {
  343.                 if (curl_getinfo($ch\CURLINFO_REDIRECT_COUNT) === $options['max_redirects']) {
  344.                     curl_setopt($ch\CURLOPT_FOLLOWLOCATIONfalse);
  345.                 } elseif (303 === $info['http_code'] || ('POST' === $info['http_method'] && \in_array($info['http_code'], [301302], true))) {
  346.                     curl_setopt($ch\CURLOPT_POSTFIELDS'');
  347.                 }
  348.             }
  349.             return \strlen($data);
  350.         }
  351.         // End of headers: handle informational responses, redirects, etc.
  352.         if (200 $statusCode) {
  353.             $multi->handlesActivity[$id][] = new InformationalChunk($statusCode$headers);
  354.             $location null;
  355.             return \strlen($data);
  356.         }
  357.         $info['redirect_url'] = null;
  358.         if (300 <= $statusCode && $statusCode 400 && null !== $location) {
  359.             if ($noContent 303 === $statusCode || ('POST' === $info['http_method'] && \in_array($statusCode, [301302], true))) {
  360.                 $info['http_method'] = 'HEAD' === $info['http_method'] ? 'HEAD' 'GET';
  361.                 curl_setopt($ch\CURLOPT_CUSTOMREQUEST$info['http_method']);
  362.             }
  363.             if (null === $info['redirect_url'] = $resolveRedirect($ch$location$noContent)) {
  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. }