Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/NativeHttpClient.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;
13
14 use Psr\Log\LoggerAwareInterface;
15 use Psr\Log\LoggerAwareTrait;
16 use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
17 use Symfony\Component\HttpClient\Exception\TransportException;
18 use Symfony\Component\HttpClient\Internal\NativeClientState;
19 use Symfony\Component\HttpClient\Response\NativeResponse;
20 use Symfony\Component\HttpClient\Response\ResponseStream;
21 use Symfony\Contracts\HttpClient\HttpClientInterface;
22 use Symfony\Contracts\HttpClient\ResponseInterface;
23 use Symfony\Contracts\HttpClient\ResponseStreamInterface;
24 use Symfony\Contracts\Service\ResetInterface;
25
26 /**
27 * A portable implementation of the HttpClientInterface contracts based on PHP stream wrappers.
28 *
29 * PHP stream wrappers are able to fetch response bodies concurrently,
30 * but each request is opened synchronously.
31 *
32 * @author Nicolas Grekas <[email protected]>
33 */
34 final class NativeHttpClient implements HttpClientInterface, LoggerAwareInterface, ResetInterface
35 {
36 use HttpClientTrait;
37 use LoggerAwareTrait;
38
39 public const OPTIONS_DEFAULTS = HttpClientInterface::OPTIONS_DEFAULTS + [
40 'crypto_method' => \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT,
41 ];
42
43 private array $defaultOptions = self::OPTIONS_DEFAULTS;
44 private static array $emptyDefaults = self::OPTIONS_DEFAULTS;
45
46 private NativeClientState $multi;
47
48 /**
49 * @param array $defaultOptions Default request's options
50 * @param int $maxHostConnections The maximum number of connections to open
51 *
52 * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
53 */
54 public function __construct(array $defaultOptions = [], int $maxHostConnections = 6)
55 {
56 $this->defaultOptions['buffer'] ??= self::shouldBuffer(...);
57
58 if ($defaultOptions) {
59 [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
60 }
61
62 $this->multi = new NativeClientState();
63 $this->multi->maxHostConnections = 0 < $maxHostConnections ? $maxHostConnections : \PHP_INT_MAX;
64 }
65
66 /**
67 * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
68 */
69 public function request(string $method, string $url, array $options = []): ResponseInterface
70 {
71 [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
72
73 if ($options['bindto']) {
74 if (file_exists($options['bindto'])) {
75 throw new TransportException(__CLASS__.' cannot bind to local Unix sockets, use e.g. CurlHttpClient instead.');
76 }
77 if (str_starts_with($options['bindto'], 'if!')) {
78 throw new TransportException(__CLASS__.' cannot bind to network interfaces, use e.g. CurlHttpClient instead.');
79 }
80 if (str_starts_with($options['bindto'], 'host!')) {
81 $options['bindto'] = substr($options['bindto'], 5);
82 }
83 if ((\PHP_VERSION_ID < 80223 || 80300 <= \PHP_VERSION_ID && 80311 < \PHP_VERSION_ID) && '\\' === \DIRECTORY_SEPARATOR && '[' === $options['bindto'][0]) {
84 $options['bindto'] = preg_replace('{^\[[^\]]++\]}', '[$0]', $options['bindto']);
85 }
86 }
87
88 $hasContentLength = isset($options['normalized_headers']['content-length']);
89 $hasBody = '' !== $options['body'] || 'POST' === $method || $hasContentLength;
90
91 $options['body'] = self::getBodyAsString($options['body']);
92
93 if ('chunked' === substr($options['normalized_headers']['transfer-encoding'][0] ?? '', \strlen('Transfer-Encoding: '))) {
94 unset($options['normalized_headers']['transfer-encoding']);
95 $options['headers'] = array_merge(...array_values($options['normalized_headers']));
96 $options['body'] = self::dechunk($options['body']);
97 }
98 if ('' === $options['body'] && $hasBody && !$hasContentLength) {
99 $options['headers'][] = 'Content-Length: 0';
100 }
101 if ($hasBody && !isset($options['normalized_headers']['content-type'])) {
102 $options['headers'][] = 'Content-Type: application/x-www-form-urlencoded';
103 }
104
105 if (\extension_loaded('zlib') && !isset($options['normalized_headers']['accept-encoding'])) {
106 // gzip is the most widely available algo, no need to deal with deflate
107 $options['headers'][] = 'Accept-Encoding: gzip';
108 }
109
110 if ($options['peer_fingerprint']) {
111 if (isset($options['peer_fingerprint']['pin-sha256']) && 1 === \count($options['peer_fingerprint'])) {
112 throw new TransportException(__CLASS__.' cannot verify "pin-sha256" fingerprints, please provide a "sha256" one.');
113 }
114
115 unset($options['peer_fingerprint']['pin-sha256']);
116 }
117
118 $info = [
119 'response_headers' => [],
120 'url' => $url,
121 'error' => null,
122 'canceled' => false,
123 'http_method' => $method,
124 'http_code' => 0,
125 'redirect_count' => 0,
126 'start_time' => 0.0,
127 'connect_time' => 0.0,
128 'redirect_time' => 0.0,
129 'pretransfer_time' => 0.0,
130 'starttransfer_time' => 0.0,
131 'total_time' => 0.0,
132 'namelookup_time' => 0.0,
133 'size_upload' => 0,
134 'size_download' => 0,
135 'size_body' => \strlen($options['body']),
136 'primary_ip' => '',
137 'primary_port' => 'http:' === $url['scheme'] ? 80 : 443,
138 'debug' => \extension_loaded('curl') ? '' : "* Enable the curl extension for better performance\n",
139 ];
140
141 if ($onProgress = $options['on_progress']) {
142 $maxDuration = 0 < $options['max_duration'] ? $options['max_duration'] : \INF;
143 $onProgress = static function (...$progress) use ($onProgress, &$info, $maxDuration) {
144 if ($info['total_time'] >= $maxDuration) {
145 throw new TransportException(\sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
146 }
147
148 $progressInfo = $info;
149 $progressInfo['url'] = implode('', $info['url']);
150 unset($progressInfo['size_body']);
151
152 // Memoize the last progress to ease calling the callback periodically when no network transfer happens
153 static $lastProgress = [0, 0];
154
155 if ($progress && -1 === $progress[0]) {
156 // Response completed
157 $lastProgress[0] = max($lastProgress);
158 } else {
159 $lastProgress = $progress ?: $lastProgress;
160 }
161
162 $onProgress($lastProgress[0], $lastProgress[1], $progressInfo);
163 };
164 } elseif (0 < $options['max_duration']) {
165 $maxDuration = $options['max_duration'];
166 $onProgress = static function () use (&$info, $maxDuration): void {
167 if ($info['total_time'] >= $maxDuration) {
168 throw new TransportException(\sprintf('Max duration was reached for "%s".', implode('', $info['url'])));
169 }
170 };
171 }
172
173 // Always register a notification callback to compute live stats about the response
174 $notification = static function (int $code, int $severity, ?string $msg, int $msgCode, int $dlNow, int $dlSize) use ($onProgress, &$info) {
175 $info['total_time'] = microtime(true) - $info['start_time'];
176
177 if (\STREAM_NOTIFY_PROGRESS === $code) {
178 $info['starttransfer_time'] = $info['starttransfer_time'] ?: $info['total_time'];
179 $info['size_upload'] += $dlNow ? 0 : $info['size_body'];
180 $info['size_download'] = $dlNow;
181 } elseif (\STREAM_NOTIFY_CONNECT === $code) {
182 $info['connect_time'] = $info['total_time'];
183 $info['debug'] .= $info['request_header'];
184 unset($info['request_header']);
185 } else {
186 return;
187 }
188
189 if ($onProgress) {
190 $onProgress($dlNow, $dlSize);
191 }
192 };
193
194 if ($options['resolve']) {
195 $this->multi->dnsCache = $options['resolve'] + $this->multi->dnsCache;
196 }
197
198 $this->logger?->info(\sprintf('Request: "%s %s"', $method, implode('', $url)));
199
200 if (!isset($options['normalized_headers']['user-agent'])) {
201 $options['headers'][] = 'User-Agent: Symfony HttpClient (Native)';
202 }
203
204 if (0 < $options['max_duration']) {
205 $options['timeout'] = min($options['max_duration'], $options['timeout']);
206 }
207 if (\PHP_INT_SIZE === 4 && 2147 < $options['timeout']) {
208 $options['timeout'] = 2147; // fopen() on x86 doesn't support longer timeouts
209 }
210
211 switch ($cryptoMethod = $options['crypto_method']) {
212 case \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT:
213 $cryptoMethod |= \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
214 // no break
215 case \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT:
216 $cryptoMethod |= \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
217 // no break
218 case \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT:
219 $cryptoMethod |= \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT;
220 }
221
222 $context = [
223 'http' => [
224 'protocol_version' => min($options['http_version'] ?: '1.1', '1.1'),
225 'method' => $method,
226 'content' => $options['body'],
227 'ignore_errors' => true,
228 'curl_verify_ssl_peer' => $options['verify_peer'],
229 'curl_verify_ssl_host' => $options['verify_host'],
230 'auto_decode' => false, // Disable dechunk filter, it's incompatible with stream_select()
231 'timeout' => $options['timeout'],
232 'follow_location' => false, // We follow redirects ourselves - the native logic is too limited
233 ],
234 'ssl' => array_filter([
235 'verify_peer' => $options['verify_peer'],
236 'verify_peer_name' => $options['verify_host'],
237 'cafile' => $options['cafile'],
238 'capath' => $options['capath'],
239 'local_cert' => $options['local_cert'],
240 'local_pk' => $options['local_pk'],
241 'passphrase' => $options['passphrase'],
242 'ciphers' => $options['ciphers'],
243 'peer_fingerprint' => $options['peer_fingerprint'],
244 'capture_peer_cert_chain' => $options['capture_peer_cert_chain'],
245 'allow_self_signed' => (bool) $options['peer_fingerprint'],
246 'SNI_enabled' => true,
247 'disable_compression' => true,
248 'crypto_method' => $cryptoMethod,
249 ], static fn ($v) => null !== $v),
250 'socket' => [
251 'bindto' => $options['bindto'],
252 'tcp_nodelay' => true,
253 ],
254 ];
255
256 $context = stream_context_create($context, ['notification' => $notification]);
257
258 $resolver = static function ($multi) use ($context, $options, $url, &$info, $onProgress) {
259 $authority = $url['authority'];
260 [$host, $port] = self::parseHostPort($url, $info);
261
262 if (!isset($options['normalized_headers']['host'])) {
263 $options['headers'][] = 'Host: '.$host.$port;
264 }
265
266 $proxy = self::getProxy($options['proxy'], $url, $options['no_proxy']);
267
268 if (!self::configureHeadersAndProxy($context, $host, $options['headers'], $proxy, 'https:' === $url['scheme'])) {
269 $ip = self::dnsResolve($host, $multi, $info, $onProgress);
270 $url['authority'] = substr_replace($url['authority'], $ip, -\strlen($host) - \strlen($port), \strlen($host));
271 }
272
273 return [self::createRedirectResolver($options, $authority, $proxy, $info, $onProgress), implode('', $url)];
274 };
275
276 return new NativeResponse($this->multi, $context, implode('', $url), $options, $info, $resolver, $onProgress, $this->logger);
277 }
278
279 public function stream(ResponseInterface|iterable $responses, ?float $timeout = null): ResponseStreamInterface
280 {
281 if ($responses instanceof NativeResponse) {
282 $responses = [$responses];
283 }
284
285 return new ResponseStream(NativeResponse::stream($responses, $timeout));
286 }
287
288 public function reset(): void
289 {
290 $this->multi->reset();
291 }
292
293 private static function getBodyAsString($body): string
294 {
295 if (\is_resource($body)) {
296 return stream_get_contents($body);
297 }
298
299 if (!$body instanceof \Closure) {
300 return $body;
301 }
302
303 $result = '';
304
305 while ('' !== $data = $body(self::$CHUNK_SIZE)) {
306 if (!\is_string($data)) {
307 throw new TransportException(\sprintf('Return value of the "body" option callback must be string, "%s" returned.', get_debug_type($data)));
308 }
309
310 $result .= $data;
311 }
312
313 return $result;
314 }
315
316 /**
317 * Extracts the host and the port from the URL.
318 */
319 private static function parseHostPort(array $url, array &$info): array
320 {
321 if ($port = parse_url($url['authority'], \PHP_URL_PORT) ?: '') {
322 $info['primary_port'] = $port;
323 $port = ':'.$port;
324 } else {
325 $info['primary_port'] = 'http:' === $url['scheme'] ? 80 : 443;
326 }
327
328 return [parse_url($url['authority'], \PHP_URL_HOST), $port];
329 }
330
331 /**
332 * Resolves the IP of the host using the local DNS cache if possible.
333 */
334 private static function dnsResolve(string $host, NativeClientState $multi, array &$info, ?\Closure $onProgress): string
335 {
336 $flag = '' !== $host && '[' === $host[0] && ']' === $host[-1] && str_contains($host, ':') ? \FILTER_FLAG_IPV6 : \FILTER_FLAG_IPV4;
337 $ip = \FILTER_FLAG_IPV6 === $flag ? substr($host, 1, -1) : $host;
338 $now = microtime(true);
339
340 if (filter_var($ip, \FILTER_VALIDATE_IP, $flag)) {
341 // The host is already an IP address
342 } elseif (null === $ip = $multi->dnsCache[$host] ?? null) {
343 $info['debug'] .= "* Hostname was NOT found in DNS cache\n";
344
345 if ($ip = gethostbynamel($host)) {
346 $ip = $ip[0];
347 } elseif (!\defined('STREAM_PF_INET6')) {
348 throw new TransportException(\sprintf('Could not resolve host "%s".', $host));
349 } elseif ($ip = dns_get_record($host, \DNS_AAAA)) {
350 $ip = $ip[0]['ipv6'];
351 } elseif (\extension_loaded('sockets')) {
352 if (!$addrInfo = socket_addrinfo_lookup($host, 0, ['ai_socktype' => \SOCK_STREAM, 'ai_family' => \AF_INET6])) {
353 throw new TransportException(\sprintf('Could not resolve host "%s".', $host));
354 }
355
356 $ip = socket_addrinfo_explain($addrInfo[0])['ai_addr']['sin6_addr'];
357 } elseif ('localhost' === $host || 'localhost.' === $host) {
358 $ip = '::1';
359 } else {
360 throw new TransportException(\sprintf('Could not resolve host "%s".', $host));
361 }
362
363 $multi->dnsCache[$host] = $ip;
364 $info['debug'] .= "* Added {$host}:0:{$ip} to DNS cache\n";
365 } else {
366 $info['debug'] .= "* Hostname was found in DNS cache\n";
367 }
368
369 $host = str_contains($ip, ':') ? "[$ip]" : $ip;
370 $info['namelookup_time'] = microtime(true) - ($info['start_time'] ?: $now);
371 $info['primary_ip'] = $ip;
372
373 if ($onProgress) {
374 // Notify DNS resolution
375 $onProgress();
376 }
377
378 return $host;
379 }
380
381 /**
382 * Handles redirects - the native logic is too buggy to be used.
383 */
384 private static function createRedirectResolver(array $options, string $authority, ?array $proxy, array &$info, ?\Closure $onProgress): \Closure
385 {
386 $redirectHeaders = [];
387 if (0 < $maxRedirects = $options['max_redirects']) {
388 $redirectHeaders = ['authority' => $authority];
389 $redirectHeaders['with_auth'] = $redirectHeaders['no_auth'] = array_filter($options['headers'], static fn ($h) => 0 !== stripos($h, 'Host:'));
390
391 if (isset($options['normalized_headers']['authorization']) || isset($options['normalized_headers']['cookie'])) {
392 $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], static fn ($h) => 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:'));
393 }
394 }
395
396 return static function (NativeClientState $multi, ?string $location, $context) use (&$redirectHeaders, $proxy, &$info, $maxRedirects, $onProgress): ?string {
397 if (null === $location || $info['http_code'] < 300 || 400 <= $info['http_code']) {
398 $info['redirect_url'] = null;
399
400 return null;
401 }
402
403 try {
404 $url = self::parseUrl($location);
405 $locationHasHost = isset($url['authority']);
406 $url = self::resolveUrl($url, $info['url']);
407 } catch (InvalidArgumentException) {
408 $info['redirect_url'] = null;
409
410 return null;
411 }
412
413 $info['redirect_url'] = implode('', $url);
414
415 if ($info['redirect_count'] >= $maxRedirects) {
416 return null;
417 }
418
419 $info['url'] = $url;
420 ++$info['redirect_count'];
421 $info['redirect_time'] = microtime(true) - $info['start_time'];
422
423 // Do like curl and browsers: turn POST to GET on 301, 302 and 303
424 if (\in_array($info['http_code'], [301, 302, 303], true)) {
425 $options = stream_context_get_options($context)['http'];
426
427 if ('POST' === $options['method'] || 303 === $info['http_code']) {
428 $info['http_method'] = $options['method'] = 'HEAD' === $options['method'] ? 'HEAD' : 'GET';
429 $options['content'] = '';
430 $filterContentHeaders = static fn ($h) => 0 !== stripos($h, 'Content-Length:') && 0 !== stripos($h, 'Content-Type:') && 0 !== stripos($h, 'Transfer-Encoding:');
431 $options['header'] = array_filter($options['header'], $filterContentHeaders);
432 $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], $filterContentHeaders);
433 $redirectHeaders['with_auth'] = array_filter($redirectHeaders['with_auth'], $filterContentHeaders);
434
435 if (\PHP_VERSION_ID >= 80300) {
436 stream_context_set_options($context, ['http' => $options]);
437 } else {
438 stream_context_set_option($context, ['http' => $options]);
439 }
440 }
441 }
442
443 [$host, $port] = self::parseHostPort($url, $info);
444
445 if ($locationHasHost) {
446 // Authorization and Cookie headers MUST NOT follow except for the initial authority name
447 $requestHeaders = $redirectHeaders['authority'] === $url['authority'] ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth'];
448 $requestHeaders[] = 'Host: '.$host.$port;
449 $dnsResolve = !self::configureHeadersAndProxy($context, $host, $requestHeaders, $proxy, 'https:' === $url['scheme']);
450 } else {
451 $dnsResolve = isset(stream_context_get_options($context)['ssl']['peer_name']);
452 }
453
454 if ($dnsResolve) {
455 $ip = self::dnsResolve($host, $multi, $info, $onProgress);
456 $url['authority'] = substr_replace($url['authority'], $ip, -\strlen($host) - \strlen($port), \strlen($host));
457 }
458
459 return implode('', $url);
460 };
461 }
462
463 private static function configureHeadersAndProxy($context, string $host, array $requestHeaders, ?array $proxy, bool $isSsl): bool
464 {
465 if (null === $proxy) {
466 stream_context_set_option($context, 'http', 'header', $requestHeaders);
467 stream_context_set_option($context, 'ssl', 'peer_name', $host);
468
469 return false;
470 }
471
472 // Matching "no_proxy" should follow the behavior of curl
473
474 foreach ($proxy['no_proxy'] as $rule) {
475 $dotRule = '.'.ltrim($rule, '.');
476
477 if ('*' === $rule || $host === $rule || str_ends_with($host, $dotRule)) {
478 stream_context_set_option($context, 'http', 'proxy', null);
479 stream_context_set_option($context, 'http', 'request_fulluri', false);
480 stream_context_set_option($context, 'http', 'header', $requestHeaders);
481 stream_context_set_option($context, 'ssl', 'peer_name', $host);
482
483 return false;
484 }
485 }
486
487 if (null !== $proxy['auth']) {
488 $requestHeaders[] = 'Proxy-Authorization: '.$proxy['auth'];
489 }
490
491 stream_context_set_option($context, 'http', 'proxy', $proxy['url']);
492 stream_context_set_option($context, 'http', 'request_fulluri', !$isSsl);
493 stream_context_set_option($context, 'http', 'header', $requestHeaders);
494 stream_context_set_option($context, 'ssl', 'peer_name', null);
495
496 return true;
497 }
498 }