AmpClientState.php 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  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. /**
  41. * @var mixed[]
  42. */
  43. public $dnsCache = [];
  44. /**
  45. * @var int
  46. */
  47. public $responseCount = 0;
  48. /**
  49. * @var mixed[]
  50. */
  51. public $pushedResponses = [];
  52. /**
  53. * @var mixed[]
  54. */
  55. private $clients = [];
  56. /**
  57. * @var \Closure
  58. */
  59. private $clientConfigurator;
  60. /**
  61. * @var int
  62. */
  63. private $maxHostConnections;
  64. /**
  65. * @var int
  66. */
  67. private $maxPendingPushes;
  68. /**
  69. * @var \Psr\Log\LoggerInterface|null
  70. */
  71. private $logger;
  72. /**
  73. * @param callable|null $clientConfigurator
  74. * @param int $maxHostConnections
  75. * @param int $maxPendingPushes
  76. * @param \Psr\Log\LoggerInterface|null $logger
  77. */
  78. public function __construct($clientConfigurator, $maxHostConnections, $maxPendingPushes, &$logger)
  79. {
  80. $clientConfigurator = $clientConfigurator ?? static function (PooledHttpClient $client) {
  81. return new InterceptedHttpClient($client, new RetryRequests(2));
  82. };
  83. $this->clientConfigurator = \Closure::fromCallable($clientConfigurator);
  84. $this->maxHostConnections = $maxHostConnections;
  85. $this->maxPendingPushes = $maxPendingPushes;
  86. $this->logger = &$logger;
  87. }
  88. /**
  89. * @return Promise<Response>
  90. * @param mixed[] $options
  91. * @param \Amp\Http\Client\Request $request
  92. * @param \Amp\CancellationToken $cancellation
  93. * @param mixed[] $info
  94. * @param \Closure $onProgress
  95. */
  96. public function request($options, $request, $cancellation, &$info, $onProgress, &$handle)
  97. {
  98. if ($options['proxy']) {
  99. if ($request->hasHeader('proxy-authorization')) {
  100. $options['proxy']['auth'] = $request->getHeader('proxy-authorization');
  101. }
  102. // Matching "no_proxy" should follow the behavior of curl
  103. $host = $request->getUri()->getHost();
  104. foreach ($options['proxy']['no_proxy'] as $rule) {
  105. $dotRule = '.'.ltrim($rule, '.');
  106. if ('*' === $rule || $host === $rule || substr_compare($host, $dotRule, -strlen($dotRule)) === 0) {
  107. $options['proxy'] = null;
  108. break;
  109. }
  110. }
  111. }
  112. $request = clone $request;
  113. if ($request->hasHeader('proxy-authorization')) {
  114. $request->removeHeader('proxy-authorization');
  115. }
  116. if ($options['capture_peer_cert_chain']) {
  117. $info['peer_certificate_chain'] = [];
  118. }
  119. $request->addEventListener(new AmpListener($info, $options['peer_fingerprint']['pin-sha256'] ?? [], $onProgress, $handle));
  120. $request->setPushHandler(function ($request, $response) use ($options) : Promise {
  121. return $this->handlePush($request, $response, $options);
  122. });
  123. ($request->hasHeader('content-length') ? new Success((int) $request->getHeader('content-length')) : $request->getBody()->getBodyLength())
  124. ->onResolve(static function ($e, $bodySize) use (&$info) {
  125. if (null !== $bodySize && 0 <= $bodySize) {
  126. $info['upload_content_length'] = ((1 + $info['upload_content_length']) ?? 1) - 1 + $bodySize;
  127. }
  128. });
  129. [$client, $connector] = $this->getClient($options);
  130. $response = $client->request($request, $cancellation);
  131. $response->onResolve(static function ($e) use ($connector, &$handle) {
  132. if (null === $e) {
  133. $handle = $connector->handle;
  134. }
  135. });
  136. return $response;
  137. }
  138. /**
  139. * @param mixed[] $options
  140. */
  141. private function getClient($options)
  142. {
  143. $options = [
  144. 'bindto' => $options['bindto'] ?: '0',
  145. 'verify_peer' => $options['verify_peer'],
  146. 'capath' => $options['capath'],
  147. 'cafile' => $options['cafile'],
  148. 'local_cert' => $options['local_cert'],
  149. 'local_pk' => $options['local_pk'],
  150. 'ciphers' => $options['ciphers'],
  151. 'capture_peer_cert_chain' => $options['capture_peer_cert_chain'] || $options['peer_fingerprint'],
  152. 'proxy' => $options['proxy'],
  153. 'crypto_method' => $options['crypto_method'],
  154. ];
  155. $key = hash('xxh128', serialize($options));
  156. if (isset($this->clients[$key])) {
  157. return $this->clients[$key];
  158. }
  159. $context = new ClientTlsContext('');
  160. $options['verify_peer'] || $context = $context->withoutPeerVerification();
  161. $options['cafile'] && $context = $context->withCaFile($options['cafile']);
  162. $options['capath'] && $context = $context->withCaPath($options['capath']);
  163. $options['local_cert'] && $context = $context->withCertificate(new Certificate($options['local_cert'], $options['local_pk']));
  164. $options['ciphers'] && $context = $context->withCiphers($options['ciphers']);
  165. $options['capture_peer_cert_chain'] && $context = $context->withPeerCapturing();
  166. $options['crypto_method'] && $context = $context->withMinimumVersion($options['crypto_method']);
  167. $connector = $handleConnector = new class() implements Connector {
  168. public $connector;
  169. public $uri;
  170. public $handle;
  171. public function connect(string $uri, ConnectContext $context = null, CancellationToken $token = null)
  172. {
  173. $result = $this->connector->connect($this->uri ?? $uri, $context, $token);
  174. $result->onResolve(function ($e, $socket) {
  175. $this->handle = null !== $socket ? $socket->getResource() : false;
  176. });
  177. return $result;
  178. }
  179. };
  180. $connector->connector = new DnsConnector(new AmpResolver($this->dnsCache));
  181. $context = (new ConnectContext())
  182. ->withTcpNoDelay()
  183. ->withTlsContext($context);
  184. if ($options['bindto']) {
  185. if (file_exists($options['bindto'])) {
  186. $connector->uri = 'unix://'.$options['bindto'];
  187. } else {
  188. $context = $context->withBindTo($options['bindto']);
  189. }
  190. }
  191. if ($options['proxy']) {
  192. $proxyUrl = parse_url($options['proxy']['url']);
  193. $proxySocket = new SocketAddress($proxyUrl['host'], $proxyUrl['port']);
  194. $proxyHeaders = $options['proxy']['auth'] ? ['Proxy-Authorization' => $options['proxy']['auth']] : [];
  195. if ('ssl' === $proxyUrl['scheme']) {
  196. $connector = new Https1TunnelConnector($proxySocket, $context->getTlsContext(), $proxyHeaders, $connector);
  197. } else {
  198. $connector = new Http1TunnelConnector($proxySocket, $proxyHeaders, $connector);
  199. }
  200. }
  201. $maxHostConnections = 0 < $this->maxHostConnections ? $this->maxHostConnections : \PHP_INT_MAX;
  202. $pool = new DefaultConnectionFactory($connector, $context);
  203. $pool = ConnectionLimitingPool::byAuthority($maxHostConnections, $pool);
  204. return $this->clients[$key] = [($this->clientConfigurator)(new PooledHttpClient($pool)), $handleConnector];
  205. }
  206. /**
  207. * @param \Amp\Http\Client\Request $request
  208. * @param \Amp\Promise $response
  209. * @param mixed[] $options
  210. */
  211. private function handlePush($request, $response, $options)
  212. {
  213. $deferred = new Deferred();
  214. $authority = $request->getUri()->getAuthority();
  215. if ($this->maxPendingPushes <= \count($this->pushedResponses[$authority] ?? [])) {
  216. $fifoUrl = key($this->pushedResponses[$authority]);
  217. unset($this->pushedResponses[$authority][$fifoUrl]);
  218. ($logger = $this->logger) ? $logger->debug(sprintf('Evicting oldest pushed response: "%s"', $fifoUrl)) : null;
  219. }
  220. $url = (string) $request->getUri();
  221. ($logger = $this->logger) ? $logger->debug(sprintf('Queueing pushed response: "%s"', $url)) : null;
  222. $this->pushedResponses[$authority][] = [$url, $deferred, $request, $response, [
  223. 'proxy' => $options['proxy'],
  224. 'bindto' => $options['bindto'],
  225. 'local_cert' => $options['local_cert'],
  226. 'local_pk' => $options['local_pk'],
  227. ]];
  228. return $deferred->promise();
  229. }
  230. }