Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/Internal/AmpClientStateV4.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\HttpClient\Internal;
13
14 use Amp\CancellationToken;
15 use Amp\Deferred;
16 use Amp\Http\Client\Connection\ConnectionLimitingPool;
17 use Amp\Http\Client\Connection\DefaultConnectionFactory;
18 use Amp\Http\Client\InterceptedHttpClient;
19 use Amp\Http\Client\Interceptor\RetryRequests;
20 use Amp\Http\Client\PooledHttpClient;
21 use Amp\Http\Client\Request;
22 use Amp\Http\Client\Response;
23 use Amp\Http\Tunnel\Http1TunnelConnector;
24 use Amp\Http\Tunnel\Https1TunnelConnector;
25 use Amp\Promise;
26 use Amp\Socket\Certificate;
27 use Amp\Socket\ClientTlsContext;
28 use Amp\Socket\ConnectContext;
29 use Amp\Socket\Connector;
30 use Amp\Socket\DnsConnector;
31 use Amp\Socket\SocketAddress;
32 use Amp\Success;
33 use Psr\Log\LoggerInterface;
34
35 /**
36 * Internal representation of the Amp client's state.
37 *
38 * @author Nicolas Grekas <[email protected]>
39 *
40 * @internal
41 */
42 final class AmpClientStateV4 extends ClientState
43 {
44 public array $dnsCache = [];
45 public int $responseCount = 0;
46 public array $pushedResponses = [];
47
48 private array $clients = [];
49 private \Closure $clientConfigurator;
50
51 public function __construct(
52 ?callable $clientConfigurator,
53 private int $maxHostConnections,
54 private int $maxPendingPushes,
55 private ?LoggerInterface &$logger,
56 ) {
57 $clientConfigurator ??= static fn (PooledHttpClient $client) => new InterceptedHttpClient($client, new RetryRequests(2));
58 $this->clientConfigurator = $clientConfigurator(...);
59 }
60
61 /**
62 * @return Promise<Response>
63 */
64 public function request(array $options, Request $request, CancellationToken $cancellation, array &$info, \Closure $onProgress, &$handle): Promise
65 {
66 if ($options['proxy']) {
67 if ($request->hasHeader('proxy-authorization')) {
68 $options['proxy']['auth'] = $request->getHeader('proxy-authorization');
69 }
70
71 // Matching "no_proxy" should follow the behavior of curl
72 $host = $request->getUri()->getHost();
73 foreach ($options['proxy']['no_proxy'] as $rule) {
74 $dotRule = '.'.ltrim($rule, '.');
75
76 if ('*' === $rule || $host === $rule || str_ends_with($host, $dotRule)) {
77 $options['proxy'] = null;
78 break;
79 }
80 }
81 }
82
83 $request = clone $request;
84
85 if ($request->hasHeader('proxy-authorization')) {
86 $request->removeHeader('proxy-authorization');
87 }
88
89 if ($options['capture_peer_cert_chain']) {
90 $info['peer_certificate_chain'] = [];
91 }
92
93 $request->addEventListener(new AmpListenerV4($info, $options['peer_fingerprint']['pin-sha256'] ?? [], $onProgress, $handle));
94 $request->setPushHandler(fn ($request, $response): Promise => $this->handlePush($request, $response, $options));
95
96 ($request->hasHeader('content-length') ? new Success((int) $request->getHeader('content-length')) : $request->getBody()->getBodyLength())
97 ->onResolve(static function ($e, $bodySize) use (&$info) {
98 if (null !== $bodySize && 0 <= $bodySize) {
99 $info['upload_content_length'] = ((1 + $info['upload_content_length']) ?? 1) - 1 + $bodySize;
100 }
101 });
102
103 [$client, $connector] = $this->getClient($options);
104 $response = $client->request($request, $cancellation);
105 $response->onResolve(static function ($e) use ($connector, &$handle) {
106 if (null === $e) {
107 $handle = $connector->handle;
108 }
109 });
110
111 return $response;
112 }
113
114 private function getClient(array $options): array
115 {
116 $options = [
117 'bindto' => $options['bindto'] ?: '0',
118 'verify_peer' => $options['verify_peer'],
119 'capath' => $options['capath'],
120 'cafile' => $options['cafile'],
121 'local_cert' => $options['local_cert'],
122 'local_pk' => $options['local_pk'],
123 'ciphers' => $options['ciphers'],
124 'capture_peer_cert_chain' => $options['capture_peer_cert_chain'] || $options['peer_fingerprint'],
125 'proxy' => $options['proxy'],
126 'crypto_method' => $options['crypto_method'],
127 ];
128
129 $key = hash('xxh128', serialize($options));
130
131 if (isset($this->clients[$key])) {
132 return $this->clients[$key];
133 }
134
135 $context = new ClientTlsContext('');
136 $options['verify_peer'] || $context = $context->withoutPeerVerification();
137 $options['cafile'] && $context = $context->withCaFile($options['cafile']);
138 $options['capath'] && $context = $context->withCaPath($options['capath']);
139 $options['local_cert'] && $context = $context->withCertificate(new Certificate($options['local_cert'], $options['local_pk']));
140 $options['ciphers'] && $context = $context->withCiphers($options['ciphers']);
141 $options['capture_peer_cert_chain'] && $context = $context->withPeerCapturing();
142 $options['crypto_method'] && $context = $context->withMinimumVersion($options['crypto_method']);
143
144 $connector = $handleConnector = new class implements Connector {
145 public DnsConnector $connector;
146 public string $uri;
147 /** @var resource|null */
148 public $handle;
149
150 public function connect(string $uri, ?ConnectContext $context = null, ?CancellationToken $token = null): Promise
151 {
152 $result = $this->connector->connect($this->uri ?? $uri, $context, $token);
153 $result->onResolve(function ($e, $socket) {
154 $this->handle = $socket?->getResource();
155 });
156
157 return $result;
158 }
159 };
160 $connector->connector = new DnsConnector(new AmpResolverV4($this->dnsCache));
161
162 $context = (new ConnectContext())
163 ->withTcpNoDelay()
164 ->withTlsContext($context);
165
166 if ($options['bindto']) {
167 if (file_exists($options['bindto'])) {
168 $connector->uri = 'unix://'.$options['bindto'];
169 } else {
170 $context = $context->withBindTo($options['bindto']);
171 }
172 }
173
174 if ($options['proxy']) {
175 $proxyUrl = parse_url($options['proxy']['url']);
176 $proxySocket = new SocketAddress($proxyUrl['host'], $proxyUrl['port']);
177 $proxyHeaders = $options['proxy']['auth'] ? ['Proxy-Authorization' => $options['proxy']['auth']] : [];
178
179 if ('ssl' === $proxyUrl['scheme']) {
180 $connector = new Https1TunnelConnector($proxySocket, $context->getTlsContext(), $proxyHeaders, $connector);
181 } else {
182 $connector = new Http1TunnelConnector($proxySocket, $proxyHeaders, $connector);
183 }
184 }
185
186 $maxHostConnections = 0 < $this->maxHostConnections ? $this->maxHostConnections : \PHP_INT_MAX;
187 $pool = new DefaultConnectionFactory($connector, $context);
188 $pool = ConnectionLimitingPool::byAuthority($maxHostConnections, $pool);
189
190 return $this->clients[$key] = [($this->clientConfigurator)(new PooledHttpClient($pool)), $handleConnector];
191 }
192
193 private function handlePush(Request $request, Promise $response, array $options): Promise
194 {
195 $deferred = new Deferred();
196 $authority = $request->getUri()->getAuthority();
197
198 if ($this->maxPendingPushes <= \count($this->pushedResponses[$authority] ?? [])) {
199 $fifoUrl = key($this->pushedResponses[$authority]);
200 unset($this->pushedResponses[$authority][$fifoUrl]);
201 $this->logger?->debug(\sprintf('Evicting oldest pushed response: "%s"', $fifoUrl));
202 }
203
204 $url = (string) $request->getUri();
205 $this->logger?->debug(\sprintf('Queueing pushed response: "%s"', $url));
206 $this->pushedResponses[$authority][] = [$url, $deferred, $request, $response, [
207 'proxy' => $options['proxy'],
208 'bindto' => $options['bindto'],
209 'local_cert' => $options['local_cert'],
210 'local_pk' => $options['local_pk'],
211 ]];
212
213 return $deferred->promise();
214 }
215 }