Debian Codegraph @

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