CurlClientState.php 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  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\Internal;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpClient\Response\CurlResponse;
  13. /**
  14. * Internal representation of the cURL client's state.
  15. *
  16. * @author Alexander M. Turek <me@derrabus.de>
  17. *
  18. * @internal
  19. */
  20. final class CurlClientState extends ClientState
  21. {
  22. public ?\CurlMultiHandle $handle;
  23. public ?\CurlShareHandle $share;
  24. /** @var PushedResponse[] */
  25. public array $pushedResponses = [];
  26. public DnsCache $dnsCache;
  27. /** @var float[] */
  28. public array $pauseExpiries = [];
  29. public int $execCounter = \PHP_INT_MIN;
  30. public ?LoggerInterface $logger = null;
  31. public static array $curlVersion;
  32. public function __construct(int $maxHostConnections, int $maxPendingPushes)
  33. {
  34. self::$curlVersion = self::$curlVersion ?? curl_version();
  35. $this->handle = curl_multi_init();
  36. $this->dnsCache = new DnsCache();
  37. $this->reset();
  38. // Don't enable HTTP/1.1 pipelining: it forces responses to be sent in order
  39. if (\defined('CURLPIPE_MULTIPLEX')) {
  40. curl_multi_setopt($this->handle, \CURLMOPT_PIPELINING, \CURLPIPE_MULTIPLEX);
  41. }
  42. if (\defined('CURLMOPT_MAX_HOST_CONNECTIONS')) {
  43. $maxHostConnections = curl_multi_setopt($this->handle, \CURLMOPT_MAX_HOST_CONNECTIONS, 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX) ? 0 : $maxHostConnections;
  44. }
  45. if (\defined('CURLMOPT_MAXCONNECTS') && 0 < $maxHostConnections) {
  46. curl_multi_setopt($this->handle, \CURLMOPT_MAXCONNECTS, $maxHostConnections);
  47. }
  48. // Skip configuring HTTP/2 push when it's unsupported or buggy, see https://bugs.php.net/77535
  49. if (0 >= $maxPendingPushes) {
  50. return;
  51. }
  52. // HTTP/2 push crashes before curl 7.61
  53. if (!\defined('CURLMOPT_PUSHFUNCTION') || 0x073D00 > self::$curlVersion['version_number'] || !(\CURL_VERSION_HTTP2 & self::$curlVersion['features'])) {
  54. return;
  55. }
  56. // Clone to prevent a circular reference
  57. $multi = clone $this;
  58. $multi->handle = null;
  59. $multi->share = null;
  60. $multi->pushedResponses = &$this->pushedResponses;
  61. $multi->logger = &$this->logger;
  62. $multi->handlesActivity = &$this->handlesActivity;
  63. $multi->openHandles = &$this->openHandles;
  64. curl_multi_setopt($this->handle, \CURLMOPT_PUSHFUNCTION, static function ($parent, $pushed, array $requestHeaders) use ($multi, $maxPendingPushes) {
  65. return $multi->handlePush($parent, $pushed, $requestHeaders, $maxPendingPushes);
  66. });
  67. }
  68. public function reset()
  69. {
  70. foreach ($this->pushedResponses as $url => $response) {
  71. $this->logger && $this->logger->debug(sprintf('Unused pushed response: "%s"', $url));
  72. curl_multi_remove_handle($this->handle, $response->handle);
  73. curl_close($response->handle);
  74. }
  75. $this->pushedResponses = [];
  76. $this->dnsCache->evictions = $this->dnsCache->evictions ?: $this->dnsCache->removals;
  77. $this->dnsCache->removals = $this->dnsCache->hostnames = [];
  78. $this->share = curl_share_init();
  79. curl_share_setopt($this->share, \CURLSHOPT_SHARE, \CURL_LOCK_DATA_DNS);
  80. curl_share_setopt($this->share, \CURLSHOPT_SHARE, \CURL_LOCK_DATA_SSL_SESSION);
  81. if (\defined('CURL_LOCK_DATA_CONNECT') && \PHP_VERSION_ID >= 80000) {
  82. curl_share_setopt($this->share, \CURLSHOPT_SHARE, \CURL_LOCK_DATA_CONNECT);
  83. }
  84. }
  85. private function handlePush($parent, $pushed, array $requestHeaders, int $maxPendingPushes): int
  86. {
  87. $headers = [];
  88. $origin = curl_getinfo($parent, \CURLINFO_EFFECTIVE_URL);
  89. foreach ($requestHeaders as $h) {
  90. if (false !== $i = strpos($h, ':', 1)) {
  91. $headers[substr($h, 0, $i)][] = substr($h, 1 + $i);
  92. }
  93. }
  94. if (!isset($headers[':method']) || !isset($headers[':scheme']) || !isset($headers[':authority']) || !isset($headers[':path'])) {
  95. $this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": pushed headers are invalid', $origin));
  96. return \CURL_PUSH_DENY;
  97. }
  98. $url = $headers[':scheme'][0].'://'.$headers[':authority'][0];
  99. // curl before 7.65 doesn't validate the pushed ":authority" header,
  100. // but this is a MUST in the HTTP/2 RFC; let's restrict pushes to the original host,
  101. // ignoring domains mentioned as alt-name in the certificate for now (same as curl).
  102. if (!str_starts_with($origin, $url.'/')) {
  103. $this->logger && $this->logger->debug(sprintf('Rejecting pushed response from "%s": server is not authoritative for "%s"', $origin, $url));
  104. return \CURL_PUSH_DENY;
  105. }
  106. if ($maxPendingPushes <= \count($this->pushedResponses)) {
  107. $fifoUrl = key($this->pushedResponses);
  108. unset($this->pushedResponses[$fifoUrl]);
  109. $this->logger && $this->logger->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
  110. }
  111. $url .= $headers[':path'][0];
  112. $this->logger && $this->logger->debug(sprintf('Queueing pushed response: "%s"', $url));
  113. $this->pushedResponses[$url] = new PushedResponse(new CurlResponse($this, $pushed), $headers, $this->openHandles[(int) $parent][1] ?? [], $pushed);
  114. return \CURL_PUSH_OK;
  115. }
  116. }