Debian Codegraph @

lib/3rdParty/composer/symfony/http-client/CurlHttpClient.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\LoggerInterface;
16 use Symfony\Component\HttpClient\Exception\InvalidArgumentException;
17 use Symfony\Component\HttpClient\Exception\TransportException;
18 use Symfony\Component\HttpClient\Internal\CurlClientState;
19 use Symfony\Component\HttpClient\Internal\PushedResponse;
20 use Symfony\Component\HttpClient\Response\CurlResponse;
21 use Symfony\Component\HttpClient\Response\ResponseStream;
22 use Symfony\Contracts\HttpClient\HttpClientInterface;
23 use Symfony\Contracts\HttpClient\ResponseInterface;
24 use Symfony\Contracts\HttpClient\ResponseStreamInterface;
25 use Symfony\Contracts\Service\ResetInterface;
26
27 /**
28 * A performant implementation of the HttpClientInterface contracts based on the curl extension.
29 *
30 * This provides fully concurrent HTTP requests, with transparent
31 * HTTP/2 push when a curl version that supports it is installed.
32 *
33 * @author Nicolas Grekas <[email protected]>
34 */
35 final class CurlHttpClient implements HttpClientInterface, LoggerAwareInterface, ResetInterface
36 {
37 use HttpClientTrait;
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 'auth_ntlm' => null, // array|string - an array containing the username as first value, and optionally the
45 // password as the second one; or string like username:password - enabling NTLM auth
46 'extra' => [
47 'curl' => [], // A list of extra curl options indexed by their corresponding CURLOPT_*
48 ],
49 ];
50 private static array $emptyDefaults = self::OPTIONS_DEFAULTS + ['auth_ntlm' => null];
51
52 private ?LoggerInterface $logger = null;
53
54 /**
55 * An internal object to share state between the client and its responses.
56 */
57 private CurlClientState $multi;
58
59 /**
60 * @param array $defaultOptions Default request's options
61 * @param int $maxHostConnections The maximum number of connections to a single host
62 * @param int $maxPendingPushes The maximum number of pushed responses to accept in the queue
63 *
64 * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
65 */
66 public function __construct(array $defaultOptions = [], int $maxHostConnections = 6, int $maxPendingPushes = 0)
67 {
68 if (!\extension_loaded('curl')) {
69 throw new \LogicException('You cannot use the "Symfony\Component\HttpClient\CurlHttpClient" as the "curl" extension is not installed.');
70 }
71
72 $this->defaultOptions['buffer'] ??= self::shouldBuffer(...);
73
74 if ($defaultOptions) {
75 [, $this->defaultOptions] = self::prepareRequest(null, null, $defaultOptions, $this->defaultOptions);
76 }
77
78 $this->multi = new CurlClientState($maxHostConnections, $maxPendingPushes);
79 }
80
81 public function setLogger(LoggerInterface $logger): void
82 {
83 $this->logger = $this->multi->logger = $logger;
84 }
85
86 /**
87 * @see HttpClientInterface::OPTIONS_DEFAULTS for available options
88 */
89 public function request(string $method, string $url, array $options = []): ResponseInterface
90 {
91 [$url, $options] = self::prepareRequest($method, $url, $options, $this->defaultOptions);
92 $scheme = $url['scheme'];
93 $authority = $url['authority'];
94 $host = parse_url($authority, \PHP_URL_HOST);
95 $port = parse_url($authority, \PHP_URL_PORT) ?: ('http:' === $scheme ? 80 : 443);
96 $proxy = self::getProxyUrl($options['proxy'], $url);
97 $url = implode('', $url);
98
99 if (!isset($options['normalized_headers']['user-agent'])) {
100 $options['headers'][] = 'User-Agent: Symfony HttpClient (Curl)';
101 }
102
103 $curlopts = [
104 \CURLOPT_URL => $url,
105 \CURLOPT_TCP_NODELAY => true,
106 \CURLOPT_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS,
107 \CURLOPT_REDIR_PROTOCOLS => \CURLPROTO_HTTP | \CURLPROTO_HTTPS,
108 \CURLOPT_FOLLOWLOCATION => true,
109 \CURLOPT_MAXREDIRS => max(0, $options['max_redirects']),
110 \CURLOPT_COOKIEFILE => '', // Keep track of cookies during redirects
111 \CURLOPT_TIMEOUT => 0,
112 \CURLOPT_PROXY => $proxy,
113 \CURLOPT_NOPROXY => $options['no_proxy'] ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '',
114 \CURLOPT_SSL_VERIFYPEER => $options['verify_peer'],
115 \CURLOPT_SSL_VERIFYHOST => $options['verify_host'] ? 2 : 0,
116 \CURLOPT_CAINFO => $options['cafile'],
117 \CURLOPT_CAPATH => $options['capath'],
118 \CURLOPT_SSL_CIPHER_LIST => $options['ciphers'],
119 \CURLOPT_SSLCERT => $options['local_cert'],
120 \CURLOPT_SSLKEY => $options['local_pk'],
121 \CURLOPT_KEYPASSWD => $options['passphrase'],
122 \CURLOPT_CERTINFO => $options['capture_peer_cert_chain'],
123 \CURLOPT_SSLVERSION => match ($options['crypto_method']) {
124 \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT => \CURL_SSLVERSION_TLSv1_3,
125 \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT => \CURL_SSLVERSION_TLSv1_2,
126 \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT => \CURL_SSLVERSION_TLSv1_1,
127 \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT => \CURL_SSLVERSION_TLSv1_0,
128 },
129 ];
130
131 if (1.0 === (float) $options['http_version']) {
132 $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
133 } elseif (1.1 === (float) $options['http_version']) {
134 $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
135 } elseif (\defined('CURL_VERSION_HTTP2') && (\CURL_VERSION_HTTP2 & CurlClientState::$curlVersion['features']) && ('https:' === $scheme || 2.0 === (float) $options['http_version'])) {
136 $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
137 } elseif (\defined('CURL_VERSION_HTTP3') && (\CURL_VERSION_HTTP3 & CurlClientState::$curlVersion['features']) && 3.0 === (float) $options['http_version'] && !self::willUseProxy($proxy, $curlopts[\CURLOPT_NOPROXY], $host)) {
138 $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_3;
139 }
140
141 $ntlmOriginKey = null;
142 if (isset($options['auth_ntlm'])) {
143 $curlopts[\CURLOPT_HTTPAUTH] = \CURLAUTH_NTLM;
144 $curlopts[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
145
146 if (\is_array($options['auth_ntlm'])) {
147 $count = \count($options['auth_ntlm']);
148 if ($count <= 0 || $count > 2) {
149 throw new InvalidArgumentException(\sprintf('Option "auth_ntlm" must contain 1 or 2 elements, %d given.', $count));
150 }
151
152 $options['auth_ntlm'] = implode(':', $options['auth_ntlm']);
153 }
154
155 if (!\is_string($options['auth_ntlm'])) {
156 throw new InvalidArgumentException(\sprintf('Option "auth_ntlm" must be a string or an array, "%s" given.', get_debug_type($options['auth_ntlm'])));
157 }
158
159 $curlopts[\CURLOPT_USERPWD] = $options['auth_ntlm'];
160
161 $ntlmOriginKey = CurlClientState::originKey($scheme, $host, $port);
162
163 if (isset($this->multi->ntlmRequiresFreshConnection[$ntlmOriginKey])) {
164 $curlopts[\CURLOPT_FRESH_CONNECT] = true;
165 $curlopts[\CURLOPT_FORBID_REUSE] = true;
166 }
167 }
168
169 if (!\ZEND_THREAD_SAFE) {
170 $curlopts[\CURLOPT_DNS_USE_GLOBAL_CACHE] = false;
171 }
172
173 if (\defined('CURLOPT_HEADEROPT') && \defined('CURLHEADER_SEPARATE')) {
174 $curlopts[\CURLOPT_HEADEROPT] = \CURLHEADER_SEPARATE;
175 }
176
177 // curl's resolve feature varies by host:port but ours varies by host only, let's handle this with our own DNS map
178 if (isset($this->multi->dnsCache->hostnames[$host])) {
179 $options['resolve'] += [$host => $this->multi->dnsCache->hostnames[$host]];
180 }
181
182 if ($options['resolve'] || $this->multi->dnsCache->evictions) {
183 // First reset any old DNS cache entries then add the new ones
184 $resolve = $this->multi->dnsCache->evictions;
185 $this->multi->dnsCache->evictions = [];
186
187 if ($resolve && 0x072A00 > CurlClientState::$curlVersion['version_number']) {
188 // DNS cache removals require curl 7.42 or higher
189 $this->multi->reset();
190 }
191
192 foreach ($options['resolve'] as $resolveHost => $ip) {
193 $resolve[] = null === $ip ? "-$resolveHost:$port" : "$resolveHost:$port:$ip";
194 $this->multi->dnsCache->hostnames[$resolveHost] = $ip;
195 $this->multi->dnsCache->removals["-$resolveHost:$port"] = "-$resolveHost:$port";
196 }
197
198 $curlopts[\CURLOPT_RESOLVE] = $resolve;
199 }
200
201 $curlopts[\CURLOPT_CUSTOMREQUEST] = $method;
202 if ('POST' === $method) {
203 // Use CURLOPT_POST to have browser-like POST-to-GET redirects for 301, 302 and 303
204 $curlopts[\CURLOPT_POST] = true;
205 } elseif ('HEAD' === $method) {
206 $curlopts[\CURLOPT_NOBODY] = true;
207 }
208
209 if ('\\' !== \DIRECTORY_SEPARATOR && $options['timeout'] < 1) {
210 $curlopts[\CURLOPT_NOSIGNAL] = true;
211 }
212
213 if (\extension_loaded('zlib') && !isset($options['normalized_headers']['accept-encoding'])) {
214 $options['headers'][] = 'Accept-Encoding: gzip'; // Expose only one encoding, some servers mess up when more are provided
215 }
216 $body = $options['body'];
217
218 foreach ($options['headers'] as $i => $header) {
219 if (\is_string($body) && '' !== $body && 0 === stripos($header, 'Content-Length: ')) {
220 // Let curl handle Content-Length headers
221 unset($options['headers'][$i]);
222 continue;
223 }
224 if (':' === $header[-2] && \strlen($header) - 2 === strpos($header, ': ')) {
225 // curl requires a special syntax to send empty headers
226 $curlopts[\CURLOPT_HTTPHEADER][] = substr_replace($header, ';', -2);
227 } else {
228 $curlopts[\CURLOPT_HTTPHEADER][] = $header;
229 }
230 }
231
232 // Prevent curl from sending its default Accept and Expect headers
233 foreach (['accept', 'expect'] as $header) {
234 if (!isset($options['normalized_headers'][$header][0])) {
235 $curlopts[\CURLOPT_HTTPHEADER][] = $header.':';
236 }
237 }
238
239 if (!\is_string($body)) {
240 if (isset($options['auth_ntlm'])) {
241 $curlopts[\CURLOPT_FORBID_REUSE] = true; // Reusing NTLM connections requires seeking capability, which only string bodies support
242 }
243
244 if (\is_resource($body)) {
245 $curlopts[\CURLOPT_READDATA] = $body;
246 } else {
247 $curlopts[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) {
248 static $eof = false;
249 static $buffer = '';
250
251 return self::readRequestBody($length, $body, $buffer, $eof);
252 };
253 }
254
255 if (isset($options['normalized_headers']['content-length'][0])) {
256 $curlopts[\CURLOPT_INFILESIZE] = (int) substr($options['normalized_headers']['content-length'][0], \strlen('Content-Length: '));
257 }
258 if (!isset($options['normalized_headers']['transfer-encoding'])) {
259 $curlopts[\CURLOPT_HTTPHEADER][] = 'Transfer-Encoding:'.(isset($curlopts[\CURLOPT_INFILESIZE]) ? '' : ' chunked');
260 }
261
262 if ('POST' !== $method) {
263 $curlopts[\CURLOPT_UPLOAD] = true;
264
265 if (!isset($options['normalized_headers']['content-type']) && 0 !== ($curlopts[\CURLOPT_INFILESIZE] ?? null)) {
266 $curlopts[\CURLOPT_HTTPHEADER][] = 'Content-Type: application/x-www-form-urlencoded';
267 }
268 }
269 } elseif ('' !== $body || 'POST' === $method) {
270 $curlopts[\CURLOPT_POSTFIELDS] = $body;
271 }
272
273 if ($options['peer_fingerprint']) {
274 if (!isset($options['peer_fingerprint']['pin-sha256'])) {
275 throw new TransportException(__CLASS__.' supports only "pin-sha256" fingerprints.');
276 }
277
278 $curlopts[\CURLOPT_PINNEDPUBLICKEY] = 'sha256//'.implode(';sha256//', $options['peer_fingerprint']['pin-sha256']);
279 }
280
281 if ($options['bindto']) {
282 if (file_exists($options['bindto'])) {
283 $curlopts[\CURLOPT_UNIX_SOCKET_PATH] = $options['bindto'];
284 } elseif (!str_starts_with($options['bindto'], 'if!') && preg_match('/^(.*):(\d+)$/', $options['bindto'], $matches)) {
285 $curlopts[\CURLOPT_INTERFACE] = trim($matches[1], '[]');
286 $curlopts[\CURLOPT_LOCALPORT] = $matches[2];
287 } else {
288 $curlopts[\CURLOPT_INTERFACE] = $options['bindto'];
289 }
290 }
291
292 if (0 < $options['max_duration']) {
293 $curlopts[\CURLOPT_TIMEOUT_MS] = 1000 * $options['max_duration'];
294 }
295
296 if (!empty($options['extra']['curl']) && \is_array($options['extra']['curl'])) {
297 $this->validateExtraCurlOptions($options['extra']['curl']);
298 $curlopts += $options['extra']['curl'];
299 }
300
301 if ($pushedResponse = $this->multi->pushedResponses[$url] ?? null) {
302 unset($this->multi->pushedResponses[$url]);
303
304 if (self::acceptPushForRequest($method, $options, $pushedResponse)) {
305 $this->logger?->debug(\sprintf('Accepting pushed response: "%s %s"', $method, $url));
306
307 // Reinitialize the pushed response with request's options
308 $ch = $pushedResponse->handle;
309 $pushedResponse = $pushedResponse->response;
310 $pushedResponse->__construct($this->multi, $url, $options, $this->logger);
311 } else {
312 $this->logger?->debug(\sprintf('Rejecting pushed response: "%s"', $url));
313 $pushedResponse = null;
314 }
315 }
316
317 if (!$pushedResponse) {
318 $ch = curl_init();
319 $this->logger?->info(\sprintf('Request: "%s %s"', $method, $url));
320 $curlopts += [\CURLOPT_SHARE => $this->multi->share];
321 }
322
323 foreach ($curlopts as $opt => $value) {
324 if (\PHP_INT_SIZE === 8 && \defined('CURLOPT_INFILESIZE_LARGE') && \CURLOPT_INFILESIZE === $opt && $value >= 1 << 31) {
325 $opt = \CURLOPT_INFILESIZE_LARGE;
326 }
327 if (null !== $value && !curl_setopt($ch, $opt, $value) && \CURLOPT_CERTINFO !== $opt && (!\defined('CURLOPT_HEADEROPT') || \CURLOPT_HEADEROPT !== $opt)) {
328 $constantName = $this->findConstantName($opt);
329 throw new TransportException(\sprintf('Curl option "%s" is not supported.', $constantName ?? $opt));
330 }
331 }
332
333 return $pushedResponse ?? new CurlResponse($this->multi, $ch, $options, $this->logger, $method, self::createRedirectResolver($options, $authority), CurlClientState::$curlVersion['version_number'], $url, $ntlmOriginKey);
334 }
335
336 public function stream(ResponseInterface|iterable $responses, ?float $timeout = null): ResponseStreamInterface
337 {
338 if ($responses instanceof CurlResponse) {
339 $responses = [$responses];
340 }
341
342 if ($this->multi->handle instanceof \CurlMultiHandle) {
343 $active = 0;
344 while (\CURLM_CALL_MULTI_PERFORM === curl_multi_exec($this->multi->handle, $active)) {
345 }
346 }
347
348 return new ResponseStream(CurlResponse::stream($responses, $timeout));
349 }
350
351 public function reset(): void
352 {
353 $this->multi->reset();
354 }
355
356 /**
357 * Accepts pushed responses only if their headers related to authentication match the request.
358 */
359 private static function acceptPushForRequest(string $method, array $options, PushedResponse $pushedResponse): bool
360 {
361 if ('' !== $options['body'] || $method !== $pushedResponse->requestHeaders[':method'][0]) {
362 return false;
363 }
364
365 foreach (['proxy', 'no_proxy', 'bindto', 'local_cert', 'local_pk'] as $k) {
366 if ($options[$k] !== $pushedResponse->parentOptions[$k]) {
367 return false;
368 }
369 }
370
371 foreach (['authorization', 'cookie', 'range', 'proxy-authorization'] as $k) {
372 $normalizedHeaders = $options['normalized_headers'][$k] ?? [];
373 foreach ($normalizedHeaders as $i => $v) {
374 $normalizedHeaders[$i] = substr($v, \strlen($k) + 2);
375 }
376
377 if (($pushedResponse->requestHeaders[$k] ?? []) !== $normalizedHeaders) {
378 return false;
379 }
380 }
381
382 $statusCode = $pushedResponse->response->getInfo('http_code') ?: 200;
383
384 return $statusCode < 300 || 400 <= $statusCode;
385 }
386
387 /**
388 * Wraps the request's body callback to allow it to return strings longer than curl requested.
389 */
390 private static function readRequestBody(int $length, \Closure $body, string &$buffer, bool &$eof): string
391 {
392 if (!$eof && \strlen($buffer) < $length) {
393 if (!\is_string($data = $body($length))) {
394 throw new TransportException(\sprintf('The return value of the "body" option callback must be a string, "%s" returned.', get_debug_type($data)));
395 }
396
397 $buffer .= $data;
398 $eof = '' === $data;
399 }
400
401 $data = substr($buffer, 0, $length);
402 $buffer = substr($buffer, $length);
403
404 return $data;
405 }
406
407 /**
408 * Resolves relative URLs on redirects and deals with authentication headers.
409 *
410 * Work around CVE-2018-1000007: Authorization and Cookie headers should not follow redirects - fixed in Curl 7.64
411 */
412 private static function createRedirectResolver(array $options, string $authority): \Closure
413 {
414 $redirectHeaders = [];
415 if (0 < $options['max_redirects']) {
416 $redirectHeaders['authority'] = $authority;
417 $redirectHeaders['with_auth'] = $redirectHeaders['no_auth'] = array_filter($options['headers'], static fn ($h) => 0 !== stripos($h, 'Host:'));
418
419 if (isset($options['normalized_headers']['authorization'][0]) || isset($options['normalized_headers']['cookie'][0])) {
420 $redirectHeaders['no_auth'] = array_filter($options['headers'], static fn ($h) => 0 !== stripos($h, 'Authorization:') && 0 !== stripos($h, 'Cookie:'));
421 }
422 }
423
424 return static function ($ch, string $location, bool $noContent) use (&$redirectHeaders, $options) {
425 try {
426 $location = self::parseUrl($location);
427 $url = self::parseUrl(curl_getinfo($ch, \CURLINFO_EFFECTIVE_URL));
428 $url = self::resolveUrl($location, $url);
429 } catch (InvalidArgumentException) {
430 return null;
431 }
432
433 if ($noContent && $redirectHeaders) {
434 $filterContentHeaders = static fn ($h) => 0 !== stripos($h, 'Content-Length:') && 0 !== stripos($h, 'Content-Type:') && 0 !== stripos($h, 'Transfer-Encoding:');
435 $redirectHeaders['no_auth'] = array_filter($redirectHeaders['no_auth'], $filterContentHeaders);
436 $redirectHeaders['with_auth'] = array_filter($redirectHeaders['with_auth'], $filterContentHeaders);
437 }
438
439 if ($redirectHeaders && isset($location['authority'])) {
440 $requestHeaders = $location['authority'] === $redirectHeaders['authority'] ? $redirectHeaders['with_auth'] : $redirectHeaders['no_auth'];
441 curl_setopt($ch, \CURLOPT_HTTPHEADER, $requestHeaders);
442 } elseif ($noContent && $redirectHeaders) {
443 curl_setopt($ch, \CURLOPT_HTTPHEADER, $redirectHeaders['with_auth']);
444 }
445
446 $proxy = self::getProxyUrl($options['proxy'], $url);
447 curl_setopt($ch, \CURLOPT_PROXY, $proxy);
448
449 if (\defined('CURL_HTTP_VERSION_3') && \CURL_HTTP_VERSION_3 === curl_getinfo($ch, \CURLINFO_HTTP_VERSION) && self::willUseProxy($proxy, $options['no_proxy'] ?? $_SERVER['no_proxy'] ?? $_SERVER['NO_PROXY'] ?? '', parse_url($url['authority'], \PHP_URL_HOST))) {
450 curl_setopt($ch, \CURLOPT_HTTP_VERSION, \defined('CURL_HTTP_VERSION_2_0') ? \CURL_HTTP_VERSION_2_0 : \CURL_HTTP_VERSION_1_1);
451 }
452
453 return implode('', $url);
454 };
455 }
456
457 private function findConstantName(int $opt): ?string
458 {
459 $constants = array_filter(get_defined_constants(), static fn ($v, $k) => $v === $opt && 'C' === $k[0] && (str_starts_with($k, 'CURLOPT_') || str_starts_with($k, 'CURLINFO_')), \ARRAY_FILTER_USE_BOTH);
460
461 return key($constants);
462 }
463
464 /**
465 * Prevents overriding options that are set internally throughout the request.
466 */
467 private function validateExtraCurlOptions(array $options): void
468 {
469 $curloptsToConfig = [
470 // options used in CurlHttpClient
471 \CURLOPT_HTTPAUTH => 'auth_ntlm',
472 \CURLOPT_USERPWD => 'auth_ntlm',
473 \CURLOPT_RESOLVE => 'resolve',
474 \CURLOPT_NOSIGNAL => 'timeout',
475 \CURLOPT_HTTPHEADER => 'headers',
476 \CURLOPT_READDATA => 'body',
477 \CURLOPT_READFUNCTION => 'body',
478 \CURLOPT_INFILESIZE => 'body',
479 \CURLOPT_POSTFIELDS => 'body',
480 \CURLOPT_UPLOAD => 'body',
481 \CURLOPT_INTERFACE => 'bindto',
482 \CURLOPT_TIMEOUT_MS => 'max_duration',
483 \CURLOPT_TIMEOUT => 'max_duration',
484 \CURLOPT_MAXREDIRS => 'max_redirects',
485 \CURLOPT_POSTREDIR => 'max_redirects',
486 \CURLOPT_PROXY => 'proxy',
487 \CURLOPT_NOPROXY => 'no_proxy',
488 \CURLOPT_SSL_VERIFYPEER => 'verify_peer',
489 \CURLOPT_SSL_VERIFYHOST => 'verify_host',
490 \CURLOPT_CAINFO => 'cafile',
491 \CURLOPT_CAPATH => 'capath',
492 \CURLOPT_SSL_CIPHER_LIST => 'ciphers',
493 \CURLOPT_SSLCERT => 'local_cert',
494 \CURLOPT_SSLKEY => 'local_pk',
495 \CURLOPT_KEYPASSWD => 'passphrase',
496 \CURLOPT_CERTINFO => 'capture_peer_cert_chain',
497 \CURLOPT_USERAGENT => 'normalized_headers',
498 \CURLOPT_REFERER => 'headers',
499 // options used in CurlResponse
500 \CURLOPT_NOPROGRESS => 'on_progress',
501 \CURLOPT_PROGRESSFUNCTION => 'on_progress',
502 ];
503
504 if (\defined('CURLOPT_UNIX_SOCKET_PATH')) {
505 $curloptsToConfig[\CURLOPT_UNIX_SOCKET_PATH] = 'bindto';
506 }
507
508 if (\defined('CURLOPT_PINNEDPUBLICKEY')) {
509 $curloptsToConfig[\CURLOPT_PINNEDPUBLICKEY] = 'peer_fingerprint';
510 }
511
512 $curloptsToCheck = [
513 \CURLOPT_PRIVATE,
514 \CURLOPT_HEADERFUNCTION,
515 \CURLOPT_WRITEFUNCTION,
516 \CURLOPT_VERBOSE,
517 \CURLOPT_STDERR,
518 \CURLOPT_RETURNTRANSFER,
519 \CURLOPT_URL,
520 \CURLOPT_FOLLOWLOCATION,
521 \CURLOPT_HEADER,
522 \CURLOPT_CONNECTTIMEOUT,
523 \CURLOPT_CONNECTTIMEOUT_MS,
524 \CURLOPT_HTTP_VERSION,
525 \CURLOPT_PORT,
526 \CURLOPT_DNS_USE_GLOBAL_CACHE,
527 \CURLOPT_PROTOCOLS,
528 \CURLOPT_REDIR_PROTOCOLS,
529 \CURLOPT_COOKIEFILE,
530 \CURLINFO_REDIRECT_COUNT,
531 ];
532
533 if (\defined('CURLOPT_HTTP09_ALLOWED')) {
534 $curloptsToCheck[] = \CURLOPT_HTTP09_ALLOWED;
535 }
536
537 if (\defined('CURLOPT_HEADEROPT')) {
538 $curloptsToCheck[] = \CURLOPT_HEADEROPT;
539 }
540
541 foreach ($options as $opt => $optValue) {
542 if (isset($curloptsToConfig[$opt])) {
543 $constName = $this->findConstantName($opt) ?? $opt;
544 throw new InvalidArgumentException(\sprintf('Cannot set "%s" with "extra.curl", use option "%s" instead.', $constName, $curloptsToConfig[$opt]));
545 }
546
547 if (\in_array($opt, [\CURLOPT_POST, \CURLOPT_PUT, \CURLOPT_CUSTOMREQUEST, \CURLOPT_HTTPGET, \CURLOPT_NOBODY], true)) {
548 throw new InvalidArgumentException('The HTTP method cannot be overridden using "extra.curl".');
549 }
550
551 if (\in_array($opt, $curloptsToCheck, true)) {
552 $constName = $this->findConstantName($opt) ?? $opt;
553 throw new InvalidArgumentException(\sprintf('Cannot set "%s" with "extra.curl".', $constName));
554 }
555 }
556 }
557
558 private static function willUseProxy(?string $proxy, string $noProxy, string $host): bool
559 {
560 if (null === $proxy) {
561 return false;
562 }
563
564 if ('' === $noProxy) {
565 return true;
566 }
567
568 foreach (preg_split('/[\s,]+/', $noProxy) as $rule) {
569 $dotRule = '.'.ltrim($rule, '.');
570
571 if ('*' === $rule || $host === $rule || str_ends_with($host, $dotRule)) {
572 return false;
573 }
574 }
575
576 return true;
577 }
578 }