Debian Codegraph @

vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php

raw
1 <?php
2
3 namespace GuzzleHttp\Handler;
4
5 use GuzzleHttp\Exception\ConnectException;
6 use GuzzleHttp\Exception\RequestException;
7 use GuzzleHttp\Promise as P;
8 use GuzzleHttp\Promise\FulfilledPromise;
9 use GuzzleHttp\Promise\PromiseInterface;
10 use GuzzleHttp\Psr7;
11 use GuzzleHttp\Psr7\LazyOpenStream;
12 use GuzzleHttp\Psr7\Uri;
13 use GuzzleHttp\TransferStats;
14 use GuzzleHttp\TransportSharing;
15 use GuzzleHttp\Utils;
16 use Psr\Http\Message\RequestInterface;
17 use Psr\Http\Message\UriInterface;
18
19 /**
20 * Creates curl resources from a request
21 *
22 * @final
23 */
24 class CurlFactory implements CurlFactoryInterface
25 {
26 public const CURL_VERSION_STR = 'curl_version';
27
28 private const DELEGATED_PROXY_TUNNEL_OWNER = 'proxy-tunnel:delegated-to-libcurl';
29
30 /**
31 * @deprecated
32 */
33 public const LOW_CURL_VERSION_NUMBER = '7.21.2';
34
35 /**
36 * @var resource[]|\CurlHandle[]
37 */
38 private $handles = [];
39
40 /**
41 * @var string|null Owner signature of the proxy tunnels that pooled idle
42 * handles may still hold
43 */
44 private $proxyTunnelOwner;
45
46 /**
47 * @var bool Whether an in-domain handle has been pooled since the last purge
48 */
49 private $poolMayHoldTunnels = false;
50
51 /**
52 * @var int Total number of idle handles to keep in cache
53 */
54 private $maxHandles;
55
56 /**
57 * @var resource|\CurlShareHandle|null
58 */
59 private $shareHandle;
60
61 /**
62 * @var string
63 */
64 private $shareMode;
65
66 /**
67 * @param int $maxHandles Maximum number of idle handles.
68 * @param resource|\CurlShareHandle|null $shareHandle
69 */
70 public function __construct(int $maxHandles, string $shareMode = TransportSharing::NONE, $shareHandle = null)
71 {
72 $this->maxHandles = $maxHandles;
73 $this->shareMode = CurlShareHandleState::normalizeMode($shareMode, 'transport_sharing');
74
75 if ($this->shareMode === TransportSharing::NONE && $shareHandle !== null) {
76 throw new \InvalidArgumentException('A cURL share handle cannot be provided when transport sharing is disabled.');
77 }
78
79 if ($this->shareMode !== TransportSharing::NONE && $shareHandle === null) {
80 throw new \InvalidArgumentException('A cURL share handle is required when transport sharing is enabled.');
81 }
82
83 if ($shareHandle !== null && !self::isCurlShareHandle($shareHandle)) {
84 throw new \InvalidArgumentException('A cURL share handle must be an instance of CurlShareHandle or a curl_share resource.');
85 }
86
87 $this->shareHandle = $shareHandle;
88 }
89
90 /**
91 * @param mixed $value
92 */
93 private static function isCurlShareHandle($value): bool
94 {
95 if (\PHP_VERSION_ID < 80000) {
96 return \is_resource($value) && \get_resource_type($value) === 'curl_share';
97 }
98
99 return $value instanceof \CurlShareHandle;
100 }
101
102 public function create(RequestInterface $request, array $options): EasyHandle
103 {
104 self::validateRequestUriScheme($request);
105
106 $protocolVersion = $request->getProtocolVersion();
107
108 if ('' === $protocolVersion) {
109 \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Sending a request with an empty protocol version is deprecated; guzzlehttp/guzzle 8.0 will reject empty protocol versions.');
110
111 $protocolVersion = '1.1';
112 $request = Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
113 }
114
115 if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
116 if (!CurlVersion::supportsHttp2()) {
117 throw new ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
118 }
119 } elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
120 throw new ConnectException(sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request);
121 }
122
123 if (isset($options['curl']['body_as_string'])) {
124 $options['_body_as_string'] = $options['curl']['body_as_string'];
125 unset($options['curl']['body_as_string']);
126 }
127
128 self::triggerUnsupportedRequestOptionDeprecations($options);
129 $this->rejectRequestLevelShareConflict($options);
130 self::triggerUnsupportedCurlOptionDeprecations($options);
131 self::triggerConflictingCurlOptionDeprecations($options);
132
133 $easy = new EasyHandle();
134 $easy->request = $request;
135 $easy->options = $options;
136 $conf = $this->getDefaultConf($easy);
137 $this->applyMethod($easy, $conf);
138 $this->applyHandlerOptions($easy, $conf);
139 $this->applyHeaders($easy, $conf);
140 unset($conf['_headers']);
141
142 // Add handler options from the request configuration options
143 if (isset($options['curl'])) {
144 $conf = \array_replace($conf, $options['curl']);
145 }
146
147 self::normalizeCurlHeaderOptions($conf);
148 self::applyProxyAuthorizationHeaderHandling($request, $conf);
149 self::rejectRequestLevelShareWithProxyAuth($request, $options, $conf);
150
151 if ($this->shareHandle !== null) {
152 // Conservative blanket mode: a configured share handle hides the
153 // pooled connections' provenance, so sectioned reuse cannot reason
154 // about them.
155 self::forceFreshConnectionForAuthenticatedProxy($request, $conf);
156 } else {
157 $signature = self::proxyTunnelSignature($request, $conf);
158 $easy->proxyTunnelSignature = $signature;
159 if ($signature !== null && $signature !== $this->proxyTunnelOwner) {
160 if ($this->poolMayHoldTunnels) {
161 // Pooled idle handles may hold a different owner's tunnel.
162 $this->discardIdleHandles();
163 $this->poolMayHoldTunnels = false;
164 }
165 // The first in-domain owner latches without purging: the pool
166 // provably holds no in-domain tunnel yet.
167 $this->proxyTunnelOwner = $signature;
168 }
169 }
170
171 $easy->effectiveProxy = self::getEffectiveProxy($conf);
172
173 $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
174 if ($this->shareHandle !== null) {
175 if (!\defined('CURLOPT_SHARE')) {
176 throw new \InvalidArgumentException('The configured cURL share handle requires CURLOPT_SHARE, but it is not available in the installed PHP cURL extension.');
177 }
178
179 $conf[(int) \constant('CURLOPT_SHARE')] = $this->shareHandle;
180 }
181
182 $handle = $this->handles ? \array_pop($this->handles) : \curl_init();
183 if (false === $handle) {
184 throw new \RuntimeException('Can not initialize cURL handle.');
185 }
186 $easy->handle = $handle;
187
188 try {
189 $this->applyCurlOptions($handle, $conf);
190 } catch (\Throwable $e) {
191 if (PHP_VERSION_ID < 80000 && \is_resource($handle)) {
192 \curl_close($handle);
193 }
194 unset($easy->handle);
195
196 throw $e;
197 }
198
199 return $easy;
200 }
201
202 /**
203 * @param resource|\CurlHandle $handle
204 * @param array<int|string, mixed> $conf
205 */
206 private function applyCurlOptions($handle, array $conf): void
207 {
208 foreach ($conf as $option => $value) {
209 if (!\is_int($option)) {
210 throw new \InvalidArgumentException(\sprintf(
211 'Invalid cURL option %s.',
212 self::formatCurlOption($option)
213 ));
214 }
215
216 try {
217 $success = curl_setopt($handle, $option, $value);
218 } catch (\Throwable $e) {
219 throw new \InvalidArgumentException(
220 \sprintf(
221 'Unable to set cURL option %s: %s',
222 self::formatCurlOption($option),
223 $e->getMessage()
224 ),
225 0,
226 $e
227 );
228 }
229
230 if (!$success) {
231 throw new \InvalidArgumentException(\sprintf(
232 'Unable to set cURL option %s.',
233 self::formatCurlOption($option)
234 ));
235 }
236 }
237 }
238
239 private function rejectRequestLevelShareConflict(array $options): void
240 {
241 if ($this->shareHandle === null) {
242 return;
243 }
244
245 if (
246 !\defined('CURLOPT_SHARE')
247 || !isset($options['curl'])
248 || !\is_array($options['curl'])
249 || !\array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl'])
250 ) {
251 return;
252 }
253
254 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with configured transport sharing.');
255 }
256
257 /**
258 * @param array<int|string, mixed> $conf
259 */
260 private static function rejectRequestLevelShareWithProxyAuth(RequestInterface $request, array $options, array $conf): void
261 {
262 if (!self::hasRequestLevelCurlShare($options)) {
263 return;
264 }
265
266 $proxy = self::getEffectiveProxy($conf);
267 if (
268 $proxy === null
269 || !self::usesProxyTunnel($request, $conf)
270 || !self::isHttpProxyForConnectionReuse($proxy, $conf)
271 || !self::hasAuthenticatedHttpProxyState($proxy, $conf)
272 ) {
273 return;
274 }
275
276 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with authenticated HTTP/HTTPS proxy tunnel configuration; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
277 }
278
279 private static function hasRequestLevelCurlShare(array $options): bool
280 {
281 return \defined('CURLOPT_SHARE')
282 && isset($options['curl'])
283 && \is_array($options['curl'])
284 && \array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl']);
285 }
286
287 /**
288 * @param array<int|string, mixed> $conf
289 */
290 private static function hasAuthenticatedHttpProxyState(string $proxy, array $conf): bool
291 {
292 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
293 $proxyParts = \parse_url($proxyForParsing);
294
295 if (
296 \is_array($proxyParts)
297 && (\array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts))
298 ) {
299 return true;
300 }
301
302 if (self::hasCurlProxyCredentials($conf)) {
303 return true;
304 }
305
306 if (self::hasCurlProxyAuthorizationHeader($conf)) {
307 return true;
308 }
309
310 $httpHeaders = $conf[\CURLOPT_HTTPHEADER] ?? [];
311 if (\is_array($httpHeaders) && self::proxyAuthorizationHeaderValuesFromList($httpHeaders) !== []) {
312 return true;
313 }
314
315 return self::hasCurlProxyTlsCredentials($conf);
316 }
317
318 /**
319 * @param int|string $option
320 */
321 private static function formatCurlOption($option): string
322 {
323 if (!\is_int($option)) {
324 return \sprintf('"%s"', $option);
325 }
326
327 static $names = null;
328
329 if (null === $names) {
330 $names = [];
331 foreach (\get_defined_constants(true)['curl'] ?? [] as $name => $value) {
332 if (\is_int($value) && \strpos($name, 'CURLOPT_') === 0 && !isset($names[$value])) {
333 $names[$value] = $name;
334 }
335 }
336 }
337
338 if (isset($names[$option])) {
339 return \sprintf('%s (%d)', $names[$option], $option);
340 }
341
342 return (string) $option;
343 }
344
345 private static function triggerConflictingCurlOptionDeprecations(array $options): void
346 {
347 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
348 return;
349 }
350
351 $conflictingOptions = self::conflictingCurlOptions();
352 $sinceOverrides = self::conflictingCurlOptionSinceOverrides();
353
354 foreach ($options['curl'] as $option => $_) {
355 if (!\array_key_exists($option, $conflictingOptions)) {
356 continue;
357 }
358
359 $name = self::formatCurlOption($option);
360 $replacement = $conflictingOptions[$option];
361 $since = $sinceOverrides[$option] ?? '7.11';
362 if ($replacement !== null) {
363 \trigger_deprecation(
364 'guzzlehttp/guzzle',
365 $since,
366 \sprintf(
367 'Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed request handling. Use %s instead.',
368 $name,
369 $replacement
370 )
371 );
372
373 continue;
374 }
375
376 \trigger_deprecation(
377 'guzzlehttp/guzzle',
378 $since,
379 \sprintf(
380 'Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject this option because it conflicts with Guzzle-managed cURL internals.',
381 $name
382 )
383 );
384 }
385 }
386
387 private static function triggerUnsupportedCurlOptionDeprecations(array $options): void
388 {
389 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
390 return;
391 }
392
393 $supportedOptions = self::supportedCurlOptions();
394 $conflictingOptions = self::conflictingCurlOptions();
395
396 foreach ($options['curl'] as $option => $_) {
397 if (
398 !\is_int($option)
399 || \array_key_exists($option, $supportedOptions)
400 || \array_key_exists($option, $conflictingOptions)
401 ) {
402 continue;
403 }
404
405 \trigger_deprecation(
406 'guzzlehttp/guzzle',
407 '7.12',
408 \sprintf(
409 'Passing %s in the "curl" request option is deprecated; guzzlehttp/guzzle 8.0 will reject raw cURL options outside the built-in cURL handlers\' allow-list.',
410 self::formatCurlOption($option)
411 )
412 );
413 }
414 }
415
416 private static function triggerUnsupportedRequestOptionDeprecations(array $options): void
417 {
418 if (\array_key_exists('stream_context', $options)) {
419 \trigger_deprecation('guzzlehttp/guzzle', '7.11', 'Passing the "stream_context" request option to a cURL handler is deprecated; guzzlehttp/guzzle 8.0 will reject this option because cURL handlers ignore PHP stream context options.');
420 }
421 }
422
423 /**
424 * @return array<int, string|null>
425 */
426 private static function conflictingCurlOptions(): array
427 {
428 static $options = null;
429
430 if ($options !== null) {
431 return $options;
432 }
433
434 $options = [];
435
436 self::addConflictingCurlOption($options, 'CURLOPT_SHARE', 'the "transport_sharing" client option or cURL handler option');
437 self::addConflictingCurlOption($options, 'CURLOPT_URL', 'the request URI');
438 self::addConflictingCurlOption($options, 'CURLOPT_PORT', 'the request URI');
439 self::addConflictingCurlOption($options, 'CURLOPT_CUSTOMREQUEST', 'the request method');
440 self::addConflictingCurlOption($options, 'CURLOPT_HTTPGET', 'the request method');
441 self::addConflictingCurlOption($options, 'CURLOPT_POST', 'the request method and body');
442 self::addConflictingCurlOption($options, 'CURLOPT_PUT', 'the request method and body');
443 self::addConflictingCurlOption($options, 'CURLOPT_NOBODY', 'the request method');
444 self::addConflictingCurlOption($options, 'CURLOPT_UPLOAD', 'the request body');
445 self::addConflictingCurlOption($options, 'CURLOPT_POSTFIELDS', 'the request body');
446 self::addConflictingCurlOption($options, 'CURLOPT_READFUNCTION', 'the request body');
447 self::addConflictingCurlOption($options, 'CURLOPT_READDATA', 'the request body');
448 self::addConflictingCurlOption($options, 'CURLOPT_INFILE', 'the request body');
449 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE', 'the request body');
450 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE_LARGE', 'the request body');
451 self::addConflictingCurlOption($options, 'CURLOPT_HTTPHEADER', 'the request headers');
452 self::addConflictingCurlOption($options, 'CURLOPT_USERAGENT', 'the request headers');
453 self::addConflictingCurlOption($options, 'CURLOPT_REFERER', 'the request headers');
454 self::addConflictingCurlOption($options, 'CURLOPT_HEADERFUNCTION', 'the "on_headers" request option');
455 self::addConflictingCurlOption($options, 'CURLOPT_WRITEFUNCTION', 'the "sink" request option');
456 self::addConflictingCurlOption($options, 'CURLOPT_FILE', 'the "sink" request option');
457 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT', 'the "timeout" request option');
458 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT_MS', 'the "timeout" request option');
459 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT', 'the "connect_timeout" request option');
460 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT_MS', 'the "connect_timeout" request option');
461 self::addConflictingCurlOption($options, 'CURLOPT_NOSIGNAL', 'the "timeout" or "connect_timeout" request option');
462 self::addConflictingCurlOption($options, 'CURLOPT_NOPROGRESS', 'the "progress" request option');
463 self::addConflictingCurlOption($options, 'CURLOPT_PROGRESSFUNCTION', 'the "progress" request option');
464 self::addConflictingCurlOption($options, 'CURLOPT_XFERINFOFUNCTION', 'the "progress" request option');
465 self::addConflictingCurlOption($options, 'CURLOPT_VERBOSE', 'the "debug" request option');
466 self::addConflictingCurlOption($options, 'CURLOPT_STDERR', 'the "debug" request option');
467 self::addConflictingCurlOption($options, 'CURLOPT_PROXY', 'the "proxy" request option');
468 self::addConflictingCurlOption($options, 'CURLOPT_NOPROXY', 'the "proxy" request option');
469 self::addConflictingCurlOption($options, 'CURLOPT_PROXYTYPE', 'the "proxy" request option with a scheme-prefixed URL');
470 self::addConflictingCurlOption($options, 'CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option');
471 self::addConflictingCurlOption($options, 'CURLOPT_MAXREDIRS', 'the "allow_redirects" request option');
472 self::addConflictingCurlOption($options, 'CURLOPT_POSTREDIR', 'the "allow_redirects" request option');
473 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS', 'the "allow_redirects" request option');
474 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS_STR', 'the "allow_redirects" request option');
475 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS', 'the "protocols" request option');
476 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS_STR', 'the "protocols" request option');
477 self::addConflictingCurlOption($options, 'CURLOPT_HTTP_VERSION', 'the request protocol version');
478 self::addConflictingCurlOption($options, 'CURLOPT_IPRESOLVE', 'the "force_ip_resolve" request option');
479 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYPEER', 'the "verify" request option');
480 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYHOST', 'the "verify" request option');
481 self::addConflictingCurlOption($options, 'CURLOPT_CAINFO', 'the "verify" request option');
482 self::addConflictingCurlOption($options, 'CURLOPT_CAPATH', 'the "verify" request option');
483 self::addConflictingCurlOption($options, 'CURLOPT_SSLVERSION', 'the "crypto_method" or "crypto_method_max" request option');
484 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERT', 'the "cert" request option');
485 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTPASSWD', 'the "cert" request option');
486 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTTYPE', 'the "cert_type" request option');
487 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEY', 'the "ssl_key" request option');
488 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYPASSWD', 'the "ssl_key" request option');
489 self::addConflictingCurlOption($options, 'CURLOPT_KEYPASSWD', 'the "ssl_key" request option');
490 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYTYPE', 'the "ssl_key_type" request option');
491 self::addConflictingCurlOption($options, 'CURLOPT_COOKIE', 'the "Cookie" request header or Guzzle cookie middleware');
492 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEFILE', 'Guzzle cookie middleware');
493 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEJAR', 'Guzzle cookie middleware');
494 self::addConflictingCurlOption($options, 'CURLOPT_COOKIELIST', 'Guzzle cookie middleware');
495 self::addConflictingCurlOption($options, 'CURLOPT_COOKIESESSION', 'Guzzle cookie middleware');
496
497 return $options;
498 }
499
500 /**
501 * @return array<int, string>
502 */
503 private static function conflictingCurlOptionSinceOverrides(): array
504 {
505 static $options = null;
506
507 if ($options !== null) {
508 return $options;
509 }
510
511 $options = [];
512
513 if (\defined('CURLOPT_PROXYTYPE')) {
514 $options[\CURLOPT_PROXYTYPE] = '7.12';
515 }
516
517 return $options;
518 }
519
520 /**
521 * @return array<int, true>
522 */
523 private static function supportedCurlOptions(): array
524 {
525 static $options = null;
526
527 if ($options !== null) {
528 return $options;
529 }
530
531 $options = [];
532
533 self::addSupportedCurlOption($options, 'CURLOPT_ADDRESS_SCOPE');
534 self::addSupportedCurlOption($options, 'CURLOPT_CONNECT_TO');
535 self::addSupportedCurlOption($options, 'CURLOPT_DNS_CACHE_TIMEOUT');
536 self::addSupportedCurlOption($options, 'CURLOPT_DNS_INTERFACE');
537 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP4');
538 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP6');
539 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SERVERS');
540 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SHUFFLE_ADDRESSES');
541 self::addSupportedCurlOption($options, 'CURLOPT_ENCODING');
542 self::addSupportedCurlOption($options, 'CURLOPT_FORBID_REUSE');
543 self::addSupportedCurlOption($options, 'CURLOPT_FRESH_CONNECT');
544 self::addSupportedCurlOption($options, 'CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS');
545 self::addSupportedCurlOption($options, 'CURLOPT_HTTPAUTH');
546 self::addSupportedCurlOption($options, 'CURLOPT_INTERFACE');
547 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORT');
548 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORTRANGE');
549 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_LIMIT');
550 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_TIME');
551 self::addSupportedCurlOption($options, 'CURLOPT_MAXAGE_CONN');
552 self::addSupportedCurlOption($options, 'CURLOPT_MAXCONNECTS');
553 self::addSupportedCurlOption($options, 'CURLOPT_MAXLIFETIME_CONN');
554 self::addSupportedCurlOption($options, 'CURLOPT_HTTPPROXYTUNNEL');
555 self::addSupportedCurlOption($options, 'CURLOPT_PREREQFUNCTION');
556 self::addSupportedCurlOption($options, 'CURLOPT_PROXYHEADER');
557 self::addSupportedCurlOption($options, 'CURLOPT_PROXYUSERPWD');
558 self::addSupportedCurlOption($options, 'CURLOPT_RESOLVE');
559 self::addSupportedCurlOption($options, 'CURLOPT_SSL_CIPHER_LIST');
560 self::addSupportedCurlOption($options, 'CURLOPT_SSL_EC_CURVES');
561 self::addSupportedCurlOption($options, 'CURLOPT_TCP_FASTOPEN');
562 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPALIVE');
563 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPIDLE');
564 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPINTVL');
565 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPCNT');
566 self::addSupportedCurlOption($options, 'CURLOPT_TCP_NODELAY');
567 self::addSupportedCurlOption($options, 'CURLOPT_TLS13_CIPHERS');
568 self::addSupportedCurlOption($options, 'CURLOPT_UNIX_SOCKET_PATH');
569 self::addSupportedCurlOption($options, 'CURLOPT_USERPWD');
570
571 return $options;
572 }
573
574 /**
575 * @param array<int, true> $options
576 */
577 private static function addSupportedCurlOption(array &$options, string $constant): void
578 {
579 if (!\defined($constant)) {
580 return;
581 }
582
583 $value = \constant($constant);
584 if (\is_int($value)) {
585 $options[$value] = true;
586 }
587 }
588
589 /**
590 * @param array<int, string|null> $options
591 */
592 private static function addConflictingCurlOption(array &$options, string $constant, ?string $replacement): void
593 {
594 if (!\defined($constant)) {
595 return;
596 }
597
598 $value = \constant($constant);
599 if (\is_int($value)) {
600 $options[$value] = $replacement;
601 }
602 }
603
604 public function release(EasyHandle $easy): void
605 {
606 $resource = $easy->handle;
607 unset($easy->handle);
608
609 if (
610 \count($this->handles) >= $this->maxHandles
611 || ($easy->proxyTunnelSignature !== null && $easy->proxyTunnelSignature !== $this->proxyTunnelOwner)
612 ) {
613 // Pool is full, or this handle belongs to a superseded tunnel
614 // owner (an async create/release overlap can hand a stale-owner
615 // handle back after a purge) - drop it instead of pooling it.
616 if (PHP_VERSION_ID < 80000) {
617 \curl_close($resource);
618 }
619
620 return;
621 }
622
623 if ($easy->proxyTunnelSignature !== null) {
624 // A pooled handle now carries the current owner's tunnel.
625 $this->poolMayHoldTunnels = true;
626 }
627
628 // Remove all callback functions as they can hold onto references and
629 // are not cleaned up by curl_reset. Using curl_setopt_array does not
630 // work for some reason, so removing each one individually.
631 \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null);
632 \curl_setopt($resource, \CURLOPT_READFUNCTION, null);
633 \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null);
634 \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null);
635
636 if (\defined('CURLOPT_PREREQFUNCTION')) {
637 \curl_setopt($resource, (int) \constant('CURLOPT_PREREQFUNCTION'), null);
638 }
639
640 \curl_reset($resource);
641 $this->handles[] = $resource;
642 }
643
644 /**
645 * Completes a cURL transaction, either returning a response promise or a
646 * rejected promise.
647 *
648 * @param callable(RequestInterface, array): PromiseInterface $handler
649 * @param CurlFactoryInterface $factory Dictates how the handle is released
650 */
651 public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface
652 {
653 if (isset($easy->options['on_stats'])) {
654 self::invokeStats($easy);
655 }
656
657 if (!$easy->response || $easy->errno) {
658 return self::finishError($handler, $easy, $factory);
659 }
660
661 // Return the response if it is present and there is no error.
662 $factory->release($easy);
663
664 // Rewind the body of the response if possible.
665 $body = $easy->response->getBody();
666 if ($body->isSeekable()) {
667 $body->rewind();
668 }
669
670 return new FulfilledPromise($easy->response);
671 }
672
673 private static function invokeStats(EasyHandle $easy): void
674 {
675 $curlStats = \curl_getinfo($easy->handle);
676 $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME);
677 $stats = new TransferStats(
678 $easy->request,
679 $easy->response,
680 $curlStats['total_time'],
681 $easy->errno,
682 $curlStats
683 );
684 ($easy->options['on_stats'])($stats);
685 }
686
687 /**
688 * @param callable(RequestInterface, array): PromiseInterface $handler
689 */
690 private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface
691 {
692 // Get error information and release the handle to the factory.
693 $ctx = [
694 'errno' => $easy->errno,
695 'error' => \curl_error($easy->handle),
696 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME),
697 ] + \curl_getinfo($easy->handle);
698 $ctx[self::CURL_VERSION_STR] = CurlVersion::getVersion() ?? '';
699 $factory->release($easy);
700
701 // Retry when nothing is present or when curl failed to rewind.
702 if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) {
703 return self::retryFailedRewind($handler, $easy, $ctx);
704 }
705
706 return self::createRejection($easy, $ctx);
707 }
708
709 private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface
710 {
711 static $connectionErrors = [
712 \CURLE_OPERATION_TIMEOUTED => true,
713 \CURLE_COULDNT_RESOLVE_HOST => true,
714 \CURLE_COULDNT_CONNECT => true,
715 \CURLE_SSL_CONNECT_ERROR => true,
716 \CURLE_GOT_NOTHING => true,
717 ];
718
719 if ($easy->createResponseException) {
720 return P\Create::rejectionFor(
721 new RequestException(
722 'An error was encountered while creating the response',
723 $easy->request,
724 null,
725 $easy->createResponseException,
726 $ctx
727 )
728 );
729 }
730
731 // If an exception was encountered during the onHeaders event, then
732 // return a rejected promise that wraps that exception.
733 if ($easy->onHeadersException) {
734 return P\Create::rejectionFor(
735 new RequestException(
736 'An error was encountered during the on_headers event',
737 $easy->request,
738 $easy->response,
739 $easy->onHeadersException,
740 $ctx
741 )
742 );
743 }
744
745 $uri = $easy->request->getUri();
746
747 $sanitizedError = self::sanitizeCurlError($ctx['error'] ?? '', $uri, $easy->effectiveProxy);
748
749 $message = \sprintf(
750 'cURL error %s: %s (%s)',
751 $ctx['errno'],
752 $sanitizedError,
753 'see https://curl.se/libcurl/c/libcurl-errors.html'
754 );
755
756 if ('' !== $sanitizedError) {
757 $redactedUriString = Psr7\Utils::redactUserInfo($uri)->__toString();
758 if ($redactedUriString !== '' && false === \strpos($sanitizedError, $redactedUriString)) {
759 $message .= \sprintf(' for %s', $redactedUriString);
760 }
761 }
762
763 // Create a connection exception if it was a specific error code.
764 $error = isset($connectionErrors[$easy->errno])
765 ? new ConnectException($message, $easy->request, null, $ctx)
766 : new RequestException($message, $easy->request, $easy->response, null, $ctx);
767
768 return P\Create::rejectionFor($error);
769 }
770
771 private static function sanitizeCurlError(string $error, UriInterface $uri, ?string $proxy = null): string
772 {
773 if ('' === $error) {
774 return $error;
775 }
776
777 $error = self::redactProxyUserInfo($error, $proxy);
778
779 $baseUri = $uri->withQuery('')->withFragment('');
780 $baseUriString = $baseUri->__toString();
781
782 if ('' === $baseUriString) {
783 return $error;
784 }
785
786 $redactedUriString = Psr7\Utils::redactUserInfo($baseUri)->__toString();
787
788 return str_replace($baseUriString, $redactedUriString, $error);
789 }
790
791 private static function redactProxyUserInfo(string $error, ?string $proxy): string
792 {
793 if ($proxy === null || $proxy === '' || \strpos($proxy, '@') === false) {
794 return $error;
795 }
796
797 // The error message embeds the proxy string exactly as configured,
798 // so the userinfo needle is extracted with parse_url(): Psr7\Uri
799 // normalizes the components, which could make the replacement miss.
800 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
801 $proxyParts = \parse_url($proxyForParsing);
802
803 if (!\is_array($proxyParts)) {
804 // Proxy strings that defeat parse_url() are exactly the ones
805 // libcurl embeds verbatim in error text such as "Unsupported
806 // proxy syntax in '...'": redact everything up to the last '@'
807 // of the authority as a safe-side fallback.
808 $authority = \substr($proxyForParsing, \strpos($proxyForParsing, '://') + 3);
809 $atPosition = \strrpos($authority, '@');
810
811 if ($atPosition === false || $atPosition === 0) {
812 return $error;
813 }
814
815 return \str_replace(\substr($authority, 0, $atPosition).'@', '***@', $error);
816 }
817
818 if (!isset($proxyParts['user']) && !isset($proxyParts['pass'])) {
819 return $error;
820 }
821
822 $userInfo = $proxyParts['user'] ?? '';
823 if (isset($proxyParts['pass'])) {
824 $userInfo .= ':'.$proxyParts['pass'];
825 }
826
827 if ($userInfo === '') {
828 return $error;
829 }
830
831 $redactedUserInfo = '***';
832
833 try {
834 $proxyUri = new Uri($proxyForParsing);
835 $redactedUserInfo = Psr7\Utils::redactUserInfo($proxyUri)->getUserInfo();
836
837 if ($redactedUserInfo === $proxyUri->getUserInfo()) {
838 return $error;
839 }
840 } catch (\InvalidArgumentException $e) {
841 // Unparseable as a URI: fall back to redacting the whole userinfo.
842 }
843
844 return \str_replace($userInfo.'@', $redactedUserInfo.'@', $error);
845 }
846
847 /**
848 * @param array<int|string, mixed> $conf
849 */
850 private static function forceFreshConnectionForAuthenticatedProxy(RequestInterface $request, array &$conf): void
851 {
852 $proxy = self::getEffectiveProxy($conf);
853
854 if ($proxy === null || !self::requiresFreshConnectionForAuthenticatedProxy($request, $proxy, $conf)) {
855 return;
856 }
857
858 $conf[\CURLOPT_FRESH_CONNECT] = true;
859 $conf[\CURLOPT_FORBID_REUSE] = true;
860 }
861
862 /**
863 * @param array<int|string, mixed> $conf
864 */
865 private static function getEffectiveProxy(array $conf): ?string
866 {
867 if (!\array_key_exists(\CURLOPT_PROXY, $conf)) {
868 return null;
869 }
870
871 $proxy = $conf[\CURLOPT_PROXY];
872 if (!\is_string($proxy) || $proxy === '') {
873 return null;
874 }
875
876 // Only the exact raw wildcard is modeled here: libcurl treats '*' as
877 // bypass-all by whole-string comparison, without trimming or host matching.
878 if (\defined('CURLOPT_NOPROXY')) {
879 $noProxy = $conf[(int) \constant('CURLOPT_NOPROXY')] ?? null;
880 if (\is_string($noProxy) && $noProxy === '*') {
881 return null;
882 }
883 }
884
885 return $proxy;
886 }
887
888 /**
889 * @param array<int|string, mixed> $conf
890 */
891 private static function normalizeCurlHeaderOptions(array &$conf): void
892 {
893 $options = [\CURLOPT_HTTPHEADER => 'CURLOPT_HTTPHEADER'];
894 if (\defined('CURLOPT_PROXYHEADER')) {
895 $options[(int) \constant('CURLOPT_PROXYHEADER')] = 'CURLOPT_PROXYHEADER';
896 }
897
898 foreach ($options as $option => $label) {
899 if (!\array_key_exists($option, $conf) || !\is_array($conf[$option])) {
900 continue;
901 }
902
903 $normalized = [];
904 foreach ($conf[$option] as $key => $entry) {
905 if (\is_object($entry) && \method_exists($entry, '__toString')) {
906 $entry = (string) $entry;
907 } elseif (\is_float($entry) && !\is_finite($entry)) {
908 $entry = \is_nan($entry) ? 'NAN' : ($entry > 0 ? 'INF' : '-INF');
909 } elseif (\is_scalar($entry)) {
910 $entry = (string) $entry;
911 } else {
912 throw new \InvalidArgumentException(\sprintf('%s entries must be strings, stringable objects, or scalar values.', $label));
913 }
914
915 if (\strpbrk($entry, "\r\n") !== false) {
916 throw new \InvalidArgumentException(\sprintf('%s entries must not contain a carriage return or line feed.', $label));
917 }
918
919 $normalized[$key] = $entry;
920 }
921
922 $conf[$option] = $normalized;
923 }
924 }
925
926 private static function proxyScheme(string $proxy): ?string
927 {
928 $position = \strpos($proxy, '://');
929
930 return $position === false ? null : \strtolower(\substr($proxy, 0, $position));
931 }
932
933 /**
934 * @param array<int|string, mixed> $conf
935 */
936 private static function requiresFreshConnectionForAuthenticatedProxy(RequestInterface $request, string $proxy, array $conf): bool
937 {
938 if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
939 return false;
940 }
941
942 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
943 $proxyParts = \parse_url($proxyForParsing);
944
945 if (!\is_array($proxyParts)) {
946 return false;
947 }
948
949 if (self::hasCurlProxyAuthorizationHeader($conf)) {
950 return true;
951 }
952
953 // A proxy client certificate or TLS-SRP authenticates the client to the
954 // HTTPS proxy at the TLS layer; libcurl ignored TLS-SRP before 7.83.1
955 // (CVE-2022-27782), so an old build can reuse a tunnel across those
956 // identities. Force a fresh one, as the non-share signature path does.
957 if (
958 !CurlVersion::supportsProxyTlsCredentialAwareConnectionReuse()
959 && self::hasCurlProxyTlsCredentials($conf)
960 ) {
961 return true;
962 }
963
964 if (CurlVersion::supportsProxyCredentialAwareConnectionReuse()) {
965 return false;
966 }
967
968 return \array_key_exists('user', $proxyParts)
969 || \array_key_exists('pass', $proxyParts)
970 || self::hasCurlProxyCredentials($conf);
971 }
972
973 /**
974 * @param array<int|string, mixed> $conf
975 */
976 private static function usesProxyTunnel(RequestInterface $request, array $conf): bool
977 {
978 $scheme = $request->getUri()->getScheme();
979
980 if ('https' === $scheme) {
981 return true;
982 }
983
984 // An HTTP proxy auto-switches to a CONNECT tunnel when CONNECT_TO
985 // redirects the origin, so an http:// target with it set tunnels too.
986 if ('http' === $scheme && self::hasCurlConnectTo($conf)) {
987 return true;
988 }
989
990 return \defined('CURLOPT_HTTPPROXYTUNNEL')
991 && \array_key_exists((int) \constant('CURLOPT_HTTPPROXYTUNNEL'), $conf)
992 && (bool) $conf[(int) \constant('CURLOPT_HTTPPROXYTUNNEL')];
993 }
994
995 /**
996 * @param array<int|string, mixed> $conf
997 */
998 private static function hasCurlConnectTo(array $conf): bool
999 {
1000 if (!\defined('CURLOPT_CONNECT_TO')) {
1001 return false;
1002 }
1003
1004 $option = (int) \constant('CURLOPT_CONNECT_TO');
1005 if (!\array_key_exists($option, $conf)) {
1006 return false;
1007 }
1008
1009 $value = $conf[$option];
1010
1011 return \is_array($value)
1012 ? $value !== []
1013 : $value !== null && $value !== false && $value !== '';
1014 }
1015
1016 /**
1017 * @param array<int|string, mixed> $conf
1018 */
1019 private static function isHttpProxyForConnectionReuse(string $proxy, array $conf): bool
1020 {
1021 if (\strpos($proxy, '://') !== false) {
1022 $proxyParts = \parse_url($proxy);
1023
1024 if (!\is_array($proxyParts) || !isset($proxyParts['scheme'])) {
1025 return false;
1026 }
1027
1028 $proxyScheme = \strtolower($proxyParts['scheme']);
1029
1030 return $proxyScheme === 'http' || $proxyScheme === 'https';
1031 }
1032
1033 return !self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null);
1034 }
1035
1036 /**
1037 * @param mixed $proxyType
1038 */
1039 private static function isSocksProxyType($proxyType): bool
1040 {
1041 if (!\is_int($proxyType)) {
1042 return false;
1043 }
1044
1045 foreach ([
1046 'CURLPROXY_SOCKS4' => 4,
1047 'CURLPROXY_SOCKS5' => 5,
1048 'CURLPROXY_SOCKS4A' => 6,
1049 'CURLPROXY_SOCKS5_HOSTNAME' => 7,
1050 ] as $name => $fallback) {
1051 $value = \defined($name) ? (int) \constant($name) : $fallback;
1052 if ($proxyType === $value) {
1053 return true;
1054 }
1055 }
1056
1057 return false;
1058 }
1059
1060 /**
1061 * @param array<int|string, mixed> $conf
1062 */
1063 private static function hasCurlProxyCredentials(array $conf): bool
1064 {
1065 foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD'] as $option) {
1066 if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) {
1067 return true;
1068 }
1069 }
1070
1071 return false;
1072 }
1073
1074 /**
1075 * @param array<int|string, mixed> $conf
1076 */
1077 private static function hasCurlProxyTlsCredentials(array $conf): bool
1078 {
1079 foreach ([
1080 'CURLOPT_PROXY_SSLCERT',
1081 'CURLOPT_PROXY_SSLCERT_BLOB',
1082 'CURLOPT_PROXY_TLSAUTH_USERNAME',
1083 'CURLOPT_PROXY_TLSAUTH_PASSWORD',
1084 ] as $option) {
1085 if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) {
1086 return true;
1087 }
1088 }
1089
1090 return false;
1091 }
1092
1093 /**
1094 * @param array<int|string, mixed> $conf
1095 */
1096 private static function hasCurlProxyAuthorizationHeader(array $conf): bool
1097 {
1098 return self::curlProxyAuthorizationHeaderValues($conf) !== [];
1099 }
1100
1101 /**
1102 * @param array<int|string, mixed> $conf
1103 */
1104 private static function applyProxyAuthorizationHeaderHandling(RequestInterface $request, array &$conf): void
1105 {
1106 $proxy = self::getEffectiveProxy($conf);
1107 if ($proxy === null || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
1108 return;
1109 }
1110
1111 $httpHeaders = $conf[\CURLOPT_HTTPHEADER] ?? null;
1112 $movedHeaders = [];
1113 $originHeaders = [];
1114
1115 if (\is_array($httpHeaders)) {
1116 foreach ($httpHeaders as $header) {
1117 if (\is_string($header) && self::isProxyAuthorizationHeaderLine($header)) {
1118 $movedHeaders[] = $header;
1119
1120 continue;
1121 }
1122
1123 $originHeaders[] = $header;
1124 }
1125 }
1126
1127 if (CurlVersion::supportsProxyHeaderSeparation()) {
1128 if ($movedHeaders !== []) {
1129 $conf[\CURLOPT_HTTPHEADER] = $originHeaders;
1130 self::appendCurlProxyHeaders($conf, $movedHeaders);
1131 }
1132
1133 // On libcurl 7.37.0-7.42.0 the default is CURLHEADER_UNIFIED.
1134 if ($movedHeaders !== [] || self::hasCurlProxyHeaderOption($conf) || self::usesProxyTunnel($request, $conf)) {
1135 $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE');
1136 }
1137
1138 return;
1139 }
1140
1141 if (\is_array($httpHeaders) && self::proxyAuthorizationHeaderValuesFromList($httpHeaders) !== []) {
1142 $conf[\CURLOPT_FRESH_CONNECT] = true;
1143 $conf[\CURLOPT_FORBID_REUSE] = true;
1144 }
1145 }
1146
1147 /**
1148 * @param array<int|string, mixed> $conf
1149 * @param list<string> $headers
1150 */
1151 private static function appendCurlProxyHeaders(array &$conf, array $headers): void
1152 {
1153 $option = (int) \constant('CURLOPT_PROXYHEADER');
1154
1155 if (\array_key_exists($option, $conf)) {
1156 if (!\is_array($conf[$option])) {
1157 throw new \InvalidArgumentException('CURLOPT_PROXYHEADER must be an array when Proxy-Authorization is migrated from CURLOPT_HTTPHEADER.');
1158 }
1159
1160 $headers = \array_merge($conf[$option], $headers);
1161 }
1162
1163 $conf[$option] = $headers;
1164 }
1165
1166 /**
1167 * @param array<int|string, mixed> $conf
1168 */
1169 private static function hasCurlProxyHeaderOption(array $conf): bool
1170 {
1171 return \defined('CURLOPT_PROXYHEADER')
1172 && \array_key_exists((int) \constant('CURLOPT_PROXYHEADER'), $conf);
1173 }
1174
1175 private static function isProxyAuthorizationHeaderLine(string $header): bool
1176 {
1177 $length = \strcspn($header, ':;');
1178
1179 if ($length === \strlen($header)) {
1180 return false;
1181 }
1182
1183 return 0 === \strcasecmp(\trim(\substr($header, 0, $length)), 'Proxy-Authorization');
1184 }
1185
1186 private static function proxyAuthorizationHeaderValue(string $header): ?string
1187 {
1188 $position = \strpos($header, ':');
1189 if ($position === false) {
1190 return null;
1191 }
1192
1193 if (0 !== \strcasecmp(\trim(\substr($header, 0, $position)), 'Proxy-Authorization')) {
1194 return null;
1195 }
1196
1197 $value = \trim(\substr($header, $position + 1));
1198
1199 return $value === '' ? null : $value;
1200 }
1201
1202 /**
1203 * @param mixed[] $headers
1204 *
1205 * @return list<string>
1206 */
1207 private static function proxyAuthorizationHeaderValuesFromList(array $headers): array
1208 {
1209 $values = [];
1210
1211 foreach ($headers as $header) {
1212 if (!\is_string($header)) {
1213 continue;
1214 }
1215
1216 $value = self::proxyAuthorizationHeaderValue($header);
1217 if ($value !== null) {
1218 $values[] = $value;
1219 }
1220 }
1221
1222 return $values;
1223 }
1224
1225 /**
1226 * Computes the connection-reuse section signature for a proxy tunnel, or
1227 * null when the request does not require sectioning.
1228 *
1229 * @param array<int|string, mixed> $conf
1230 */
1231 private static function proxyTunnelSignature(RequestInterface $request, array $conf): ?string
1232 {
1233 $proxy = self::getEffectiveProxy($conf);
1234 if (
1235 $proxy === null
1236 || !self::usesProxyTunnel($request, $conf)
1237 || !self::isHttpProxyForConnectionReuse($proxy, $conf)
1238 ) {
1239 return null;
1240 }
1241
1242 $headerAuth = self::curlProxyAuthorizationHeaderValues($conf);
1243 if ($headerAuth === [] && CurlVersion::supportsProxyCredentialAwareConnectionReuse()) {
1244 // libcurl keys reuse on parsed proxy credentials only from 8.19.0,
1245 // trusted from 8.20.0 (PROXY_CREDENTIAL_REUSE_VERSION); a literal
1246 // Proxy-Authorization header is never keyed and always sections.
1247 return self::DELEGATED_PROXY_TUNNEL_OWNER;
1248 }
1249
1250 // Hash every proxy channel an old libcurl might not key reuse on. A
1251 // changed signature only forces a fresh connection, never relaxes
1252 // reuse, so over-covering is always safe; under-covering leaks. Proxy
1253 // credentials are the channel CVE-2026-3784 missed; the proxy-TLS
1254 // options are load-bearing on builds before the proxy-TLS reuse fixes
1255 // (the proxy client cert is keyed from 7.52.0, libcurl's first
1256 // HTTPS-proxy release; CVE-2016-5420 (7.50.1) is only the origin-cert
1257 // precedent; TLS-SRP from 7.83.1, CVE-2022-27782) and harmless after.
1258 // The private-key file and passphrase are hashed on this non-delegated
1259 // path too, as fallback hardening: libcurl's mTLS private-key matching
1260 // on reuse was incomplete before 8.21.0 (CVE-2026-8932). This does not
1261 // cover the delegated path (the early return above) or configured share
1262 // handles, so it is not a complete pre-8.21.0 mitigation. The key blob
1263 // and cert/key type encodings (PROXY_SSLKEY_BLOB, PROXY_SSLKEYTYPE,
1264 // PROXY_SSLCERTTYPE) are not hashed and are an accepted residual.
1265 $credentialState = [];
1266 foreach ([
1267 'CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD',
1268 'CURLOPT_PROXYTYPE',
1269 'CURLOPT_PROXY_SSLCERT', 'CURLOPT_PROXY_SSLCERT_BLOB', 'CURLOPT_PROXY_SSLKEY',
1270 'CURLOPT_PROXY_KEYPASSWD', 'CURLOPT_PROXY_TLSAUTH_USERNAME',
1271 'CURLOPT_PROXY_TLSAUTH_PASSWORD', 'CURLOPT_PROXY_SSLVERSION',
1272 ] as $name) {
1273 $credentialState[$name] = \defined($name)
1274 ? ($conf[(int) \constant($name)] ?? null)
1275 : null;
1276 }
1277
1278 return \hash('sha256', \serialize([$proxy, $credentialState, $headerAuth]));
1279 }
1280
1281 /**
1282 * @param array<int|string, mixed> $conf
1283 *
1284 * @return list<string>
1285 */
1286 private static function curlProxyAuthorizationHeaderValues(array $conf): array
1287 {
1288 if (!\defined('CURLOPT_PROXYHEADER')) {
1289 return [];
1290 }
1291
1292 $option = (int) \constant('CURLOPT_PROXYHEADER');
1293 if (!\array_key_exists($option, $conf)) {
1294 return [];
1295 }
1296
1297 $headers = $conf[$option];
1298 if (!\is_array($headers)) {
1299 return [];
1300 }
1301
1302 return self::proxyAuthorizationHeaderValuesFromList($headers);
1303 }
1304
1305 private function discardIdleHandles(): void
1306 {
1307 foreach ($this->handles as $id => $handle) {
1308 if (PHP_VERSION_ID < 80000) {
1309 \curl_close($handle);
1310 }
1311
1312 unset($this->handles[$id]);
1313 }
1314 }
1315
1316 /**
1317 * @return array<int|string, mixed>
1318 */
1319 private function getDefaultConf(EasyHandle $easy): array
1320 {
1321 $uri = $easy->request->getUri();
1322 $protocols = Utils::normalizeProtocols($easy->options['protocols'] ?? ['http', 'https']);
1323 $scheme = $uri->getScheme();
1324 if (!\in_array($scheme, $protocols, true)) {
1325 throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $easy->request);
1326 }
1327
1328 if ($uri->getHost() === '') {
1329 throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $easy->request);
1330 }
1331
1332 $conf = [
1333 '_headers' => $easy->request->getHeaders(),
1334 \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
1335 \CURLOPT_URL => (string) $uri->withFragment(''),
1336 \CURLOPT_RETURNTRANSFER => false,
1337 \CURLOPT_HEADER => false,
1338 \CURLOPT_CONNECTTIMEOUT => 300,
1339 ];
1340
1341 if (\defined('CURLOPT_PROTOCOLS')) {
1342 $conf[\CURLOPT_PROTOCOLS] = self::curlProtocolMask($protocols);
1343 }
1344
1345 $version = $easy->request->getProtocolVersion();
1346
1347 if ('2' === $version || '2.0' === $version) {
1348 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
1349 } elseif ('1.1' === $version) {
1350 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
1351 } else {
1352 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
1353 }
1354
1355 return $conf;
1356 }
1357
1358 /**
1359 * @param string[] $protocols
1360 */
1361 private static function curlProtocolMask(array $protocols): int
1362 {
1363 $mask = 0;
1364
1365 if (\in_array('http', $protocols, true)) {
1366 $mask |= \CURLPROTO_HTTP;
1367 }
1368
1369 if (\in_array('https', $protocols, true)) {
1370 $mask |= \CURLPROTO_HTTPS;
1371 }
1372
1373 return $mask;
1374 }
1375
1376 /**
1377 * @param mixed $type
1378 */
1379 private static function normalizeTlsFileType(string $option, $type): string
1380 {
1381 if (!\is_string($type) || $type === '') {
1382 throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
1383 }
1384
1385 return \strtoupper($type);
1386 }
1387
1388 private static function shouldValidateSslKeyFile(?string $type): bool
1389 {
1390 return $type !== 'ENG' && $type !== 'PROV';
1391 }
1392
1393 private function applyMethod(EasyHandle $easy, array &$conf): void
1394 {
1395 $body = $easy->request->getBody();
1396 $size = $body->getSize();
1397
1398 if ($size === null || $size > 0) {
1399 $this->applyBody($easy->request, $easy->options, $conf);
1400
1401 return;
1402 }
1403
1404 $method = $easy->request->getMethod();
1405 if ($method === 'PUT' || $method === 'POST') {
1406 // See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
1407 if (!$easy->request->hasHeader('Content-Length')) {
1408 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
1409 }
1410 } elseif ($method === 'HEAD') {
1411 $conf[\CURLOPT_NOBODY] = true;
1412 unset(
1413 $conf[\CURLOPT_WRITEFUNCTION],
1414 $conf[\CURLOPT_READFUNCTION],
1415 $conf[\CURLOPT_FILE],
1416 $conf[\CURLOPT_INFILE]
1417 );
1418 }
1419 }
1420
1421 private function applyBody(RequestInterface $request, array $options, array &$conf): void
1422 {
1423 $size = $request->hasHeader('Content-Length')
1424 ? (int) $request->getHeaderLine('Content-Length')
1425 : null;
1426
1427 // Send the body as a string if the size is less than 1MB OR if the
1428 // [curl][body_as_string] request value is set.
1429 if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) {
1430 $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody();
1431 // Don't duplicate the Content-Length header
1432 $this->removeHeader('Content-Length', $conf);
1433 $this->removeHeader('Transfer-Encoding', $conf);
1434 } else {
1435 $conf[\CURLOPT_UPLOAD] = true;
1436 if ($size !== null) {
1437 $conf[\CURLOPT_INFILESIZE] = $size;
1438 $this->removeHeader('Content-Length', $conf);
1439 }
1440 $body = $request->getBody();
1441 if ($body->isSeekable()) {
1442 $body->rewind();
1443 }
1444 $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body) {
1445 return $body->read($length);
1446 };
1447 }
1448
1449 // If the Expect header is not present, prevent curl from adding it
1450 if (!$request->hasHeader('Expect')) {
1451 $conf[\CURLOPT_HTTPHEADER][] = 'Expect:';
1452 }
1453
1454 // cURL sometimes adds a content-type by default. Prevent this.
1455 if (!$request->hasHeader('Content-Type')) {
1456 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:';
1457 }
1458 }
1459
1460 private function applyHeaders(EasyHandle $easy, array &$conf): void
1461 {
1462 foreach ($conf['_headers'] as $name => $values) {
1463 foreach ($values as $value) {
1464 $value = (string) $value;
1465 if ($value === '') {
1466 // cURL requires a special format for empty headers.
1467 // See https://github.com/guzzle/guzzle/issues/1882 for more details.
1468 $conf[\CURLOPT_HTTPHEADER][] = "$name;";
1469 } else {
1470 $conf[\CURLOPT_HTTPHEADER][] = "$name: $value";
1471 }
1472 }
1473 }
1474
1475 // Remove the Accept header if one was not set
1476 if (!$easy->request->hasHeader('Accept')) {
1477 $conf[\CURLOPT_HTTPHEADER][] = 'Accept:';
1478 }
1479 }
1480
1481 /**
1482 * Remove a header from the options array.
1483 *
1484 * @param string $name Case-insensitive header to remove
1485 * @param array $options Array of options to modify
1486 */
1487 private function removeHeader(string $name, array &$options): void
1488 {
1489 foreach (\array_keys($options['_headers']) as $key) {
1490 if (!\strcasecmp((string) $key, $name)) {
1491 unset($options['_headers'][$key]);
1492
1493 return;
1494 }
1495 }
1496 }
1497
1498 private function applyHandlerOptions(EasyHandle $easy, array &$conf): void
1499 {
1500 $options = $easy->options;
1501 if (isset($options['verify'])) {
1502 if ($options['verify'] === false) {
1503 unset($conf[\CURLOPT_CAINFO]);
1504 $conf[\CURLOPT_SSL_VERIFYHOST] = 0;
1505 $conf[\CURLOPT_SSL_VERIFYPEER] = false;
1506 } else {
1507 $conf[\CURLOPT_SSL_VERIFYHOST] = 2;
1508 $conf[\CURLOPT_SSL_VERIFYPEER] = true;
1509 if (\is_string($options['verify'])) {
1510 // Throw an error if the file/folder/link path is not valid or doesn't exist.
1511 if (!\file_exists($options['verify'])) {
1512 throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}");
1513 }
1514 // If it's a directory or a link to a directory use CURLOPT_CAPATH.
1515 // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
1516 if (
1517 \is_dir($options['verify'])
1518 || (
1519 \is_link($options['verify']) === true
1520 && ($verifyLink = \readlink($options['verify'])) !== false
1521 && \is_dir($verifyLink)
1522 )
1523 ) {
1524 $conf[\CURLOPT_CAPATH] = $options['verify'];
1525 } else {
1526 $conf[\CURLOPT_CAINFO] = $options['verify'];
1527 }
1528 }
1529 }
1530 }
1531
1532 if (!isset($options['curl'][\CURLOPT_ENCODING]) && isset($options['decode_content']) && $options['decode_content'] !== false) {
1533 $accept = $easy->request->getHeaderLine('Accept-Encoding');
1534 if ($accept !== '') {
1535 $conf[\CURLOPT_ENCODING] = $accept;
1536 } else {
1537 // The empty string enables all available decoders and implicitly
1538 // sets a matching 'Accept-Encoding' header.
1539 $conf[\CURLOPT_ENCODING] = '';
1540 // But as the user did not specify any encoding preference,
1541 // let's leave it up to server by preventing curl from sending
1542 // the header, which will be interpreted as 'Accept-Encoding: *'.
1543 // https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
1544 $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
1545 }
1546 }
1547
1548 if (!isset($options['sink'])) {
1549 // Use a default temp stream if no sink was set.
1550 $options['sink'] = Psr7\Utils::tryFopen('php://temp', 'w+');
1551 }
1552 $sink = $options['sink'];
1553 if (!\is_string($sink)) {
1554 $sink = Psr7\Utils::streamFor($sink);
1555 } elseif (!\is_dir(\dirname($sink))) {
1556 // Ensure that the directory exists before failing in curl.
1557 throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink));
1558 } else {
1559 $sink = new LazyOpenStream($sink, 'w+');
1560 }
1561 $easy->sink = $sink;
1562 $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int {
1563 return $sink->write($write);
1564 };
1565
1566 $timeoutRequiresNoSignal = false;
1567 if (isset($options['timeout'])) {
1568 $timeoutRequiresNoSignal |= $options['timeout'] < 1;
1569 $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
1570 }
1571
1572 // CURL default value is CURL_IPRESOLVE_WHATEVER
1573 if (isset($options['force_ip_resolve'])) {
1574 if ('v4' === $options['force_ip_resolve']) {
1575 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4;
1576 } elseif ('v6' === $options['force_ip_resolve']) {
1577 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6;
1578 }
1579 }
1580
1581 if (isset($options['connect_timeout'])) {
1582 $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1;
1583 $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
1584 }
1585
1586 if ($timeoutRequiresNoSignal && \strtoupper(\substr(\PHP_OS, 0, 3)) !== 'WIN') {
1587 $conf[\CURLOPT_NOSIGNAL] = true;
1588 }
1589
1590 // Always pin CURLOPT_PROXY (and CURLOPT_NOPROXY when available) so
1591 // that libcurl never falls back to reading proxy environment
1592 // variables itself. When the proxy request option makes no decision,
1593 // the environment is resolved here with libcurl's own semantics.
1594 $proxyConf = null;
1595 $noProxyConf = '';
1596 if (isset($options['proxy'])) {
1597 if (!\is_array($options['proxy'])) {
1598 $proxyConf = $options['proxy'];
1599 } else {
1600 $scheme = $easy->request->getUri()->getScheme();
1601 if (isset($options['proxy'][$scheme])) {
1602 if (
1603 isset($options['proxy']['no'])
1604 && Utils::isUriInNoProxy($easy->request->getUri(), $options['proxy']['no'])
1605 ) {
1606 $proxyConf = '';
1607 $noProxyConf = '*';
1608 } else {
1609 $proxyConf = $options['proxy'][$scheme];
1610 }
1611 }
1612 }
1613 }
1614
1615 if ($proxyConf === null) {
1616 $proxyConf = ProxyEnvironment::getProxyForScheme($easy->request->getUri()->getScheme());
1617 if ($proxyConf === null) {
1618 $proxyConf = '';
1619 } elseif (
1620 ($noProxy = ProxyEnvironment::getNoProxy()) !== null
1621 && Utils::isUriInNoProxy($easy->request->getUri(), ProxyEnvironment::splitNoProxy($noProxy))
1622 ) {
1623 // The environment no_proxy list is tokenized the way libcurl
1624 // tokenizes it and matched here with the same rules as the
1625 // proxy option's "no" list, so behavior does not depend on
1626 // the installed libcurl's matcher.
1627 $proxyConf = '';
1628 $noProxyConf = '*';
1629 }
1630 }
1631
1632 if (\is_string($proxyConf) && $proxyConf !== '') {
1633 $scheme = self::proxyScheme($proxyConf);
1634 if ($scheme !== null && \preg_match('/^[a-z][a-z0-9.+-]*$/D', $scheme) !== 1) {
1635 // A "://" with a prefix that is not a valid scheme (leading
1636 // junk such as a space or non-breaking space) is treated by
1637 // libcurl as an unknown scheme and silently downgraded to a
1638 // plaintext HTTP proxy. Fail closed before any bytes reach the
1639 // wire.
1640 throw new RequestException('The proxy URL is malformed.', $easy->request);
1641 }
1642 if ($scheme === 'https' && !CurlVersion::supportsHttpsProxy()) {
1643 // libcurl before 7.50.2 silently downgrades an https:// proxy
1644 // to a plaintext HTTP proxy; 7.50.2 through 7.51, and builds
1645 // without HTTPS-proxy support, fail at connect time. Fail
1646 // closed before any bytes reach the wire.
1647 throw new RequestException('HTTPS proxies are not supported by the installed libcurl; libcurl 7.52.0 or newer built with HTTPS-proxy support is required.', $easy->request);
1648 }
1649 }
1650
1651 $conf[\CURLOPT_PROXY] = $proxyConf;
1652 if (\defined('CURLOPT_NOPROXY')) {
1653 $conf[(int) \constant('CURLOPT_NOPROXY')] = $noProxyConf;
1654 }
1655
1656 $this->applyTlsVersionRange($easy, $conf);
1657
1658 $certType = null;
1659 if (isset($options['cert_type'])) {
1660 $certType = self::normalizeTlsFileType('cert_type', $options['cert_type']);
1661 $conf[\CURLOPT_SSLCERTTYPE] = $certType;
1662 }
1663
1664 if (isset($options['cert'])) {
1665 $cert = $options['cert'];
1666 if (\is_array($cert)) {
1667 if (!isset($cert[0]) || !\is_string($cert[0])) {
1668 throw new \InvalidArgumentException('Invalid cert request option');
1669 }
1670 if (isset($cert[1])) {
1671 if (!\is_string($cert[1])) {
1672 throw new \InvalidArgumentException('Invalid cert request option');
1673 }
1674 $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
1675 }
1676 $cert = $cert[0];
1677 }
1678 if (!\is_string($cert)) {
1679 throw new \InvalidArgumentException('Invalid cert request option');
1680 }
1681 if (!\file_exists($cert)) {
1682 throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
1683 }
1684 // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
1685 // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
1686 $ext = pathinfo($cert, \PATHINFO_EXTENSION);
1687 if ($certType === null && preg_match('#^(der|p12)$#i', $ext)) {
1688 $conf[\CURLOPT_SSLCERTTYPE] = strtoupper($ext);
1689 }
1690 $conf[\CURLOPT_SSLCERT] = $cert;
1691 }
1692
1693 $sslKeyType = null;
1694 if (isset($options['ssl_key_type'])) {
1695 $sslKeyType = self::normalizeTlsFileType('ssl_key_type', $options['ssl_key_type']);
1696 $conf[\CURLOPT_SSLKEYTYPE] = $sslKeyType;
1697 }
1698
1699 if (isset($options['ssl_key'])) {
1700 if (\is_array($options['ssl_key'])) {
1701 if (!isset($options['ssl_key'][0]) || !\is_string($options['ssl_key'][0])) {
1702 throw new \InvalidArgumentException('Invalid ssl_key request option');
1703 }
1704 if (isset($options['ssl_key'][1])) {
1705 if (!\is_string($options['ssl_key'][1])) {
1706 throw new \InvalidArgumentException('Invalid ssl_key request option');
1707 }
1708 $conf[\CURLOPT_SSLKEYPASSWD] = $options['ssl_key'][1];
1709 }
1710 $sslKey = $options['ssl_key'][0];
1711 }
1712
1713 $sslKey = $sslKey ?? $options['ssl_key'];
1714
1715 if (!\is_string($sslKey)) {
1716 throw new \InvalidArgumentException('Invalid ssl_key request option');
1717 }
1718
1719 if (self::shouldValidateSslKeyFile($sslKeyType) && !\file_exists($sslKey)) {
1720 throw new \InvalidArgumentException("SSL private key not found: {$sslKey}");
1721 }
1722 $conf[\CURLOPT_SSLKEY] = $sslKey;
1723 }
1724
1725 if (isset($options['progress'])) {
1726 $progress = $options['progress'];
1727 if (!\is_callable($progress)) {
1728 throw new \InvalidArgumentException('progress client option must be callable');
1729 }
1730 $conf[\CURLOPT_NOPROGRESS] = false;
1731 $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) {
1732 $progress($downloadSize, $downloaded, $uploadSize, $uploaded);
1733 };
1734 }
1735
1736 if (!empty($options['debug'])) {
1737 $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']);
1738 $conf[\CURLOPT_VERBOSE] = true;
1739 }
1740 }
1741
1742 private function applyTlsVersionRange(EasyHandle $easy, array &$conf): void
1743 {
1744 $options = $easy->options;
1745 $cryptoMethod = $options['crypto_method'] ?? null;
1746 $cryptoMethodMax = $options['crypto_method_max'] ?? null;
1747
1748 if ($cryptoMethod === null && $cryptoMethodMax === null) {
1749 return;
1750 }
1751
1752 $protocolVersion = $easy->request->getProtocolVersion();
1753 $isHttp2 = '2' === $protocolVersion || '2.0' === $protocolVersion;
1754
1755 if ($isHttp2 && $cryptoMethodMax !== null && TlsVersion::ordinal('crypto_method_max', $cryptoMethodMax) < 12) {
1756 throw new \InvalidArgumentException(
1757 'Invalid crypto_method_max request option: HTTP/2 requires TLS 1.2 or higher'
1758 );
1759 }
1760
1761 if ($isHttp2 && $cryptoMethod !== null && TlsVersion::ordinal('crypto_method', $cryptoMethod) < 12) {
1762 $cryptoMethod = \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
1763 }
1764
1765 TlsVersion::assertRange($cryptoMethod, $cryptoMethodMax);
1766
1767 $sslVersion = $cryptoMethod === null
1768 ? \CURL_SSLVERSION_DEFAULT
1769 : self::curlMinSslVersion($cryptoMethod);
1770
1771 if ($cryptoMethodMax !== null) {
1772 $sslVersion |= self::curlMaxSslVersion($cryptoMethodMax);
1773 }
1774
1775 $conf[\CURLOPT_SSLVERSION] = $sslVersion;
1776 }
1777
1778 /**
1779 * @param mixed $value
1780 */
1781 private static function curlMinSslVersion($value): int
1782 {
1783 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
1784 return \CURL_SSLVERSION_TLSv1_0;
1785 }
1786
1787 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
1788 return \CURL_SSLVERSION_TLSv1_1;
1789 }
1790
1791 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
1792 if (!CurlVersion::supportsTls12()) {
1793 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL');
1794 }
1795
1796 return \CURL_SSLVERSION_TLSv1_2;
1797 }
1798
1799 if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
1800 if (!CurlVersion::supportsTls13()) {
1801 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
1802 }
1803
1804 return \CURL_SSLVERSION_TLSv1_3;
1805 }
1806
1807 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
1808 }
1809
1810 /**
1811 * @param mixed $value
1812 */
1813 private static function curlMaxSslVersion($value): int
1814 {
1815 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
1816 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_0');
1817 }
1818
1819 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
1820 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_1');
1821 }
1822
1823 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
1824 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_2');
1825 }
1826
1827 if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
1828 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_3');
1829 }
1830
1831 throw new \InvalidArgumentException('Invalid crypto_method_max request option: unknown version provided');
1832 }
1833
1834 private static function requireCurlMaxSslVersion(string $constant): int
1835 {
1836 if (\defined($constant)) {
1837 /** @var int */
1838 return \constant($constant);
1839 }
1840
1841 throw new \InvalidArgumentException(
1842 'Invalid crypto_method_max request option: maximum TLS version control is not supported by your version of cURL'
1843 );
1844 }
1845
1846 private static function validateRequestUriScheme(RequestInterface $request): void
1847 {
1848 $scheme = $request->getUri()->getScheme();
1849 if ($scheme === '') {
1850 throw new RequestException('URI must include a scheme and host. Use an absolute URI, a network-path reference starting with //, or configure a base_uri.', $request);
1851 }
1852
1853 if (!\in_array($scheme, ['http', 'https'], true)) {
1854 throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
1855 }
1856 }
1857
1858 /**
1859 * This function ensures that a response was set on a transaction. If one
1860 * was not set, then the request is retried if possible. This error
1861 * typically means you are sending a payload, curl encountered a
1862 * "Connection died, retrying a fresh connect" error, tried to rewind the
1863 * stream, and then encountered a "necessary data rewind wasn't possible"
1864 * error, causing the request to be sent through curl_multi_info_read()
1865 * without an error status.
1866 *
1867 * @param callable(RequestInterface, array): PromiseInterface $handler
1868 */
1869 private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface
1870 {
1871 try {
1872 // Only rewind if the body has been read from.
1873 $body = $easy->request->getBody();
1874 if ($body->tell() > 0) {
1875 $body->rewind();
1876 }
1877 } catch (\RuntimeException $e) {
1878 $ctx['error'] = 'The connection unexpectedly failed without '
1879 .'providing an error. The request would have been retried, '
1880 .'but attempting to rewind the request body failed. '
1881 .'Exception: '.$e;
1882
1883 return self::createRejection($easy, $ctx);
1884 }
1885
1886 // Retry no more than 3 times before giving up.
1887 if (!isset($easy->options['_curl_retries'])) {
1888 $easy->options['_curl_retries'] = 1;
1889 } elseif ($easy->options['_curl_retries'] == 2) {
1890 $ctx['error'] = 'The cURL request was retried 3 times '
1891 .'and did not succeed. The most likely reason for the failure '
1892 .'is that cURL was unable to rewind the body of the request '
1893 .'and subsequent retries resulted in the same error. Turn on '
1894 .'the debug option to see what went wrong. See '
1895 .'https://bugs.php.net/bug.php?id=47204 for more information.';
1896
1897 return self::createRejection($easy, $ctx);
1898 } else {
1899 ++$easy->options['_curl_retries'];
1900 }
1901
1902 return $handler($easy->request, $easy->options);
1903 }
1904
1905 private function createHeaderFn(EasyHandle $easy): callable
1906 {
1907 if (isset($easy->options['on_headers'])) {
1908 $onHeaders = $easy->options['on_headers'];
1909
1910 if (!\is_callable($onHeaders)) {
1911 throw new \InvalidArgumentException('on_headers must be callable');
1912 }
1913 } else {
1914 $onHeaders = null;
1915 }
1916
1917 return static function ($ch, $h) use (
1918 $onHeaders,
1919 $easy,
1920 &$startingResponse
1921 ) {
1922 $value = \trim($h);
1923 if ($value === '') {
1924 $startingResponse = true;
1925 try {
1926 $easy->createResponse();
1927 } catch (\Throwable $e) {
1928 $easy->response = null;
1929 $easy->createResponseException = $e;
1930
1931 return -1;
1932 }
1933 if ($onHeaders !== null) {
1934 try {
1935 $onHeaders($easy->response);
1936 } catch (\Throwable $e) {
1937 // Associate the exception with the handle and trigger
1938 // a curl header write error by returning 0.
1939 $easy->onHeadersException = $e;
1940
1941 return -1;
1942 }
1943 }
1944 } elseif ($startingResponse) {
1945 $startingResponse = false;
1946 $easy->headers = [$value];
1947 } else {
1948 $easy->headers[] = $value;
1949 }
1950
1951 return \strlen($h);
1952 };
1953 }
1954
1955 public function __destruct()
1956 {
1957 $this->discardIdleHandles();
1958 }
1959 }