AmpClientState.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  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 Amp\CancellationToken;
  12. use Amp\Deferred;
  13. use Amp\Http\Client\Connection\ConnectionLimitingPool;
  14. use Amp\Http\Client\Connection\DefaultConnectionFactory;
  15. use Amp\Http\Client\InterceptedHttpClient;
  16. use Amp\Http\Client\Interceptor\RetryRequests;
  17. use Amp\Http\Client\PooledHttpClient;
  18. use Amp\Http\Client\Request;
  19. use Amp\Http\Client\Response;
  20. use Amp\Http\Tunnel\Http1TunnelConnector;
  21. use Amp\Http\Tunnel\Https1TunnelConnector;
  22. use Amp\Promise;
  23. use Amp\Socket\Certificate;
  24. use Amp\Socket\ClientTlsContext;
  25. use Amp\Socket\ConnectContext;
  26. use Amp\Socket\Connector;
  27. use Amp\Socket\DnsConnector;
  28. use Amp\Socket\SocketAddress;
  29. use Amp\Success;
  30. use Psr\Log\LoggerInterface;
  31. /**
  32. * Internal representation of the Amp client's state.
  33. *
  34. * @author Nicolas Grekas <p@tchwork.com>
  35. *
  36. * @internal
  37. */
  38. final class AmpClientState extends ClientState
  39. {
  40. public $dnsCache = [];
  41. public $responseCount = 0;
  42. public $pushedResponses = [];
  43. private $clients = [];
  44. private $clientConfigurator;
  45. private $maxHostConnections;
  46. private $maxPendingPushes;
  47. private $logger;
  48. public function __construct(?callable $clientConfigurator, int $maxHostConnections, int $maxPendingPushes, ?LoggerInterface &$logger)
  49. {
  50. $this->clientConfigurator = $clientConfigurator ?? static function (PooledHttpClient $client) {
  51. return new InterceptedHttpClient($client, new RetryRequests(2));
  52. };
  53. $this->maxHostConnections = $maxHostConnections;
  54. $this->maxPendingPushes = $maxPendingPushes;
  55. $this->logger = &$logger;
  56. }
  57. /**
  58. * @return Promise<Response>
  59. */
  60. public function request(array $options, Request $request, CancellationToken $cancellation, array &$info, \Closure $onProgress, &$handle): Promise
  61. {
  62. if ($options['proxy']) {
  63. if ($request->hasHeader('proxy-authorization')) {
  64. $options['proxy']['auth'] = $request->getHeader('proxy-authorization');
  65. }
  66. // Matching "no_proxy" should follow the behavior of curl
  67. $host = $request->getUri()->getHost();
  68. foreach ($options['proxy']['no_proxy'] as $rule) {
  69. $dotRule = '.'.ltrim($rule, '.');
  70. if ('*' === $rule || $host === $rule || substr($host, -\strlen($dotRule)) === $dotRule) {
  71. $options['proxy'] = null;
  72. break;
  73. }
  74. }
  75. }
  76. $request = clone $request;
  77. if ($request->hasHeader('proxy-authorization')) {
  78. $request->removeHeader('proxy-authorization');
  79. }
  80. if ($options['capture_peer_cert_chain']) {
  81. $info['peer_certificate_chain'] = [];
  82. }
  83. $request->addEventListener(new AmpListener($info, $options['peer_fingerprint']['pin-sha256'] ?? [], $onProgress, $handle));
  84. $request->setPushHandler(function ($request, $response) use ($options): Promise {
  85. return $this->handlePush($request, $response, $options);
  86. });
  87. ($request->hasHeader('content-length') ? new Success((int) $request->getHeader('content-length')) : $request->getBody()->getBodyLength())
  88. ->onResolve(static function ($e, $bodySize) use (&$info) {
  89. if (null !== $bodySize && 0 <= $bodySize) {
  90. $info['upload_content_length'] = ((1 + $info['upload_content_length']) ?? 1) - 1 + $bodySize;
  91. }
  92. });
  93. [$client, $connector] = $this->getClient($options);
  94. $response = $client->request($request, $cancellation);
  95. $response->onResolve(static function ($e) use ($connector, &$handle) {
  96. if (null === $e) {
  97. $handle = $connector->handle;
  98. }
  99. });
  100. return $response;
  101. }
  102. private function getClient(array $options): array
  103. {
  104. $options = [
  105. 'bindto' => $options['bindto'] ?: '0',
  106. 'verify_peer' => $options['verify_peer'],
  107. 'capath' => $options['capath'],
  108. 'cafile' => $options['cafile'],
  109. 'local_cert' => $options['local_cert'],
  110. 'local_pk' => $options['local_pk'],
  111. 'ciphers' => $options['ciphers'],
  112. 'capture_peer_cert_chain' => $options['capture_peer_cert_chain'] || $options['peer_fingerprint'],
  113. 'proxy' => $options['proxy'],
  114. ];
  115. $key = md5(serialize($options));
  116. if (isset($this->clients[$key])) {
  117. return $this->clients[$key];
  118. }
  119. $context = new ClientTlsContext('');
  120. $options['verify_peer'] || $context = $context->withoutPeerVerification();
  121. $options['cafile'] && $context = $context->withCaFile($options['cafile']);
  122. $options['capath'] && $context = $context->withCaPath($options['capath']);
  123. $options['local_cert'] && $context = $context->withCertificate(new Certificate($options['local_cert'], $options['local_pk']));
  124. $options['ciphers'] && $context = $context->withCiphers($options['ciphers']);
  125. $options['capture_peer_cert_chain'] && $context = $context->withPeerCapturing();
  126. $connector = $handleConnector = new class() implements Connector {
  127. public $connector;
  128. public $uri;
  129. public $handle;
  130. public function connect(string $uri, ?ConnectContext $context = null, ?CancellationToken $token = null): Promise
  131. {
  132. $result = $this->connector->connect($this->uri ?? $uri, $context, $token);
  133. $result->onResolve(function ($e, $socket) {
  134. $this->handle = null !== $socket ? $socket->getResource() : false;
  135. });
  136. return $result;
  137. }
  138. };
  139. $connector->connector = new DnsConnector(new AmpResolver($this->dnsCache));
  140. $context = (new ConnectContext())
  141. ->withTcpNoDelay()
  142. ->withTlsContext($context);
  143. if ($options['bindto']) {
  144. if (file_exists($options['bindto'])) {
  145. $connector->uri = 'unix://'.$options['bindto'];
  146. } else {
  147. $context = $context->withBindTo($options['bindto']);
  148. }
  149. }
  150. if ($options['proxy']) {
  151. $proxyUrl = parse_url($options['proxy']['url']);
  152. $proxySocket = new SocketAddress($proxyUrl['host'], $proxyUrl['port']);
  153. $proxyHeaders = $options['proxy']['auth'] ? ['Proxy-Authorization' => $options['proxy']['auth']] : [];
  154. if ('ssl' === $proxyUrl['scheme']) {
  155. $connector = new Https1TunnelConnector($proxySocket, $context->getTlsContext(), $proxyHeaders, $connector);
  156. } else {
  157. $connector = new Http1TunnelConnector($proxySocket, $proxyHeaders, $connector);
  158. }
  159. }
  160. $maxHostConnections = 0 < $this->maxHostConnections ? $this->maxHostConnections : \PHP_INT_MAX;
  161. $pool = new DefaultConnectionFactory($connector, $context);
  162. $pool = ConnectionLimitingPool::byAuthority($maxHostConnections, $pool);
  163. return $this->clients[$key] = [($this->clientConfigurator)(new PooledHttpClient($pool)), $handleConnector];
  164. }
  165. private function handlePush(Request $request, Promise $response, array $options): Promise
  166. {
  167. $deferred = new Deferred();
  168. $authority = $request->getUri()->getAuthority();
  169. if ($this->maxPendingPushes <= \count($this->pushedResponses[$authority] ?? [])) {
  170. $fifoUrl = key($this->pushedResponses[$authority]);
  171. unset($this->pushedResponses[$authority][$fifoUrl]);
  172. $this->logger && $this->logger->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
  173. }
  174. $url = (string) $request->getUri();
  175. $this->logger && $this->logger->debug(sprintf('Queueing pushed response: "%s"', $url));
  176. $this->pushedResponses[$authority][] = [$url, $deferred, $request, $response, [
  177. 'proxy' => $options['proxy'],
  178. 'bindto' => $options['bindto'],
  179. 'local_cert' => $options['local_cert'],
  180. 'local_pk' => $options['local_pk'],
  181. ]];
  182. return $deferred->promise();
  183. }
  184. }