CurlClientState.php 5.8 KB

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