vendor/guzzlehttp/guzzle/src/Handler/CurlFactory.php
2585 lines · 103579 bytes
1<?php
2
3namespace GuzzleHttp\Handler;
4
5use GuzzleHttp\Exception\ConnectException;
6use GuzzleHttp\Exception\RequestException;
7use GuzzleHttp\Multiplexing;
8use GuzzleHttp\Promise as P;
9use GuzzleHttp\Promise\FulfilledPromise;
10use GuzzleHttp\Promise\PromiseInterface;
11use GuzzleHttp\Psr7;
12use GuzzleHttp\Psr7\LazyOpenStream;
13use GuzzleHttp\Psr7\Uri;
14use GuzzleHttp\TransferStats;
15use GuzzleHttp\TransportSharing;
16use GuzzleHttp\Utils;
17use Psr\Http\Message\RequestInterface;
18use Psr\Http\Message\UriInterface;
19
20/**
21 * Creates curl resources from a request
22 *
23 * @final
24 */
25class CurlFactory implements CurlFactoryInterface
26{
27 public const CURL_VERSION_STR = 'curl_version';
28
29 private const DELEGATED_PROXY_TUNNEL_OWNER = 'proxy-tunnel:delegated-to-libcurl';
30
31 /**
32 * String-valued proxy credential cURL options whose values feed the
33 * connection-reuse section signatures. Stringable values are cast
34 * exactly once, before signature computation, so the signature and
35 * ext-curl observe the same string; a stateful __toString() could
36 * otherwise produce one value for the signature and a different one on
37 * the wire, giving two credentials the same section. Numeric options
38 * (CURLOPT_PROXYTYPE, CURLOPT_PROXY_SSLVERSION) and blob options
39 * (CURLOPT_PROXY_SSLCERT_BLOB) are deliberately excluded.
40 */
41 private const STRINGABLE_PROXY_CREDENTIAL_OPTIONS = [
42 'CURLOPT_PROXYUSERPWD',
43 'CURLOPT_PROXYUSERNAME',
44 'CURLOPT_PROXYPASSWORD',
45 'CURLOPT_PROXY_SSLCERT',
46 'CURLOPT_PROXY_SSLKEY',
47 'CURLOPT_PROXY_KEYPASSWD',
48 'CURLOPT_PROXY_TLSAUTH_USERNAME',
49 'CURLOPT_PROXY_TLSAUTH_PASSWORD',
50 ];
51
52 /**
53 * @deprecated
54 */
55 public const LOW_CURL_VERSION_NUMBER = '7.21.2';
56
57 /**
58 * @var resource[]|\CurlHandle[]
59 */
60 private $handles = [];
61
62 /**
63 * @var string|null Owner signature of the proxy tunnels that pooled idle
64 * handles may still hold
65 */
66 private $proxyTunnelOwner;
67
68 /**
69 * @var bool Whether an in-domain handle has been pooled since the last purge
70 */
71 private $poolMayHoldTunnels = false;
72
73 /**
74 * @var int Total number of idle handles to keep in cache
75 */
76 private $maxHandles;
77
78 /**
79 * @var resource|\CurlShareHandle|null
80 */
81 private $shareHandle;
82
83 /**
84 * @var string
85 */
86 private $shareMode;
87
88 /**
89 * @var bool Whether the configured share handle may own a connection
90 * cache populated outside this factory
91 */
92 private $opaqueShareConnectionCache = false;
93
94 /**
95 * @param int $maxHandles Maximum number of idle handles.
96 * @param resource|\CurlShareHandle|CurlShareHandleState|null $shareHandle
97 */
98 public function __construct(int $maxHandles, string $shareMode = TransportSharing::NONE, $shareHandle = null)
99 {
100 $this->maxHandles = $maxHandles;
101 $this->shareMode = CurlShareHandleState::normalizeMode($shareMode, 'transport_sharing');
102
103 if ($shareHandle instanceof CurlShareHandleState) {
104 if ($shareHandle->mode !== $this->shareMode) {
105 throw new \InvalidArgumentException('The cURL share handle state mode does not match the configured transport sharing mode.');
106 }
107
108 // A Guzzle-created handler-lifetime state locks only DNS and TLS
109 // session data, so its handle can never own a connection cache.
110 $shareHandle = $shareHandle->handle;
111 } elseif ($shareHandle !== null) {
112 // An externally supplied handle's lock set and cached contents
113 // cannot be inspected from PHP, so it may own a connection cache
114 // populated outside this factory.
115 $this->opaqueShareConnectionCache = true;
116 }
117
118 if ($this->shareMode === TransportSharing::NONE && $shareHandle !== null) {
119 throw new \InvalidArgumentException('A cURL share handle cannot be provided when transport sharing is disabled.');
120 }
121
122 if ($this->shareMode !== TransportSharing::NONE && $shareHandle === null) {
123 throw new \InvalidArgumentException('A cURL share handle is required when transport sharing is enabled.');
124 }
125
126 if ($shareHandle !== null && !self::isCurlShareHandle($shareHandle)) {
127 throw new \InvalidArgumentException('A cURL share handle must be an instance of CurlShareHandle or a curl_share resource.');
128 }
129
130 $this->shareHandle = $shareHandle;
131 }
132
133 /**
134 * @param mixed $value
135 */
136 private static function isCurlShareHandle($value): bool
137 {
138 if (\PHP_VERSION_ID < 80000) {
139 return \is_resource($value) && \get_resource_type($value) === 'curl_share';
140 }
141
142 return $value instanceof \CurlShareHandle;
143 }
144
145 public function create(RequestInterface $request, array $options): EasyHandle
146 {
147 self::validateRequestUriScheme($request);
148
149 if (isset($options['on_trailers']) && !\is_callable($options['on_trailers'])) {
150 throw new \InvalidArgumentException('on_trailers must be callable');
151 }
152
153 $protocolVersion = $request->getProtocolVersion();
154
155 if ('' === $protocolVersion) {
156 \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.');
157
158 $protocolVersion = '1.1';
159 $request = Psr7\Utils::modifyRequest($request, ['version' => $protocolVersion]);
160 }
161
162 $multiplex = self::normalizeMultiplex($options);
163 $requiredMultiplex = \in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true);
164
165 if ($requiredMultiplex && isset($options['curl']) && \is_array($options['curl'])) {
166 $requiredModeConflicts = [
167 \CURLOPT_HTTP_VERSION => ['CURLOPT_HTTP_VERSION', 'the request protocol version'],
168 \CURLOPT_URL => ['CURLOPT_URL', 'the request URI'],
169 \CURLOPT_FOLLOWLOCATION => ['CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option'],
170 ];
171
172 foreach ($requiredModeConflicts as $option => [$name, $replacement]) {
173 if (\array_key_exists($option, $options['curl'])) {
174 // Key presence alone conflicts: whatever the raw value,
175 // it is a second authority over the protocol or route,
176 // applied after the required mode's decisions.
177 throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be required when the raw %s cURL option is set; remove the raw option and use %s instead.', $name, $replacement));
178 }
179 }
180 }
181
182 if ('2' === $protocolVersion || '2.0' === $protocolVersion) {
183 if (!CurlVersion::supportsHttp2()) {
184 if ($requiredMultiplex) {
185 throw new ConnectException('Required multiplexing needs libcurl 8.14.0 or newer built with HTTP/2 support.', $request);
186 }
187
188 throw new ConnectException('HTTP/2 is supported by the cURL handler, however libcurl is built without HTTP/2 support.', $request);
189 }
190 } elseif ('1.0' !== $protocolVersion && '1.1' !== $protocolVersion) {
191 throw new ConnectException(sprintf('HTTP/%s is not supported by the cURL handler.', $protocolVersion), $request);
192 }
193
194 if (isset($options['curl']['body_as_string'])) {
195 $options['_body_as_string'] = $options['curl']['body_as_string'];
196 unset($options['curl']['body_as_string']);
197 }
198
199 self::triggerUnsupportedRequestOptionDeprecations($options);
200 self::triggerUnsupportedCurlOptionDeprecations($options);
201 self::triggerConflictingCurlOptionDeprecations($options);
202
203 // Capture the managed Proxy-Authorization values before header
204 // serialization so they never enter the origin header list, and
205 // record whether a deprecated raw CURLOPT_HTTPHEADER value replaces
206 // every generated header, the managed values included. Key presence
207 // alone replaces: an empty or null raw value still suppresses the
208 // generated list.
209 $managedProxyAuthorization = self::managedProxyAuthorizationHeaderLines($request);
210 $rawHttpHeadersReplaceManaged = isset($options['curl'])
211 && \is_array($options['curl'])
212 && \array_key_exists(\CURLOPT_HTTPHEADER, $options['curl']);
213
214 $easy = new EasyHandle();
215 $easy->request = $request;
216 $easy->options = $options;
217 $conf = $this->getDefaultConf($easy);
218 $this->applyMethod($easy, $conf);
219 $this->applyHandlerOptions($easy, $conf);
220 $this->applyHeaders($easy, $conf);
221 unset($conf['_headers']);
222
223 // Add handler options from the request configuration options
224 if (isset($options['curl'])) {
225 $conf = \array_replace($conf, $options['curl']);
226 }
227
228 self::assertFinalProxyOptionTypes($conf, $requiredMultiplex && 'https' !== $request->getUri()->getScheme());
229 self::isolatePreProxyOnAffectedCurl($conf);
230 self::normalizeStringableProxyCredentialOptions($conf);
231
232 if ($requiredMultiplex) {
233 self::assertRequiredMultiplexRouteDirect($easy, $conf);
234 self::assertRequiredMultiplexAuthSupported($conf);
235 }
236
237 self::normalizeCurlHeaderOptions($conf);
238 self::applyProxyAuthorizationHeaderHandling($request, $conf);
239 self::applyManagedProxyAuthorization($request, $conf, $managedProxyAuthorization, $rawHttpHeadersReplaceManaged);
240 // Validate the appended managed lines too: a custom RequestInterface
241 // can bypass a normal PSR-7 implementation's header validation.
242 self::normalizeCurlHeaderOptions($conf);
243 $this->rejectRequestLevelShareConflict($options);
244 self::rejectRequestLevelShareWithProxyAuth($request, $options, $conf);
245
246 if ($this->shareHandle !== null) {
247 // Conservative blanket mode: a configured share handle hides the
248 // pooled connections' provenance, so sectioned reuse cannot reason
249 // about them.
250 self::forceFreshConnectionForAuthenticatedProxy($request, $conf);
251 $this->isolateOpaqueShareAnonymousProxyTunnel($request, $conf);
252 } else {
253 $signature = self::proxyTunnelSignature($request, $conf);
254 $easy->proxyTunnelSignature = $signature;
255 if ($signature !== null && $signature !== $this->proxyTunnelOwner) {
256 if ($this->poolMayHoldTunnels) {
257 // Pooled idle handles may hold a different owner's tunnel.
258 $this->discardIdleHandles();
259 $this->poolMayHoldTunnels = false;
260 }
261 // The first in-domain owner latches without purging: the pool
262 // provably holds no in-domain tunnel yet.
263 $this->proxyTunnelOwner = $signature;
264 }
265 }
266
267 $easy->effectiveProxy = self::getEffectiveProxy($conf);
268
269 $conf[\CURLOPT_HEADERFUNCTION] = $this->createHeaderFn($easy);
270 if ($this->shareHandle !== null) {
271 if (!\defined('CURLOPT_SHARE')) {
272 throw new \InvalidArgumentException('The configured cURL share handle requires CURLOPT_SHARE, but it is not available in the installed PHP cURL extension.');
273 }
274
275 $conf[(int) \constant('CURLOPT_SHARE')] = $this->shareHandle;
276 }
277
278 if (\defined('CURLOPT_PIPEWAIT')) {
279 $easy->usesPipewait = !empty($conf[(int) \constant('CURLOPT_PIPEWAIT')]);
280 }
281
282 $handle = $this->handles ? \array_pop($this->handles) : \curl_init();
283 if (false === $handle) {
284 throw new \RuntimeException('Can not initialize cURL handle.');
285 }
286 $easy->handle = $handle;
287
288 try {
289 $this->applyCurlOptions($handle, $conf);
290 } catch (\Throwable $e) {
291 if (PHP_VERSION_ID < 80000 && \is_resource($handle)) {
292 \curl_close($handle);
293 }
294 unset($easy->handle);
295
296 throw $e;
297 }
298
299 return $easy;
300 }
301
302 /**
303 * @param resource|\CurlHandle $handle
304 * @param array<int|string, mixed> $conf
305 */
306 private function applyCurlOptions($handle, array $conf): void
307 {
308 foreach ($conf as $option => $value) {
309 if (!\is_int($option)) {
310 throw new \InvalidArgumentException(\sprintf(
311 'Invalid cURL option %s.',
312 self::formatCurlOption($option)
313 ));
314 }
315
316 try {
317 $success = curl_setopt($handle, $option, $value);
318 } catch (\Throwable $e) {
319 throw new \InvalidArgumentException(
320 \sprintf(
321 'Unable to set cURL option %s: %s',
322 self::formatCurlOption($option),
323 $e->getMessage()
324 ),
325 0,
326 $e
327 );
328 }
329
330 if (!$success) {
331 throw new \InvalidArgumentException(\sprintf(
332 'Unable to set cURL option %s.',
333 self::formatCurlOption($option)
334 ));
335 }
336 }
337 }
338
339 /**
340 * @param array<int|string, mixed> $conf
341 */
342 private static function normalizeStringableProxyCredentialOptions(array &$conf): void
343 {
344 foreach (self::STRINGABLE_PROXY_CREDENTIAL_OPTIONS as $name) {
345 if (!\defined($name)) {
346 continue;
347 }
348
349 $option = (int) \constant($name);
350 if (!isset($conf[$option]) || !\is_object($conf[$option]) || !\method_exists($conf[$option], '__toString')) {
351 continue;
352 }
353
354 try {
355 $conf[$option] = (string) $conf[$option];
356 } catch (\Throwable $e) {
357 // Wrap the failure exactly as applyCurlOptions() does for a
358 // value that cannot be applied.
359 throw new \InvalidArgumentException(
360 \sprintf(
361 'Unable to set cURL option %s: %s',
362 self::formatCurlOption($option),
363 $e->getMessage()
364 ),
365 0,
366 $e
367 );
368 }
369 }
370 }
371
372 private function rejectRequestLevelShareConflict(array $options): void
373 {
374 if ($this->shareHandle === null) {
375 return;
376 }
377
378 if (
379 !\defined('CURLOPT_SHARE')
380 || !isset($options['curl'])
381 || !\is_array($options['curl'])
382 || !\array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl'])
383 ) {
384 return;
385 }
386
387 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with configured transport sharing.');
388 }
389
390 private static function normalizeMultiplex(array $options): ?string
391 {
392 $multiplex = $options['multiplex'] ?? null;
393
394 if ($multiplex === null) {
395 // Absent/null leaves multiplexing to libcurl: no CURLOPT_PIPEWAIT
396 // is written and no guarantees apply.
397 return null;
398 }
399
400 if (!\in_array($multiplex, [Multiplexing::NONE, Multiplexing::EAGER, Multiplexing::WAIT, Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
401 throw new \InvalidArgumentException(\sprintf(
402 'The "multiplex" option must be null or a GuzzleHttp\\Multiplexing::* constant; received %s.',
403 \get_debug_type($multiplex)
404 ));
405 }
406
407 return $multiplex;
408 }
409
410 private static function assertRequiredMultiplexSupported(EasyHandle $easy): void
411 {
412 if (!CurlVersion::supportsRequiredMultiplex()) {
413 throw new ConnectException('Required multiplexing needs libcurl 8.14.0 or newer built with HTTP/2 support.', $easy->request);
414 }
415 }
416
417 /**
418 * Required multiplexing sends cleartext requests with HTTP/2 prior
419 * knowledge, which an HTTP proxy hop silently downgrades, so the request
420 * must reach the origin directly. The check runs against the final
421 * merged cURL configuration because deprecated raw proxy options are
422 * applied after Guzzle's own decisions and may add, replace, or disable
423 * the selected proxy. Value types that ext-curl would coerce are
424 * rejected as ambiguous, and only the exact CURLOPT_NOPROXY wildcard '*'
425 * counts as disabling the primary proxy and pre-proxy: host-specific
426 * patterns are conservatively treated as leaving them active.
427 *
428 * @param array<int|string, mixed> $conf
429 */
430 private static function assertRequiredMultiplexRouteDirect(EasyHandle $easy, array $conf): void
431 {
432 if ('https' === $easy->request->getUri()->getScheme()) {
433 return;
434 }
435
436 $proxyOptions = [\CURLOPT_PROXY => 'CURLOPT_PROXY'];
437 if (\defined('CURLOPT_NOPROXY')) {
438 $proxyOptions[(int) \constant('CURLOPT_NOPROXY')] = 'CURLOPT_NOPROXY';
439 }
440 if (\defined('CURLOPT_PRE_PROXY')) {
441 $proxyOptions[(int) \constant('CURLOPT_PRE_PROXY')] = 'CURLOPT_PRE_PROXY';
442 }
443
444 foreach ($proxyOptions as $option => $name) {
445 if (\array_key_exists($option, $conf) && !\is_string($conf[$option])) {
446 throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be required when the final %s cURL option value is not a string.', $name));
447 }
448 }
449
450 if (\defined('CURLOPT_NOPROXY') && ($conf[(int) \constant('CURLOPT_NOPROXY')] ?? null) === '*') {
451 // libcurl's exact wildcard disables the primary proxy and the
452 // pre-proxy together, leaving a direct route.
453 return;
454 }
455
456 if (self::getEffectiveProxy($conf) !== null
457 || (\defined('CURLOPT_PRE_PROXY') && ($conf[(int) \constant('CURLOPT_PRE_PROXY')] ?? '') !== '')
458 ) {
459 throw new ConnectException('Required multiplexing cannot be guaranteed for cleartext requests sent through a proxy.', $easy->request);
460 }
461 }
462
463 /**
464 * libcurl forces NTLM-authenticated transfers onto HTTP/1.1: when the
465 * server picks NTLM from the offered mask, the connection is closed and
466 * the request is retried over HTTP/1.1 whatever HTTP version was asked
467 * for, silently defeating the required protocol guarantee on both
468 * cleartext and TLS routes. The final merged mask is checked so the
469 * deprecated "auth" request option and the raw CURLOPT_HTTPAUTH cURL
470 * option are both covered, and any mask permitting NTLM, such as
471 * CURLAUTH_ANY, is rejected because the selection is server-controlled.
472 *
473 * @param array<int|string, mixed> $conf
474 */
475 private static function assertRequiredMultiplexAuthSupported(array $conf): void
476 {
477 if (!\array_key_exists(\CURLOPT_HTTPAUTH, $conf)) {
478 return;
479 }
480
481 $auth = $conf[\CURLOPT_HTTPAUTH];
482 if (!\is_scalar($auth)) {
483 throw new \InvalidArgumentException('The "multiplex" request option cannot be required when the final CURLOPT_HTTPAUTH cURL option value is not an integer.');
484 }
485
486 $ntlmBits = \CURLAUTH_NTLM;
487 if (\defined('CURLAUTH_NTLM_WB')) {
488 $ntlmBits |= (int) \constant('CURLAUTH_NTLM_WB');
489 }
490
491 if (((int) $auth & $ntlmBits) !== 0) {
492 throw new \InvalidArgumentException('The "multiplex" request option cannot be required when the final CURLOPT_HTTPAUTH cURL option value permits NTLM; libcurl retries NTLM authentication over HTTP/1.1.');
493 }
494 }
495
496 /**
497 * @param mixed $proxyConf
498 */
499 private static function assertResolvedProxySupported(RequestInterface $request, $proxyConf): void
500 {
501 if (!\is_string($proxyConf) || $proxyConf === '') {
502 return;
503 }
504
505 $scheme = self::proxyScheme($proxyConf);
506 if ($scheme !== null && \preg_match('/^[a-z][a-z0-9.+-]*$/D', $scheme) !== 1) {
507 throw new RequestException('The proxy URL is malformed.', $request);
508 }
509
510 if ($scheme === 'https' && !CurlVersion::supportsHttpsProxy()) {
511 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.', $request);
512 }
513 }
514
515 /**
516 * @return array{0: mixed, 1: string}
517 */
518 private static function resolveProxy(RequestInterface $request, array $options): array
519 {
520 $proxyConf = null;
521 $noProxyConf = '';
522
523 if (isset($options['proxy'])) {
524 if (!\is_array($options['proxy'])) {
525 $proxyConf = $options['proxy'];
526 } else {
527 $scheme = $request->getUri()->getScheme();
528 if (isset($options['proxy'][$scheme])) {
529 if (
530 isset($options['proxy']['no'])
531 && Utils::isUriInNoProxy($request->getUri(), $options['proxy']['no'])
532 ) {
533 $proxyConf = '';
534 $noProxyConf = '*';
535 } else {
536 $proxyConf = $options['proxy'][$scheme];
537 }
538 }
539 }
540 }
541
542 if ($proxyConf === null) {
543 $proxyConf = ProxyEnvironment::getProxyForScheme($request->getUri()->getScheme());
544 if ($proxyConf === null) {
545 $proxyConf = '';
546 } elseif (
547 ($noProxy = ProxyEnvironment::getNoProxy()) !== null
548 && Utils::isUriInNoProxy($request->getUri(), ProxyEnvironment::splitNoProxy($noProxy))
549 ) {
550 $proxyConf = '';
551 $noProxyConf = '*';
552 }
553 }
554
555 return [$proxyConf, $noProxyConf];
556 }
557
558 /**
559 * @param array<int|string, mixed> $conf
560 */
561 private static function rejectRequestLevelShareWithProxyAuth(RequestInterface $request, array $options, array $conf): void
562 {
563 if (!self::hasRequestLevelCurlShare($options)) {
564 return;
565 }
566
567 $proxy = self::getEffectiveProxy($conf);
568 if ($proxy === null) {
569 return;
570 }
571
572 // An external share handle may pool SOCKS connections where no section
573 // signature can reach them. On affected libcurl, even an anonymous
574 // request could inherit authenticated state already in that pool.
575 if (self::isSocksProxy($proxy, $conf)) {
576 if (!CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse()) {
577 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with SOCKS proxy configuration on libcurl before 7.69.0; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
578 }
579
580 if (self::hasAuthenticatedSocksProxyState($proxy, $conf)) {
581 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with authenticated SOCKS proxy configuration; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
582 }
583 }
584
585 if (
586 !self::usesProxyTunnel($request, $conf)
587 || !self::isHttpProxyForConnectionReuse($proxy, $conf)
588 ) {
589 return;
590 }
591
592 if (self::hasAuthenticatedHttpProxyState($proxy, $conf)) {
593 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.');
594 }
595
596 // From libcurl 7.57.0 the external share can also own a connection
597 // cache seeded outside Guzzle with tunnel identity libcurl cannot
598 // key, so anonymous tunnels are rejected there too.
599 if (CurlVersion::supportsShareConnectionCaches()) {
600 throw new \InvalidArgumentException('The request-level CURLOPT_SHARE cURL option cannot be combined with HTTP/HTTPS proxy tunnel configuration on libcurl 7.57.0 or newer; use Guzzle-managed "transport_sharing" or a custom handler/factory instead.');
601 }
602 }
603
604 private static function hasRequestLevelCurlShare(array $options): bool
605 {
606 return \defined('CURLOPT_SHARE')
607 && isset($options['curl'])
608 && \is_array($options['curl'])
609 && \array_key_exists((int) \constant('CURLOPT_SHARE'), $options['curl']);
610 }
611
612 /**
613 * @param array<int|string, mixed> $conf
614 */
615 private static function hasAuthenticatedHttpProxyState(string $proxy, array $conf): bool
616 {
617 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
618 $proxyParts = \parse_url($proxyForParsing);
619
620 if (
621 \is_array($proxyParts)
622 && (\array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts))
623 ) {
624 return true;
625 }
626
627 if (self::hasCurlProxyCredentials($conf)) {
628 return true;
629 }
630
631 if (self::hasCurlProxyAuthorizationHeader($conf)) {
632 return true;
633 }
634
635 $httpHeaders = $conf[\CURLOPT_HTTPHEADER] ?? [];
636 if (\is_array($httpHeaders) && self::proxyAuthorizationHeaderValuesFromList($httpHeaders) !== []) {
637 return true;
638 }
639
640 return self::hasCurlProxyTlsCredentials($conf);
641 }
642
643 /**
644 * @param int|string $option
645 */
646 private static function formatCurlOption($option): string
647 {
648 if (!\is_int($option)) {
649 return \sprintf('"%s"', $option);
650 }
651
652 static $names = null;
653
654 if (null === $names) {
655 $names = [];
656 foreach (\get_defined_constants(true)['curl'] ?? [] as $name => $value) {
657 if (\is_int($value) && \strpos($name, 'CURLOPT_') === 0 && !isset($names[$value])) {
658 $names[$value] = $name;
659 }
660 }
661 }
662
663 if (isset($names[$option])) {
664 return \sprintf('%s (%d)', $names[$option], $option);
665 }
666
667 return (string) $option;
668 }
669
670 private static function triggerConflictingCurlOptionDeprecations(array $options): void
671 {
672 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
673 return;
674 }
675
676 $conflictingOptions = self::conflictingCurlOptions();
677 $sinceOverrides = self::conflictingCurlOptionSinceOverrides();
678
679 foreach ($options['curl'] as $option => $_) {
680 if (!\array_key_exists($option, $conflictingOptions)) {
681 continue;
682 }
683
684 $name = self::formatCurlOption($option);
685 $replacement = $conflictingOptions[$option];
686 $since = $sinceOverrides[$option] ?? '7.11';
687 if ($replacement !== null) {
688 \trigger_deprecation(
689 'guzzlehttp/guzzle',
690 $since,
691 \sprintf(
692 '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.',
693 $name,
694 $replacement
695 )
696 );
697
698 continue;
699 }
700
701 \trigger_deprecation(
702 'guzzlehttp/guzzle',
703 $since,
704 \sprintf(
705 '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.',
706 $name
707 )
708 );
709 }
710 }
711
712 private static function triggerUnsupportedCurlOptionDeprecations(array $options): void
713 {
714 if (!isset($options['curl']) || !\is_array($options['curl']) || $options['curl'] === []) {
715 return;
716 }
717
718 if (
719 \defined('CURLOPT_PROXYHEADER')
720 && \array_key_exists((int) \constant('CURLOPT_PROXYHEADER'), $options['curl'])
721 && !CurlVersion::supportsProxyHeaderSeparation()
722 ) {
723 \trigger_deprecation(
724 'guzzlehttp/guzzle',
725 '7.15',
726 \sprintf(
727 'Passing %s in the "curl" request option on a build without proxy header separation support is deprecated; guzzlehttp/guzzle 8.0 will reject this configuration because proxy headers require libcurl 7.37.0 or newer built with proxy header separation support.',
728 self::formatCurlOption((int) \constant('CURLOPT_PROXYHEADER'))
729 )
730 );
731 }
732
733 $supportedOptions = self::supportedCurlOptions();
734 $conflictingOptions = self::conflictingCurlOptions();
735
736 foreach ($options['curl'] as $option => $_) {
737 if (
738 !\is_int($option)
739 || \array_key_exists($option, $supportedOptions)
740 || \array_key_exists($option, $conflictingOptions)
741 ) {
742 continue;
743 }
744
745 \trigger_deprecation(
746 'guzzlehttp/guzzle',
747 '7.12',
748 \sprintf(
749 '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.',
750 self::formatCurlOption($option)
751 )
752 );
753 }
754 }
755
756 private static function triggerUnsupportedRequestOptionDeprecations(array $options): void
757 {
758 if (\array_key_exists('stream_context', $options)) {
759 \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.');
760 }
761 }
762
763 /**
764 * @return array<int, string|null>
765 */
766 private static function conflictingCurlOptions(): array
767 {
768 static $options = null;
769
770 if ($options !== null) {
771 return $options;
772 }
773
774 $options = [];
775
776 self::addConflictingCurlOption($options, 'CURLOPT_SHARE', 'the "transport_sharing" client option or cURL handler option');
777 self::addConflictingCurlOption($options, 'CURLOPT_URL', 'the request URI');
778 self::addConflictingCurlOption($options, 'CURLOPT_PORT', 'the request URI');
779 self::addConflictingCurlOption($options, 'CURLOPT_CUSTOMREQUEST', 'the request method');
780 self::addConflictingCurlOption($options, 'CURLOPT_HTTPGET', 'the request method');
781 self::addConflictingCurlOption($options, 'CURLOPT_POST', 'the request method and body');
782 self::addConflictingCurlOption($options, 'CURLOPT_PUT', 'the request method and body');
783 self::addConflictingCurlOption($options, 'CURLOPT_NOBODY', 'the request method');
784 self::addConflictingCurlOption($options, 'CURLOPT_UPLOAD', 'the request body');
785 self::addConflictingCurlOption($options, 'CURLOPT_POSTFIELDS', 'the request body');
786 self::addConflictingCurlOption($options, 'CURLOPT_READFUNCTION', 'the request body');
787 self::addConflictingCurlOption($options, 'CURLOPT_READDATA', 'the request body');
788 self::addConflictingCurlOption($options, 'CURLOPT_INFILE', 'the request body');
789 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE', 'the request body');
790 self::addConflictingCurlOption($options, 'CURLOPT_INFILESIZE_LARGE', 'the request body');
791 self::addConflictingCurlOption($options, 'CURLOPT_HTTPHEADER', 'the request headers');
792 self::addConflictingCurlOption($options, 'CURLOPT_USERAGENT', 'the request headers');
793 self::addConflictingCurlOption($options, 'CURLOPT_REFERER', 'the request headers');
794 self::addConflictingCurlOption($options, 'CURLOPT_HEADERFUNCTION', 'the "on_headers" request option');
795 self::addConflictingCurlOption($options, 'CURLOPT_WRITEFUNCTION', 'the "sink" request option');
796 self::addConflictingCurlOption($options, 'CURLOPT_FILE', 'the "sink" request option');
797 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT', 'the "timeout" request option');
798 self::addConflictingCurlOption($options, 'CURLOPT_TIMEOUT_MS', 'the "timeout" request option');
799 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT', 'the "connect_timeout" request option');
800 self::addConflictingCurlOption($options, 'CURLOPT_CONNECTTIMEOUT_MS', 'the "connect_timeout" request option');
801 self::addConflictingCurlOption($options, 'CURLOPT_NOSIGNAL', 'the "timeout" or "connect_timeout" request option');
802 self::addConflictingCurlOption($options, 'CURLOPT_NOPROGRESS', 'the "progress" request option');
803 self::addConflictingCurlOption($options, 'CURLOPT_PROGRESSFUNCTION', 'the "progress" request option');
804 self::addConflictingCurlOption($options, 'CURLOPT_XFERINFOFUNCTION', 'the "progress" request option');
805 self::addConflictingCurlOption($options, 'CURLOPT_VERBOSE', 'the "debug" request option');
806 self::addConflictingCurlOption($options, 'CURLOPT_STDERR', 'the "debug" request option');
807 self::addConflictingCurlOption($options, 'CURLOPT_PROXY', 'the "proxy" request option');
808 self::addConflictingCurlOption($options, 'CURLOPT_NOPROXY', 'the "proxy" request option');
809 self::addConflictingCurlOption($options, 'CURLOPT_PROXYTYPE', 'the "proxy" request option with a scheme-prefixed URL');
810 self::addConflictingCurlOption($options, 'CURLOPT_FOLLOWLOCATION', 'the "allow_redirects" request option');
811 self::addConflictingCurlOption($options, 'CURLOPT_MAXREDIRS', 'the "allow_redirects" request option');
812 self::addConflictingCurlOption($options, 'CURLOPT_POSTREDIR', 'the "allow_redirects" request option');
813 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS', 'the "allow_redirects" request option');
814 self::addConflictingCurlOption($options, 'CURLOPT_REDIR_PROTOCOLS_STR', 'the "allow_redirects" request option');
815 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS', 'the "protocols" request option');
816 self::addConflictingCurlOption($options, 'CURLOPT_PROTOCOLS_STR', 'the "protocols" request option');
817 self::addConflictingCurlOption($options, 'CURLOPT_HTTP_VERSION', 'the request protocol version');
818 self::addConflictingCurlOption($options, 'CURLOPT_PIPEWAIT', 'the "multiplex" request option');
819 self::addConflictingCurlOption($options, 'CURLOPT_IPRESOLVE', 'the "force_ip_resolve" request option');
820 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYPEER', 'the "verify" request option');
821 self::addConflictingCurlOption($options, 'CURLOPT_SSL_VERIFYHOST', 'the "verify" request option');
822 self::addConflictingCurlOption($options, 'CURLOPT_CAINFO', 'the "verify" request option');
823 self::addConflictingCurlOption($options, 'CURLOPT_CAPATH', 'the "verify" request option');
824 self::addConflictingCurlOption($options, 'CURLOPT_SSLVERSION', 'the "crypto_method" or "crypto_method_max" request option');
825 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERT', 'the "cert" request option');
826 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTPASSWD', 'the "cert" request option');
827 self::addConflictingCurlOption($options, 'CURLOPT_SSLCERTTYPE', 'the "cert_type" request option');
828 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEY', 'the "ssl_key" request option');
829 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYPASSWD', 'the "ssl_key" request option');
830 self::addConflictingCurlOption($options, 'CURLOPT_KEYPASSWD', 'the "ssl_key" request option');
831 self::addConflictingCurlOption($options, 'CURLOPT_SSLKEYTYPE', 'the "ssl_key_type" request option');
832 self::addConflictingCurlOption($options, 'CURLOPT_COOKIE', 'the "Cookie" request header or Guzzle cookie middleware');
833 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEFILE', 'Guzzle cookie middleware');
834 self::addConflictingCurlOption($options, 'CURLOPT_COOKIEJAR', 'Guzzle cookie middleware');
835 self::addConflictingCurlOption($options, 'CURLOPT_COOKIELIST', 'Guzzle cookie middleware');
836 self::addConflictingCurlOption($options, 'CURLOPT_COOKIESESSION', 'Guzzle cookie middleware');
837
838 return $options;
839 }
840
841 /**
842 * @return array<int, string>
843 */
844 private static function conflictingCurlOptionSinceOverrides(): array
845 {
846 static $options = null;
847
848 if ($options !== null) {
849 return $options;
850 }
851
852 $options = [];
853
854 if (\defined('CURLOPT_PROXYTYPE')) {
855 $options[\CURLOPT_PROXYTYPE] = '7.12';
856 }
857
858 if (\defined('CURLOPT_PIPEWAIT')) {
859 $options[\CURLOPT_PIPEWAIT] = '7.14';
860 }
861
862 return $options;
863 }
864
865 /**
866 * @return array<int, true>
867 */
868 private static function supportedCurlOptions(): array
869 {
870 static $options = null;
871
872 if ($options !== null) {
873 return $options;
874 }
875
876 $options = [];
877
878 self::addSupportedCurlOption($options, 'CURLOPT_ADDRESS_SCOPE');
879 self::addSupportedCurlOption($options, 'CURLOPT_CERTINFO');
880 self::addSupportedCurlOption($options, 'CURLOPT_CONNECT_TO');
881 self::addSupportedCurlOption($options, 'CURLOPT_DNS_CACHE_TIMEOUT');
882 self::addSupportedCurlOption($options, 'CURLOPT_DNS_INTERFACE');
883 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP4');
884 self::addSupportedCurlOption($options, 'CURLOPT_DNS_LOCAL_IP6');
885 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SERVERS');
886 self::addSupportedCurlOption($options, 'CURLOPT_DNS_SHUFFLE_ADDRESSES');
887 self::addSupportedCurlOption($options, 'CURLOPT_ENCODING');
888 self::addSupportedCurlOption($options, 'CURLOPT_FORBID_REUSE');
889 self::addSupportedCurlOption($options, 'CURLOPT_FRESH_CONNECT');
890 self::addSupportedCurlOption($options, 'CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS');
891 self::addSupportedCurlOption($options, 'CURLOPT_HTTPAUTH');
892 self::addSupportedCurlOption($options, 'CURLOPT_INTERFACE');
893 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORT');
894 self::addSupportedCurlOption($options, 'CURLOPT_LOCALPORTRANGE');
895 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_LIMIT');
896 self::addSupportedCurlOption($options, 'CURLOPT_LOW_SPEED_TIME');
897 self::addSupportedCurlOption($options, 'CURLOPT_MAXAGE_CONN');
898 self::addSupportedCurlOption($options, 'CURLOPT_MAXCONNECTS');
899 self::addSupportedCurlOption($options, 'CURLOPT_MAXLIFETIME_CONN');
900 self::addSupportedCurlOption($options, 'CURLOPT_HTTPPROXYTUNNEL');
901 self::addSupportedCurlOption($options, 'CURLOPT_PREREQFUNCTION');
902 self::addSupportedCurlOption($options, 'CURLOPT_PROXYHEADER');
903 self::addSupportedCurlOption($options, 'CURLOPT_PROXYUSERPWD');
904 self::addSupportedCurlOption($options, 'CURLOPT_RESOLVE');
905 self::addSupportedCurlOption($options, 'CURLOPT_SSL_CIPHER_LIST');
906 self::addSupportedCurlOption($options, 'CURLOPT_SSL_EC_CURVES');
907 self::addSupportedCurlOption($options, 'CURLOPT_TCP_FASTOPEN');
908 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPALIVE');
909 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPIDLE');
910 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPINTVL');
911 self::addSupportedCurlOption($options, 'CURLOPT_TCP_KEEPCNT');
912 self::addSupportedCurlOption($options, 'CURLOPT_TCP_NODELAY');
913 self::addSupportedCurlOption($options, 'CURLOPT_TLS13_CIPHERS');
914 self::addSupportedCurlOption($options, 'CURLOPT_UNIX_SOCKET_PATH');
915 self::addSupportedCurlOption($options, 'CURLOPT_USERPWD');
916
917 return $options;
918 }
919
920 /**
921 * @param array<int, true> $options
922 */
923 private static function addSupportedCurlOption(array &$options, string $constant): void
924 {
925 if (!\defined($constant)) {
926 return;
927 }
928
929 $value = \constant($constant);
930 if (\is_int($value)) {
931 $options[$value] = true;
932 }
933 }
934
935 /**
936 * @param array<int, string|null> $options
937 */
938 private static function addConflictingCurlOption(array &$options, string $constant, ?string $replacement): void
939 {
940 if (!\defined($constant)) {
941 return;
942 }
943
944 $value = \constant($constant);
945 if (\is_int($value)) {
946 $options[$value] = $replacement;
947 }
948 }
949
950 public function release(EasyHandle $easy): void
951 {
952 $resource = $easy->handle;
953 unset($easy->handle);
954
955 if (
956 \count($this->handles) >= $this->maxHandles
957 || ($easy->proxyTunnelSignature !== null && $easy->proxyTunnelSignature !== $this->proxyTunnelOwner)
958 ) {
959 // Pool is full, or this handle belongs to a superseded tunnel
960 // owner (an async create/release overlap can hand a stale-owner
961 // handle back after a purge) - drop it instead of pooling it.
962 if (PHP_VERSION_ID < 80000) {
963 \curl_close($resource);
964 }
965
966 return;
967 }
968
969 if ($easy->proxyTunnelSignature !== null) {
970 // A pooled handle now carries the current owner's tunnel.
971 $this->poolMayHoldTunnels = true;
972 }
973
974 // Remove all callback functions as they can hold onto references and
975 // are not cleaned up by curl_reset. Using curl_setopt_array does not
976 // work for some reason, so removing each one individually.
977 \curl_setopt($resource, \CURLOPT_HEADERFUNCTION, null);
978 \curl_setopt($resource, \CURLOPT_READFUNCTION, null);
979 \curl_setopt($resource, \CURLOPT_WRITEFUNCTION, null);
980 \curl_setopt($resource, \CURLOPT_PROGRESSFUNCTION, null);
981
982 if (\defined('CURLOPT_PREREQFUNCTION')) {
983 \curl_setopt($resource, (int) \constant('CURLOPT_PREREQFUNCTION'), null);
984 }
985
986 \curl_reset($resource);
987 $this->handles[] = $resource;
988 }
989
990 /**
991 * Completes a cURL transaction, either returning a response promise or a
992 * rejected promise.
993 *
994 * @param callable(RequestInterface, array): PromiseInterface $handler
995 * @param CurlFactoryInterface $factory Dictates how the handle is released
996 */
997 public static function finish(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface
998 {
999 if (isset($easy->options['on_stats'])) {
1000 try {
1001 self::invokeStats($easy);
1002 } catch (\Throwable $e) {
1003 try {
1004 $factory->release($easy);
1005 } catch (\Throwable $releaseFailure) {
1006 // Keep the on_stats throwable as the visible failure.
1007 }
1008
1009 throw $e;
1010 }
1011 }
1012
1013 if (!$easy->response || $easy->errno) {
1014 return self::finishError($handler, $easy, $factory);
1015 }
1016
1017 // Return the response if it is present and there is no error.
1018 $factory->release($easy);
1019
1020 // Rewind the body of the response if possible.
1021 $body = $easy->response->getBody();
1022 if ($body->isSeekable()) {
1023 $body->rewind();
1024 }
1025
1026 if (isset($easy->options['on_trailers'])) {
1027 try {
1028 ($easy->options['on_trailers'])(self::headersFromTrailerLines($easy->trailers), $easy->response);
1029 } catch (\Throwable $e) {
1030 return P\Create::rejectionFor(
1031 new RequestException(
1032 'An error was encountered during the on_trailers event',
1033 $easy->request,
1034 $easy->response,
1035 $e
1036 )
1037 );
1038 }
1039 }
1040
1041 return new FulfilledPromise($easy->response);
1042 }
1043
1044 private static function invokeStats(EasyHandle $easy): void
1045 {
1046 $curlStats = \curl_getinfo($easy->handle);
1047 $curlStats['appconnect_time'] = \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME);
1048 $stats = new TransferStats(
1049 $easy->request,
1050 $easy->response,
1051 $curlStats['total_time'],
1052 $easy->errno,
1053 $curlStats
1054 );
1055 ($easy->options['on_stats'])($stats);
1056 }
1057
1058 /**
1059 * @param callable(RequestInterface, array): PromiseInterface $handler
1060 */
1061 private static function finishError(callable $handler, EasyHandle $easy, CurlFactoryInterface $factory): PromiseInterface
1062 {
1063 // Get error information and release the handle to the factory.
1064 $ctx = [
1065 'errno' => $easy->errno,
1066 'error' => \curl_error($easy->handle),
1067 'appconnect_time' => \curl_getinfo($easy->handle, \CURLINFO_APPCONNECT_TIME),
1068 ] + \curl_getinfo($easy->handle);
1069 $ctx[self::CURL_VERSION_STR] = CurlVersion::getVersion() ?? '';
1070 $factory->release($easy);
1071
1072 // Retry when nothing is present or when curl failed to rewind.
1073 if (empty($easy->options['_err_message']) && (!$easy->errno || $easy->errno == 65)) {
1074 return self::retryFailedRewind($handler, $easy, $ctx);
1075 }
1076
1077 return self::createRejection($easy, $ctx);
1078 }
1079
1080 private static function createRejection(EasyHandle $easy, array $ctx): PromiseInterface
1081 {
1082 static $connectionErrors = [
1083 \CURLE_OPERATION_TIMEOUTED => true,
1084 \CURLE_COULDNT_RESOLVE_HOST => true,
1085 \CURLE_COULDNT_CONNECT => true,
1086 \CURLE_SSL_CONNECT_ERROR => true,
1087 \CURLE_GOT_NOTHING => true,
1088 ];
1089
1090 $uri = $easy->request->getUri();
1091
1092 // Redact the native error before it reaches any exception so the
1093 // handler context matches the sanitized exception message.
1094 $ctx['error'] = self::sanitizeCurlError((string) ($ctx['error'] ?? ''), $uri, $easy->effectiveProxy);
1095
1096 if ($easy->createResponseException) {
1097 return P\Create::rejectionFor(
1098 new RequestException(
1099 'An error was encountered while creating the response',
1100 $easy->request,
1101 null,
1102 $easy->createResponseException,
1103 $ctx
1104 )
1105 );
1106 }
1107
1108 // If an exception was encountered during the onHeaders event, then
1109 // return a rejected promise that wraps that exception.
1110 if ($easy->onHeadersException) {
1111 return P\Create::rejectionFor(
1112 new RequestException(
1113 'An error was encountered during the on_headers event',
1114 $easy->request,
1115 $easy->response,
1116 $easy->onHeadersException,
1117 $ctx
1118 )
1119 );
1120 }
1121
1122 $sanitizedError = $ctx['error'];
1123
1124 $message = \sprintf(
1125 'cURL error %s: %s (%s)',
1126 $ctx['errno'],
1127 $sanitizedError,
1128 'see https://curl.se/libcurl/c/libcurl-errors.html'
1129 );
1130
1131 if ('' !== $sanitizedError) {
1132 $redactedUriString = Psr7\Utils::redactUserInfo($uri)->__toString();
1133 if ($redactedUriString !== '' && false === \strpos($sanitizedError, $redactedUriString)) {
1134 $message .= \sprintf(' for %s', $redactedUriString);
1135 }
1136 }
1137
1138 // Create a connection exception if it was a specific error code.
1139 $error = isset($connectionErrors[$easy->errno])
1140 ? new ConnectException($message, $easy->request, null, $ctx)
1141 : new RequestException($message, $easy->request, $easy->response, null, $ctx);
1142
1143 return P\Create::rejectionFor($error);
1144 }
1145
1146 private static function sanitizeCurlError(string $error, UriInterface $uri, ?string $proxy = null): string
1147 {
1148 if ('' === $error) {
1149 return $error;
1150 }
1151
1152 $error = self::redactProxyUserInfo($error, $proxy);
1153
1154 $baseUri = $uri->withQuery('')->withFragment('');
1155 $baseUriString = $baseUri->__toString();
1156
1157 if ('' === $baseUriString) {
1158 return $error;
1159 }
1160
1161 $redactedUriString = Psr7\Utils::redactUserInfo($baseUri)->__toString();
1162
1163 return str_replace($baseUriString, $redactedUriString, $error);
1164 }
1165
1166 private static function redactProxyUserInfo(string $error, ?string $proxy): string
1167 {
1168 if ($proxy === null || $proxy === '' || \strpos($proxy, '@') === false) {
1169 return $error;
1170 }
1171
1172 // The error message embeds the proxy string exactly as configured, so
1173 // the userinfo needle is taken verbatim from the raw string:
1174 // parse_url() and Psr7\Uri normalize the components, e.g. by rewriting
1175 // raw control bytes to '_', which could make the replacement miss.
1176 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
1177 $remainder = \substr($proxyForParsing, \strpos($proxyForParsing, '://') + 3);
1178
1179 if (\parse_url($proxyForParsing) === false) {
1180 // Raw '/', '?', or '#' separators may sit inside the credentials
1181 // of a proxy that defeats parse_url(), so the redaction cannot
1182 // stop at the apparent authority.
1183 $atPosition = \strrpos($remainder, '@');
1184
1185 if ($atPosition === false || $atPosition === 0) {
1186 return $error;
1187 }
1188
1189 return \str_replace(\substr($remainder, 0, $atPosition).'@', '***@', $error);
1190 }
1191
1192 $authority = \substr($remainder, 0, \strcspn($remainder, '/?#'));
1193 $atPosition = \strrpos($authority, '@');
1194
1195 if ($atPosition === false || $atPosition === 0) {
1196 // A parseable proxy URL with '@' only past its authority, or with
1197 // an empty userinfo, carries no credentials to redact.
1198 return $error;
1199 }
1200
1201 $rawUserInfo = \substr($authority, 0, $atPosition);
1202
1203 // Redact with the same policy Psr7\Utils::redactUserInfo() applies to
1204 // request URIs, so the bundled psr7 version governs the redacted form.
1205 $redactedUserInfo = '***';
1206
1207 try {
1208 $proxyUri = new Uri($proxyForParsing);
1209 $redactedUserInfo = Psr7\Utils::redactUserInfo($proxyUri)->getUserInfo();
1210
1211 if ($redactedUserInfo === $proxyUri->getUserInfo()) {
1212 return $error;
1213 }
1214 } catch (\InvalidArgumentException $e) {
1215 // Unparseable as a URI: fall back to redacting the whole userinfo.
1216 }
1217
1218 return \str_replace($rawUserInfo.'@', $redactedUserInfo.'@', $error);
1219 }
1220
1221 /**
1222 * @param array<int|string, mixed> $conf
1223 */
1224 private static function forceFreshConnectionForAuthenticatedProxy(RequestInterface $request, array &$conf): void
1225 {
1226 $proxy = self::getEffectiveProxy($conf);
1227
1228 if ($proxy === null || !self::requiresFreshConnectionForAuthenticatedProxy($request, $proxy, $conf)) {
1229 return;
1230 }
1231
1232 $conf[\CURLOPT_FRESH_CONNECT] = true;
1233 $conf[\CURLOPT_FORBID_REUSE] = true;
1234 }
1235
1236 /**
1237 * @param array<int|string, mixed> $conf
1238 */
1239 private function isolateOpaqueShareAnonymousProxyTunnel(RequestInterface $request, array &$conf): void
1240 {
1241 if (!$this->opaqueShareConnectionCache || !CurlVersion::supportsShareConnectionCaches()) {
1242 return;
1243 }
1244
1245 $proxy = self::getEffectiveProxy($conf);
1246 if (
1247 $proxy === null
1248 || !self::usesProxyTunnel($request, $conf)
1249 || !self::isHttpProxyForConnectionReuse($proxy, $conf)
1250 || self::hasAuthenticatedHttpProxyState($proxy, $conf)
1251 ) {
1252 return;
1253 }
1254
1255 // From libcurl 7.57.0 an opaque share handle can own a connection
1256 // cache, and a tunnel seeded there with a literal Proxy-Authorization
1257 // header is never keyed on credentials, so an anonymous request could
1258 // inherit it on every later libcurl version. Requests carrying
1259 // recognized credential state keep the version-gated channel
1260 // safeguards above.
1261 $conf[\CURLOPT_FRESH_CONNECT] = true;
1262 $conf[\CURLOPT_FORBID_REUSE] = true;
1263 }
1264
1265 /**
1266 * @param array<int|string, mixed> $conf
1267 */
1268 private static function assertFinalProxyOptionTypes(array $conf, bool $requiredCleartextMultiplex): void
1269 {
1270 if (\array_key_exists(\CURLOPT_PROXYTYPE, $conf) && !\is_int($conf[\CURLOPT_PROXYTYPE])) {
1271 throw new \InvalidArgumentException('CURLOPT_PROXYTYPE must be an integer.');
1272 }
1273
1274 foreach (['CURLOPT_PROXY', 'CURLOPT_NOPROXY', 'CURLOPT_PRE_PROXY'] as $name) {
1275 if (!\defined($name)) {
1276 continue;
1277 }
1278
1279 $option = (int) \constant($name);
1280 if (\array_key_exists($option, $conf) && !\is_string($conf[$option])) {
1281 if ($requiredCleartextMultiplex) {
1282 throw new \InvalidArgumentException(\sprintf('The "multiplex" request option cannot be required when the final %s cURL option value is not a string.', $name));
1283 }
1284
1285 throw new \InvalidArgumentException($name.' must be a string.');
1286 }
1287 }
1288 }
1289
1290 /**
1291 * @param array<int|string, mixed> $conf
1292 */
1293 private static function isolatePreProxyOnAffectedCurl(array &$conf): void
1294 {
1295 if (CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse() || !\defined('CURLOPT_PRE_PROXY')) {
1296 return;
1297 }
1298
1299 $option = (int) \constant('CURLOPT_PRE_PROXY');
1300 if (!\array_key_exists($option, $conf) || $conf[$option] === '') {
1301 return;
1302 }
1303
1304 $conf[\CURLOPT_FRESH_CONNECT] = true;
1305 $conf[\CURLOPT_FORBID_REUSE] = true;
1306 }
1307
1308 /**
1309 * @param array<int|string, mixed> $conf
1310 */
1311 private static function getEffectiveProxy(array $conf): ?string
1312 {
1313 if (!\array_key_exists(\CURLOPT_PROXY, $conf)) {
1314 return null;
1315 }
1316
1317 $proxy = $conf[\CURLOPT_PROXY];
1318 if (!\is_string($proxy) || $proxy === '') {
1319 return null;
1320 }
1321
1322 // Only the exact raw wildcard is modeled here: libcurl treats '*' as
1323 // bypass-all by whole-string comparison, without trimming or host matching.
1324 if (\defined('CURLOPT_NOPROXY')) {
1325 $noProxy = $conf[(int) \constant('CURLOPT_NOPROXY')] ?? null;
1326 if (\is_string($noProxy) && $noProxy === '*') {
1327 return null;
1328 }
1329 }
1330
1331 return $proxy;
1332 }
1333
1334 /**
1335 * @param array<int|string, mixed> $conf
1336 */
1337 private static function normalizeCurlHeaderOptions(array &$conf): void
1338 {
1339 $options = [\CURLOPT_HTTPHEADER => 'CURLOPT_HTTPHEADER'];
1340 if (\defined('CURLOPT_PROXYHEADER')) {
1341 $options[(int) \constant('CURLOPT_PROXYHEADER')] = 'CURLOPT_PROXYHEADER';
1342 }
1343
1344 foreach ($options as $option => $label) {
1345 if (!\array_key_exists($option, $conf) || !\is_array($conf[$option])) {
1346 continue;
1347 }
1348
1349 $normalized = [];
1350 foreach ($conf[$option] as $key => $entry) {
1351 if (\is_object($entry) && \method_exists($entry, '__toString')) {
1352 $entry = (string) $entry;
1353 } elseif (\is_float($entry) && !\is_finite($entry)) {
1354 $entry = \is_nan($entry) ? 'NAN' : ($entry > 0 ? 'INF' : '-INF');
1355 } elseif (\is_scalar($entry)) {
1356 $entry = (string) $entry;
1357 } else {
1358 throw new \InvalidArgumentException(\sprintf('%s entries must be strings, stringable objects, or scalar values.', $label));
1359 }
1360
1361 if (\strpbrk($entry, "\r\n") !== false) {
1362 throw new \InvalidArgumentException(\sprintf('%s entries must not contain a carriage return or line feed.', $label));
1363 }
1364
1365 $normalized[$key] = $entry;
1366 }
1367
1368 $conf[$option] = $normalized;
1369 }
1370 }
1371
1372 private static function proxyScheme(string $proxy): ?string
1373 {
1374 $position = \strpos($proxy, '://');
1375
1376 return $position === false ? null : Psr7\Utils::asciiToLower(\substr($proxy, 0, $position));
1377 }
1378
1379 /**
1380 * @param array<int|string, mixed> $conf
1381 */
1382 private static function requiresFreshConnectionForAuthenticatedProxy(RequestInterface $request, string $proxy, array $conf): bool
1383 {
1384 // SOCKS authentication binds an identity to the connection itself, and
1385 // below 7.69.0 an opaque configured share may already contain a SOCKS
1386 // connection whose credential state Guzzle cannot inspect. Isolate
1387 // authenticated and anonymous requests so neither can inherit it.
1388 if (self::isSocksProxy($proxy, $conf)) {
1389 return !CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse();
1390 }
1391
1392 if (!self::usesProxyTunnel($request, $conf) || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
1393 return false;
1394 }
1395
1396 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
1397 $proxyParts = \parse_url($proxyForParsing);
1398
1399 if (!\is_array($proxyParts)) {
1400 return false;
1401 }
1402
1403 if (self::hasCurlProxyAuthorizationHeader($conf)) {
1404 return true;
1405 }
1406
1407 // A proxy client certificate or TLS-SRP authenticates the client to the
1408 // HTTPS proxy at the TLS layer; libcurl ignored TLS-SRP before 7.83.1
1409 // (CVE-2022-27782), so an old build can reuse a tunnel across those
1410 // identities. Force a fresh one, as the non-share signature path does.
1411 if (
1412 !CurlVersion::supportsProxyTlsCredentialAwareConnectionReuse()
1413 && self::hasCurlProxyTlsCredentials($conf)
1414 ) {
1415 return true;
1416 }
1417
1418 if (CurlVersion::supportsProxyCredentialAwareConnectionReuse()) {
1419 return false;
1420 }
1421
1422 return \array_key_exists('user', $proxyParts)
1423 || \array_key_exists('pass', $proxyParts)
1424 || self::hasCurlProxyCredentials($conf);
1425 }
1426
1427 /**
1428 * @param array<int|string, mixed> $conf
1429 */
1430 private static function hasAuthenticatedSocksProxyState(string $proxy, array $conf): bool
1431 {
1432 $proxyForParsing = \strpos($proxy, '://') === false ? 'http://'.$proxy : $proxy;
1433 $proxyParts = \parse_url($proxyForParsing);
1434
1435 if (
1436 \is_array($proxyParts)
1437 && (\array_key_exists('user', $proxyParts) || \array_key_exists('pass', $proxyParts))
1438 ) {
1439 return true;
1440 }
1441
1442 return self::hasCurlProxyCredentials($conf);
1443 }
1444
1445 /**
1446 * @param array<int|string, mixed> $conf
1447 */
1448 private static function usesProxyTunnel(RequestInterface $request, array $conf): bool
1449 {
1450 $scheme = $request->getUri()->getScheme();
1451
1452 if ('https' === $scheme) {
1453 return true;
1454 }
1455
1456 // An HTTP proxy auto-switches to a CONNECT tunnel when CONNECT_TO
1457 // redirects the origin, so an http:// target with it set tunnels too.
1458 if ('http' === $scheme && self::hasCurlConnectTo($conf)) {
1459 return true;
1460 }
1461
1462 return \defined('CURLOPT_HTTPPROXYTUNNEL')
1463 && \array_key_exists((int) \constant('CURLOPT_HTTPPROXYTUNNEL'), $conf)
1464 && (bool) $conf[(int) \constant('CURLOPT_HTTPPROXYTUNNEL')];
1465 }
1466
1467 /**
1468 * @param array<int|string, mixed> $conf
1469 */
1470 private static function hasCurlConnectTo(array $conf): bool
1471 {
1472 if (!\defined('CURLOPT_CONNECT_TO')) {
1473 return false;
1474 }
1475
1476 $option = (int) \constant('CURLOPT_CONNECT_TO');
1477 if (!\array_key_exists($option, $conf)) {
1478 return false;
1479 }
1480
1481 $value = $conf[$option];
1482
1483 return \is_array($value)
1484 ? $value !== []
1485 : $value !== null && $value !== false && $value !== '';
1486 }
1487
1488 /**
1489 * @param array<int|string, mixed> $conf
1490 */
1491 private static function isHttpProxyForConnectionReuse(string $proxy, array $conf): bool
1492 {
1493 if (\strpos($proxy, '://') !== false) {
1494 $proxyParts = \parse_url($proxy);
1495
1496 if (!\is_array($proxyParts) || !isset($proxyParts['scheme'])) {
1497 return false;
1498 }
1499
1500 $proxyScheme = Psr7\Utils::asciiToLower($proxyParts['scheme']);
1501
1502 return $proxyScheme === 'http' || $proxyScheme === 'https';
1503 }
1504
1505 return !self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null);
1506 }
1507
1508 /**
1509 * @param array<int|string, mixed> $conf
1510 */
1511 private static function isSocksProxy(string $proxy, array $conf): bool
1512 {
1513 $scheme = self::proxyScheme($proxy);
1514 if ($scheme !== null) {
1515 if (\in_array($scheme, ['socks', 'socks4', 'socks4a', 'socks5', 'socks5h'], true)) {
1516 return true;
1517 }
1518
1519 // libcurl preserves a raw SOCKS CURLOPT_PROXYTYPE behind an http
1520 // scheme, while every other scheme overrides the proxy type.
1521 if ($scheme !== 'http') {
1522 return false;
1523 }
1524 }
1525
1526 return self::isSocksProxyType($conf[\CURLOPT_PROXYTYPE] ?? null);
1527 }
1528
1529 /**
1530 * Computes the connection-reuse section signature for a SOCKS proxy.
1531 * libcurl compares SOCKS credentials on connection reuse from 7.69.0 (curl
1532 * #4835), so no sectioning is needed there. Older libcurl matches a SOCKS
1533 * proxy by type, host, and port only, so every SOCKS request is sectioned
1534 * by its credential state; hashing the credential-less state too keeps an
1535 * unauthenticated request from inheriting an authenticated connection.
1536 *
1537 * @param array<int|string, mixed> $conf
1538 */
1539 private static function socksProxySignature(string $proxy, array $conf): ?string
1540 {
1541 if (CurlVersion::supportsSocksProxyCredentialAwareConnectionReuse()) {
1542 return null;
1543 }
1544
1545 $credentialState = [];
1546 foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD', 'CURLOPT_PROXYTYPE'] as $name) {
1547 $credentialState[$name] = \defined($name)
1548 ? ($conf[(int) \constant($name)] ?? null)
1549 : null;
1550 }
1551
1552 return \hash('sha256', \serialize(['socks', $proxy, $credentialState]));
1553 }
1554
1555 /**
1556 * @param mixed $proxyType
1557 */
1558 private static function isSocksProxyType($proxyType): bool
1559 {
1560 if (!\is_int($proxyType)) {
1561 return false;
1562 }
1563
1564 foreach ([
1565 'CURLPROXY_SOCKS4' => 4,
1566 'CURLPROXY_SOCKS5' => 5,
1567 'CURLPROXY_SOCKS4A' => 6,
1568 'CURLPROXY_SOCKS5_HOSTNAME' => 7,
1569 ] as $name => $fallback) {
1570 $value = \defined($name) ? (int) \constant($name) : $fallback;
1571 if ($proxyType === $value) {
1572 return true;
1573 }
1574 }
1575
1576 return false;
1577 }
1578
1579 /**
1580 * @param array<int|string, mixed> $conf
1581 */
1582 private static function hasCurlProxyCredentials(array $conf): bool
1583 {
1584 foreach (['CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD'] as $option) {
1585 if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) {
1586 return true;
1587 }
1588 }
1589
1590 return false;
1591 }
1592
1593 /**
1594 * @param array<int|string, mixed> $conf
1595 */
1596 private static function hasCurlProxyTlsCredentials(array $conf): bool
1597 {
1598 foreach ([
1599 'CURLOPT_PROXY_SSLCERT',
1600 'CURLOPT_PROXY_SSLCERT_BLOB',
1601 'CURLOPT_PROXY_TLSAUTH_USERNAME',
1602 'CURLOPT_PROXY_TLSAUTH_PASSWORD',
1603 ] as $option) {
1604 if (\defined($option) && \array_key_exists((int) \constant($option), $conf)) {
1605 return true;
1606 }
1607 }
1608
1609 return false;
1610 }
1611
1612 /**
1613 * @param array<int|string, mixed> $conf
1614 */
1615 private static function hasCurlProxyAuthorizationHeader(array $conf): bool
1616 {
1617 return self::curlProxyAuthorizationHeaderValues($conf) !== [];
1618 }
1619
1620 /**
1621 * @param array<int|string, mixed> $conf
1622 */
1623 private static function applyProxyAuthorizationHeaderHandling(RequestInterface $request, array &$conf): void
1624 {
1625 $proxy = self::getEffectiveProxy($conf);
1626 if ($proxy === null || !self::isHttpProxyForConnectionReuse($proxy, $conf)) {
1627 return;
1628 }
1629
1630 $httpHeaders = $conf[\CURLOPT_HTTPHEADER] ?? null;
1631 $movedHeaders = [];
1632 $originHeaders = [];
1633
1634 if (\is_array($httpHeaders)) {
1635 foreach ($httpHeaders as $header) {
1636 if (\is_string($header) && self::isProxyAuthorizationHeaderLine($header)) {
1637 $movedHeaders[] = $header;
1638
1639 continue;
1640 }
1641
1642 $originHeaders[] = $header;
1643 }
1644 }
1645
1646 if (CurlVersion::supportsProxyHeaderSeparation()) {
1647 if ($movedHeaders !== []) {
1648 $conf[\CURLOPT_HTTPHEADER] = $originHeaders;
1649 self::appendCurlProxyHeaders($conf, $movedHeaders);
1650 }
1651
1652 // On libcurl 7.37.0-7.42.0 the default is CURLHEADER_UNIFIED.
1653 if ($movedHeaders !== [] || self::hasCurlProxyHeaderOption($conf) || self::usesProxyTunnel($request, $conf)) {
1654 $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE');
1655 }
1656
1657 return;
1658 }
1659
1660 if (\is_array($httpHeaders) && self::proxyAuthorizationHeaderValuesFromList($httpHeaders) !== []) {
1661 $conf[\CURLOPT_FRESH_CONNECT] = true;
1662 $conf[\CURLOPT_FORBID_REUSE] = true;
1663 }
1664 }
1665
1666 /**
1667 * Routes the managed first-class Proxy-Authorization values to libcurl's
1668 * proxy-only header channel, independently of Guzzle's proxy prediction:
1669 * libcurl alone decides whether the proxy-only list is used for the
1670 * actual transfer, so the credential can never reach an origin through
1671 * CURLOPT_HTTPHEADER. Without proxy header separation support, values are
1672 * safely omitted on known direct, bypassed, and SOCKS routes; a route that
1673 * may use an HTTP(S) proxy is rejected before cURL initialization and
1674 * network I/O. A deprecated raw CURLOPT_HTTPHEADER replacement suppresses
1675 * every generated header, the managed values included.
1676 *
1677 * @param array<int|string, mixed> $conf
1678 * @param list<string> $headers
1679 */
1680 private static function applyManagedProxyAuthorization(RequestInterface $request, array &$conf, array $headers, bool $rawHttpHeadersReplaceManaged): void
1681 {
1682 if ($rawHttpHeadersReplaceManaged || $headers === []) {
1683 return;
1684 }
1685
1686 if (!CurlVersion::supportsProxyHeaderSeparation()) {
1687 $proxy = self::getEffectiveProxy($conf);
1688 if ($proxy !== null && !self::isSocksProxy($proxy, $conf)) {
1689 throw new RequestException('Proxy-Authorization request headers through a possible HTTP or HTTPS proxy require libcurl 7.37.0 or newer built with proxy header separation support.', $request);
1690 }
1691
1692 return;
1693 }
1694
1695 self::appendCurlProxyHeaders($conf, $headers);
1696 $conf[(int) \constant('CURLOPT_HEADEROPT')] = (int) \constant('CURLHEADER_SEPARATE');
1697 }
1698
1699 /**
1700 * @return list<string>
1701 */
1702 private static function managedProxyAuthorizationHeaderLines(RequestInterface $request): array
1703 {
1704 $headers = [];
1705
1706 foreach ($request->getHeader('Proxy-Authorization') as $value) {
1707 $headers[] = $value === ''
1708 ? 'Proxy-Authorization;'
1709 : 'Proxy-Authorization: '.$value;
1710 }
1711
1712 return $headers;
1713 }
1714
1715 /**
1716 * @param array<int|string, mixed> $conf
1717 * @param list<string> $headers
1718 */
1719 private static function appendCurlProxyHeaders(array &$conf, array $headers): void
1720 {
1721 $option = (int) \constant('CURLOPT_PROXYHEADER');
1722
1723 if (\array_key_exists($option, $conf)) {
1724 if (!\is_array($conf[$option])) {
1725 throw new \InvalidArgumentException('CURLOPT_PROXYHEADER must be an array when a Proxy-Authorization request header is routed to the proxy header channel.');
1726 }
1727
1728 $headers = \array_merge($conf[$option], $headers);
1729 }
1730
1731 $conf[$option] = $headers;
1732 }
1733
1734 /**
1735 * @param array<int|string, mixed> $conf
1736 */
1737 private static function hasCurlProxyHeaderOption(array $conf): bool
1738 {
1739 return \defined('CURLOPT_PROXYHEADER')
1740 && \array_key_exists((int) \constant('CURLOPT_PROXYHEADER'), $conf);
1741 }
1742
1743 private static function isProxyAuthorizationHeaderLine(string $header): bool
1744 {
1745 $length = \strcspn($header, ':;');
1746
1747 if ($length === \strlen($header)) {
1748 return false;
1749 }
1750
1751 return Psr7\Utils::caselessEquals(\trim(\substr($header, 0, $length), " \n\r\t\0\x0B"), 'Proxy-Authorization');
1752 }
1753
1754 private static function proxyAuthorizationHeaderValue(string $header): ?string
1755 {
1756 $position = \strpos($header, ':');
1757 if ($position === false) {
1758 return null;
1759 }
1760
1761 if (!Psr7\Utils::caselessEquals(\trim(\substr($header, 0, $position), " \n\r\t\0\x0B"), 'Proxy-Authorization')) {
1762 return null;
1763 }
1764
1765 $value = \trim(\substr($header, $position + 1), " \n\r\t\0\x0B");
1766
1767 return $value === '' ? null : $value;
1768 }
1769
1770 /**
1771 * @param mixed[] $headers
1772 *
1773 * @return list<string>
1774 */
1775 private static function proxyAuthorizationHeaderValuesFromList(array $headers): array
1776 {
1777 $values = [];
1778
1779 foreach ($headers as $header) {
1780 if (!\is_string($header)) {
1781 continue;
1782 }
1783
1784 $value = self::proxyAuthorizationHeaderValue($header);
1785 if ($value !== null) {
1786 $values[] = $value;
1787 }
1788 }
1789
1790 return $values;
1791 }
1792
1793 /**
1794 * Computes the connection-reuse section signature for a proxy tunnel or
1795 * SOCKS proxy, or null when the request does not require sectioning.
1796 *
1797 * @param array<int|string, mixed> $conf
1798 */
1799 private static function proxyTunnelSignature(RequestInterface $request, array $conf): ?string
1800 {
1801 $proxy = self::getEffectiveProxy($conf);
1802 if ($proxy === null) {
1803 return null;
1804 }
1805
1806 // SOCKS authentication binds an identity to the connection itself, for
1807 // plain http:// requests as much as https://, so it sections ahead of
1808 // the CONNECT tunnel domain checks.
1809 if (self::isSocksProxy($proxy, $conf)) {
1810 return self::socksProxySignature($proxy, $conf);
1811 }
1812
1813 if (
1814 !self::usesProxyTunnel($request, $conf)
1815 || !self::isHttpProxyForConnectionReuse($proxy, $conf)
1816 ) {
1817 return null;
1818 }
1819
1820 $headerAuth = self::curlProxyAuthorizationHeaderValues($conf);
1821 if ($headerAuth === [] && CurlVersion::supportsProxyCredentialAwareConnectionReuse()) {
1822 // libcurl keys reuse on parsed proxy credentials only from 8.19.0,
1823 // trusted from 8.20.0 (PROXY_CREDENTIAL_REUSE_VERSION); a literal
1824 // Proxy-Authorization header is never keyed and always sections.
1825 return self::DELEGATED_PROXY_TUNNEL_OWNER;
1826 }
1827
1828 // Hash every proxy channel an old libcurl might not key reuse on. A
1829 // changed signature only forces a fresh connection, never relaxes
1830 // reuse, so over-covering is always safe; under-covering leaks. Proxy
1831 // credentials are the channel CVE-2026-3784 missed; the proxy-TLS
1832 // options are load-bearing on builds before the proxy-TLS reuse fixes
1833 // (the proxy client cert is keyed from 7.52.0, libcurl's first
1834 // HTTPS-proxy release; CVE-2016-5420 (7.50.1) is only the origin-cert
1835 // precedent; TLS-SRP from 7.83.1, CVE-2022-27782) and harmless after.
1836 // The private-key file and passphrase are hashed on this non-delegated
1837 // path too, as fallback hardening: libcurl's mTLS private-key matching
1838 // on reuse was incomplete before 8.21.0 (CVE-2026-8932). This does not
1839 // cover the delegated path (the early return above) or configured share
1840 // handles, so it is not a complete pre-8.21.0 mitigation. The key blob
1841 // and cert/key type encodings (PROXY_SSLKEY_BLOB, PROXY_SSLKEYTYPE,
1842 // PROXY_SSLCERTTYPE) are not hashed and are an accepted residual.
1843 $credentialState = [];
1844 foreach ([
1845 'CURLOPT_PROXYUSERPWD', 'CURLOPT_PROXYUSERNAME', 'CURLOPT_PROXYPASSWORD',
1846 'CURLOPT_PROXYTYPE',
1847 'CURLOPT_PROXY_SSLCERT', 'CURLOPT_PROXY_SSLCERT_BLOB', 'CURLOPT_PROXY_SSLKEY',
1848 'CURLOPT_PROXY_KEYPASSWD', 'CURLOPT_PROXY_TLSAUTH_USERNAME',
1849 'CURLOPT_PROXY_TLSAUTH_PASSWORD', 'CURLOPT_PROXY_SSLVERSION',
1850 ] as $name) {
1851 $credentialState[$name] = \defined($name)
1852 ? ($conf[(int) \constant($name)] ?? null)
1853 : null;
1854 }
1855
1856 return \hash('sha256', \serialize([$proxy, $credentialState, $headerAuth]));
1857 }
1858
1859 /**
1860 * @param array<int|string, mixed> $conf
1861 *
1862 * @return list<string>
1863 */
1864 private static function curlProxyAuthorizationHeaderValues(array $conf): array
1865 {
1866 if (!\defined('CURLOPT_PROXYHEADER')) {
1867 return [];
1868 }
1869
1870 $option = (int) \constant('CURLOPT_PROXYHEADER');
1871 if (!\array_key_exists($option, $conf)) {
1872 return [];
1873 }
1874
1875 $headers = $conf[$option];
1876 if (!\is_array($headers)) {
1877 return [];
1878 }
1879
1880 return self::proxyAuthorizationHeaderValuesFromList($headers);
1881 }
1882
1883 private function discardIdleHandles(): void
1884 {
1885 foreach ($this->handles as $id => $handle) {
1886 if (PHP_VERSION_ID < 80000) {
1887 \curl_close($handle);
1888 }
1889
1890 unset($this->handles[$id]);
1891 }
1892 }
1893
1894 /**
1895 * @return array<int|string, mixed>
1896 */
1897 private function getDefaultConf(EasyHandle $easy): array
1898 {
1899 $uri = $easy->request->getUri();
1900 $protocols = Utils::normalizeProtocols($easy->options['protocols'] ?? ['http', 'https']);
1901 $scheme = $uri->getScheme();
1902 if (!\in_array($scheme, $protocols, true)) {
1903 throw new RequestException(\sprintf('The scheme "%s" is not allowed by the protocols request option.', $scheme), $easy->request);
1904 }
1905
1906 if ($uri->getHost() === '') {
1907 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);
1908 }
1909
1910 $conf = [
1911 '_headers' => $easy->request->getHeaders(),
1912 \CURLOPT_CUSTOMREQUEST => $easy->request->getMethod(),
1913 \CURLOPT_URL => (string) $uri->withFragment(''),
1914 \CURLOPT_RETURNTRANSFER => false,
1915 \CURLOPT_HEADER => false,
1916 \CURLOPT_CONNECTTIMEOUT => 300,
1917 ];
1918
1919 if (\defined('CURLOPT_PROTOCOLS')) {
1920 $conf[\CURLOPT_PROTOCOLS] = self::curlProtocolMask($protocols);
1921 }
1922
1923 $version = $easy->request->getProtocolVersion();
1924 $multiplex = self::normalizeMultiplex($easy->options);
1925
1926 if ('2' === $version || '2.0' === $version) {
1927 if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
1928 self::assertRequiredMultiplexSupported($easy);
1929 // New HTTP/2 connections cannot negotiate HTTP/1.x here, and
1930 // the 8.14.0 floor's version-aware reuse matching keeps
1931 // reused connections on HTTP/2 as well.
1932 $conf[\CURLOPT_HTTP_VERSION] = (int) \constant('CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE');
1933 } else {
1934 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_2_0;
1935 }
1936
1937 if (\in_array($multiplex, [Multiplexing::WAIT, Multiplexing::REQUIRE_WAIT], true) && CurlVersion::supportsMultiplex()) {
1938 // Wait for a connection that is still being established to the
1939 // same origin to reveal whether it can be multiplexed instead
1940 // of immediately opening another connection.
1941 $conf[(int) \constant('CURLOPT_PIPEWAIT')] = true;
1942 }
1943 } elseif ('1.1' === $version) {
1944 if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
1945 throw new ConnectException(\sprintf('The "multiplex" request option cannot be required for HTTP/%s requests; use protocol version 2.', $version), $easy->request);
1946 }
1947 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_1;
1948 } else {
1949 if (\in_array($multiplex, [Multiplexing::REQUIRE_EAGER, Multiplexing::REQUIRE_WAIT], true)) {
1950 throw new ConnectException(\sprintf('The "multiplex" request option cannot be required for HTTP/%s requests; use protocol version 2.', $version), $easy->request);
1951 }
1952 $conf[\CURLOPT_HTTP_VERSION] = \CURL_HTTP_VERSION_1_0;
1953 }
1954
1955 return $conf;
1956 }
1957
1958 /**
1959 * @param string[] $protocols
1960 */
1961 private static function curlProtocolMask(array $protocols): int
1962 {
1963 $mask = 0;
1964
1965 if (\in_array('http', $protocols, true)) {
1966 $mask |= \CURLPROTO_HTTP;
1967 }
1968
1969 if (\in_array('https', $protocols, true)) {
1970 $mask |= \CURLPROTO_HTTPS;
1971 }
1972
1973 return $mask;
1974 }
1975
1976 /**
1977 * @param mixed $type
1978 */
1979 private static function normalizeTlsFileType(string $option, $type): string
1980 {
1981 if (!\is_string($type) || $type === '') {
1982 throw new \InvalidArgumentException(\sprintf('%s must be a non-empty string', $option));
1983 }
1984
1985 return Psr7\Utils::asciiToUpper($type);
1986 }
1987
1988 private static function shouldValidateSslKeyFile(?string $type): bool
1989 {
1990 return $type !== 'ENG' && $type !== 'PROV';
1991 }
1992
1993 private function applyMethod(EasyHandle $easy, array &$conf): void
1994 {
1995 if ($easy->request->getMethod() === 'HEAD') {
1996 // libcurl stops at HEAD response headers only when CURLOPT_NOBODY
1997 // is set; CURLOPT_CUSTOMREQUEST changes only the method string.
1998 // NOBODY also suppresses request upload, so strip non-zero body
1999 // length, transfer coding, and a 100-continue expectation.
2000 $conf[\CURLOPT_CUSTOMREQUEST] = null;
2001 $conf[\CURLOPT_NOBODY] = true;
2002 unset(
2003 $conf[\CURLOPT_WRITEFUNCTION],
2004 $conf[\CURLOPT_READFUNCTION],
2005 $conf[\CURLOPT_FILE],
2006 $conf[\CURLOPT_INFILE]
2007 );
2008 if (\trim($easy->request->getHeaderLine('Content-Length'), " \n\r\t\0\x0B") !== '0') {
2009 $this->removeHeader('Content-Length', $conf);
2010 }
2011 $this->removeHeader('Transfer-Encoding', $conf);
2012 if (Psr7\Utils::caselessEquals(\trim($easy->request->getHeaderLine('Expect'), " \n\r\t\0\x0B"), '100-continue')) {
2013 $this->removeHeader('Expect', $conf);
2014 }
2015
2016 return;
2017 }
2018
2019 $body = $easy->request->getBody();
2020 $size = $body->getSize();
2021
2022 if ($size === null || $size > 0) {
2023 $this->applyBody($easy->request, $easy->options, $conf);
2024
2025 return;
2026 }
2027
2028 $method = $easy->request->getMethod();
2029 if ($method === 'PUT' || $method === 'POST') {
2030 // See https://datatracker.ietf.org/doc/html/rfc7230#section-3.3.2
2031 if (!$easy->request->hasHeader('Content-Length')) {
2032 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
2033 }
2034 }
2035 }
2036
2037 private function applyBody(RequestInterface $request, array $options, array &$conf): void
2038 {
2039 $size = $request->hasHeader('Content-Length')
2040 ? (int) $request->getHeaderLine('Content-Length')
2041 : null;
2042
2043 // Send the body as a string if the size is less than 1MB OR if the
2044 // [curl][body_as_string] request value is set.
2045 if (($size !== null && $size < 1000000) || !empty($options['_body_as_string'])) {
2046 $conf[\CURLOPT_POSTFIELDS] = (string) $request->getBody();
2047 // Don't duplicate the Content-Length header
2048 $this->removeHeader('Content-Length', $conf);
2049 $this->removeHeader('Transfer-Encoding', $conf);
2050 } else {
2051 $conf[\CURLOPT_UPLOAD] = true;
2052 if ($size !== null) {
2053 $conf[\CURLOPT_INFILESIZE] = $size;
2054 $this->removeHeader('Content-Length', $conf);
2055 }
2056 $body = $request->getBody();
2057 if ($body->isSeekable()) {
2058 $body->rewind();
2059 }
2060 $remaining = $size;
2061 $conf[\CURLOPT_READFUNCTION] = static function ($ch, $fd, $length) use ($body, &$remaining) {
2062 if ($remaining === 0) {
2063 return '';
2064 }
2065
2066 $limit = $remaining === null ? $length : \min($length, $remaining);
2067 $data = $body->read($limit);
2068 if ($remaining !== null) {
2069 $remaining -= \strlen($data);
2070 }
2071
2072 return $data;
2073 };
2074 }
2075
2076 // If the Expect header is not present, prevent curl from adding it
2077 if (!$request->hasHeader('Expect')) {
2078 $conf[\CURLOPT_HTTPHEADER][] = 'Expect:';
2079 }
2080
2081 // cURL sometimes adds a content-type by default. Prevent this.
2082 if (!$request->hasHeader('Content-Type')) {
2083 $conf[\CURLOPT_HTTPHEADER][] = 'Content-Type:';
2084 }
2085 }
2086
2087 private function applyHeaders(EasyHandle $easy, array &$conf): void
2088 {
2089 foreach ($conf['_headers'] as $name => $values) {
2090 // A first-class Proxy-Authorization header is proxy-scoped and
2091 // must never be generated in the origin header list; managed
2092 // handling routes it to CURLOPT_PROXYHEADER or safely omits it on
2093 // a legacy non-HTTP-proxy route. The
2094 // caselessEquals() helper is locale-independent, unlike
2095 // strcasecmp(), so a locale cannot make this match miss and
2096 // re-leak the credential.
2097 if (Psr7\Utils::caselessEquals((string) $name, 'Proxy-Authorization')) {
2098 continue;
2099 }
2100
2101 foreach ($values as $value) {
2102 $value = (string) $value;
2103 if ($value === '') {
2104 // cURL requires a special format for empty headers.
2105 // See https://github.com/guzzle/guzzle/issues/1882 for more details.
2106 $conf[\CURLOPT_HTTPHEADER][] = "$name;";
2107 } else {
2108 $conf[\CURLOPT_HTTPHEADER][] = "$name: $value";
2109 }
2110 }
2111 }
2112
2113 // Remove the Accept header if one was not set
2114 if (!$easy->request->hasHeader('Accept')) {
2115 $conf[\CURLOPT_HTTPHEADER][] = 'Accept:';
2116 }
2117 }
2118
2119 /**
2120 * Remove a header from the options array.
2121 *
2122 * @param string $name Case-insensitive header to remove
2123 * @param array $options Array of options to modify
2124 */
2125 private function removeHeader(string $name, array &$options): void
2126 {
2127 foreach (\array_keys($options['_headers']) as $key) {
2128 if (Psr7\Utils::caselessEquals((string) $key, $name)) {
2129 unset($options['_headers'][$key]);
2130
2131 return;
2132 }
2133 }
2134 }
2135
2136 private function applyHandlerOptions(EasyHandle $easy, array &$conf): void
2137 {
2138 $options = $easy->options;
2139 if (isset($options['verify'])) {
2140 if ($options['verify'] === false) {
2141 unset($conf[\CURLOPT_CAINFO]);
2142 $conf[\CURLOPT_SSL_VERIFYHOST] = 0;
2143 $conf[\CURLOPT_SSL_VERIFYPEER] = false;
2144 } else {
2145 $conf[\CURLOPT_SSL_VERIFYHOST] = 2;
2146 $conf[\CURLOPT_SSL_VERIFYPEER] = true;
2147 if (\is_string($options['verify'])) {
2148 // Throw an error if the file/folder/link path is not valid or doesn't exist.
2149 if (!\file_exists($options['verify'])) {
2150 throw new \InvalidArgumentException("SSL CA bundle not found: {$options['verify']}");
2151 }
2152 // If it's a directory or a link to a directory use CURLOPT_CAPATH.
2153 // If not, it's probably a file, or a link to a file, so use CURLOPT_CAINFO.
2154 if (
2155 \is_dir($options['verify'])
2156 || (
2157 \is_link($options['verify']) === true
2158 && ($verifyLink = \readlink($options['verify'])) !== false
2159 && \is_dir($verifyLink)
2160 )
2161 ) {
2162 $conf[\CURLOPT_CAPATH] = $options['verify'];
2163 } else {
2164 $conf[\CURLOPT_CAINFO] = $options['verify'];
2165 }
2166 }
2167 }
2168 }
2169
2170 if (!isset($options['curl'][\CURLOPT_ENCODING]) && isset($options['decode_content']) && $options['decode_content'] !== false) {
2171 $accept = $easy->request->getHeaderLine('Accept-Encoding');
2172 if ($accept !== '') {
2173 $conf[\CURLOPT_ENCODING] = $accept;
2174 } else {
2175 // The empty string enables all available decoders and implicitly
2176 // sets a matching 'Accept-Encoding' header.
2177 $conf[\CURLOPT_ENCODING] = '';
2178 // But as the user did not specify any encoding preference,
2179 // let's leave it up to server by preventing curl from sending
2180 // the header, which will be interpreted as 'Accept-Encoding: *'.
2181 // https://www.rfc-editor.org/rfc/rfc9110#field.accept-encoding
2182 $conf[\CURLOPT_HTTPHEADER][] = 'Accept-Encoding:';
2183 }
2184 }
2185
2186 if (!isset($options['sink'])) {
2187 // Use a default temp stream if no sink was set.
2188 $options['sink'] = Psr7\Utils::tryFopen('php://temp', 'w+');
2189 }
2190 $sink = $options['sink'];
2191 if (!\is_string($sink)) {
2192 $sink = Psr7\Utils::streamFor($sink);
2193 } elseif (!\is_dir(\dirname($sink))) {
2194 // Ensure that the directory exists before failing in curl.
2195 throw new \RuntimeException(\sprintf('Directory %s does not exist for sink value of %s', \dirname($sink), $sink));
2196 } else {
2197 $sink = new LazyOpenStream($sink, 'w+');
2198 }
2199 $easy->sink = $sink;
2200 $conf[\CURLOPT_WRITEFUNCTION] = static function ($ch, $write) use ($sink): int {
2201 return $sink->write($write);
2202 };
2203
2204 $timeoutRequiresNoSignal = false;
2205 if (isset($options['timeout'])) {
2206 $timeoutRequiresNoSignal |= $options['timeout'] < 1;
2207 $conf[\CURLOPT_TIMEOUT_MS] = $options['timeout'] * 1000;
2208 }
2209
2210 // CURL default value is CURL_IPRESOLVE_WHATEVER
2211 if (isset($options['force_ip_resolve'])) {
2212 if ('v4' === $options['force_ip_resolve']) {
2213 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V4;
2214 } elseif ('v6' === $options['force_ip_resolve']) {
2215 $conf[\CURLOPT_IPRESOLVE] = \CURL_IPRESOLVE_V6;
2216 }
2217 }
2218
2219 if (isset($options['connect_timeout'])) {
2220 $timeoutRequiresNoSignal |= $options['connect_timeout'] < 1;
2221 $conf[\CURLOPT_CONNECTTIMEOUT_MS] = $options['connect_timeout'] * 1000;
2222 }
2223
2224 if ($timeoutRequiresNoSignal && Psr7\Utils::asciiToUpper(\substr(\PHP_OS, 0, 3)) !== 'WIN') {
2225 $conf[\CURLOPT_NOSIGNAL] = true;
2226 }
2227
2228 // Always pin CURLOPT_PROXY (and CURLOPT_NOPROXY when available) so
2229 // that libcurl never falls back to reading proxy environment
2230 // variables itself. When the proxy request option makes no decision,
2231 // the environment is resolved here with libcurl's own semantics.
2232 [$proxyConf, $noProxyConf] = self::resolveProxy($easy->request, $options);
2233 self::assertResolvedProxySupported($easy->request, $proxyConf);
2234
2235 $conf[\CURLOPT_PROXY] = $proxyConf;
2236 if (\defined('CURLOPT_NOPROXY')) {
2237 $conf[(int) \constant('CURLOPT_NOPROXY')] = $noProxyConf;
2238 }
2239
2240 $this->applyTlsVersionRange($easy, $conf);
2241
2242 $certType = null;
2243 if (isset($options['cert_type'])) {
2244 $certType = self::normalizeTlsFileType('cert_type', $options['cert_type']);
2245 $conf[\CURLOPT_SSLCERTTYPE] = $certType;
2246 }
2247
2248 if (isset($options['cert'])) {
2249 $cert = $options['cert'];
2250 if (\is_array($cert)) {
2251 if (!isset($cert[0]) || !\is_string($cert[0])) {
2252 throw new \InvalidArgumentException('Invalid cert request option');
2253 }
2254 if (isset($cert[1])) {
2255 if (!\is_string($cert[1])) {
2256 throw new \InvalidArgumentException('Invalid cert request option');
2257 }
2258 $conf[\CURLOPT_SSLCERTPASSWD] = $cert[1];
2259 }
2260 $cert = $cert[0];
2261 }
2262 if (!\is_string($cert)) {
2263 throw new \InvalidArgumentException('Invalid cert request option');
2264 }
2265 if (!\file_exists($cert)) {
2266 throw new \InvalidArgumentException("SSL certificate not found: {$cert}");
2267 }
2268 // OpenSSL (versions 0.9.3 and later) also support "P12" for PKCS#12-encoded files.
2269 // see https://curl.se/libcurl/c/CURLOPT_SSLCERTTYPE.html
2270 $ext = pathinfo($cert, \PATHINFO_EXTENSION);
2271 if ($certType === null && preg_match('#^(der|p12)$#iD', $ext)) {
2272 $conf[\CURLOPT_SSLCERTTYPE] = Psr7\Utils::asciiToUpper($ext);
2273 }
2274 $conf[\CURLOPT_SSLCERT] = $cert;
2275 }
2276
2277 $sslKeyType = null;
2278 if (isset($options['ssl_key_type'])) {
2279 $sslKeyType = self::normalizeTlsFileType('ssl_key_type', $options['ssl_key_type']);
2280 $conf[\CURLOPT_SSLKEYTYPE] = $sslKeyType;
2281 }
2282
2283 if (isset($options['ssl_key'])) {
2284 if (\is_array($options['ssl_key'])) {
2285 if (!isset($options['ssl_key'][0]) || !\is_string($options['ssl_key'][0])) {
2286 throw new \InvalidArgumentException('Invalid ssl_key request option');
2287 }
2288 if (isset($options['ssl_key'][1])) {
2289 if (!\is_string($options['ssl_key'][1])) {
2290 throw new \InvalidArgumentException('Invalid ssl_key request option');
2291 }
2292 $conf[\CURLOPT_SSLKEYPASSWD] = $options['ssl_key'][1];
2293 }
2294 $sslKey = $options['ssl_key'][0];
2295 }
2296
2297 $sslKey = $sslKey ?? $options['ssl_key'];
2298
2299 if (!\is_string($sslKey)) {
2300 throw new \InvalidArgumentException('Invalid ssl_key request option');
2301 }
2302
2303 if (self::shouldValidateSslKeyFile($sslKeyType) && !\file_exists($sslKey)) {
2304 throw new \InvalidArgumentException("SSL private key not found: {$sslKey}");
2305 }
2306 $conf[\CURLOPT_SSLKEY] = $sslKey;
2307 }
2308
2309 if (isset($options['progress'])) {
2310 $progress = $options['progress'];
2311 if (!\is_callable($progress)) {
2312 throw new \InvalidArgumentException('progress client option must be callable');
2313 }
2314 $conf[\CURLOPT_NOPROGRESS] = false;
2315 $conf[\CURLOPT_PROGRESSFUNCTION] = static function ($resource, int $downloadSize, int $downloaded, int $uploadSize, int $uploaded) use ($progress) {
2316 $progress($downloadSize, $downloaded, $uploadSize, $uploaded);
2317 };
2318 }
2319
2320 if (!empty($options['debug'])) {
2321 $conf[\CURLOPT_STDERR] = Utils::debugResource($options['debug']);
2322 $conf[\CURLOPT_VERBOSE] = true;
2323 }
2324 }
2325
2326 private function applyTlsVersionRange(EasyHandle $easy, array &$conf): void
2327 {
2328 $options = $easy->options;
2329 $cryptoMethod = $options['crypto_method'] ?? null;
2330 $cryptoMethodMax = $options['crypto_method_max'] ?? null;
2331
2332 if ($cryptoMethod === null && $cryptoMethodMax === null) {
2333 return;
2334 }
2335
2336 $protocolVersion = $easy->request->getProtocolVersion();
2337 $isHttp2 = '2' === $protocolVersion || '2.0' === $protocolVersion;
2338
2339 if ($isHttp2 && $cryptoMethodMax !== null && TlsVersion::ordinal('crypto_method_max', $cryptoMethodMax) < 12) {
2340 throw new \InvalidArgumentException(
2341 'Invalid crypto_method_max request option: HTTP/2 requires TLS 1.2 or higher'
2342 );
2343 }
2344
2345 if ($isHttp2 && $cryptoMethod !== null && TlsVersion::ordinal('crypto_method', $cryptoMethod) < 12) {
2346 $cryptoMethod = \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
2347 }
2348
2349 TlsVersion::assertRange($cryptoMethod, $cryptoMethodMax);
2350
2351 $sslVersion = $cryptoMethod === null
2352 ? \CURL_SSLVERSION_DEFAULT
2353 : self::curlMinSslVersion($cryptoMethod);
2354
2355 if ($cryptoMethodMax !== null) {
2356 $sslVersion |= self::curlMaxSslVersion($cryptoMethodMax);
2357 }
2358
2359 $conf[\CURLOPT_SSLVERSION] = $sslVersion;
2360 }
2361
2362 /**
2363 * @param mixed $value
2364 */
2365 private static function curlMinSslVersion($value): int
2366 {
2367 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
2368 return \CURL_SSLVERSION_TLSv1_0;
2369 }
2370
2371 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
2372 return \CURL_SSLVERSION_TLSv1_1;
2373 }
2374
2375 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
2376 if (!CurlVersion::supportsTls12()) {
2377 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.2 not supported by your version of cURL');
2378 }
2379
2380 return \CURL_SSLVERSION_TLSv1_2;
2381 }
2382
2383 if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
2384 if (!CurlVersion::supportsTls13()) {
2385 throw new \InvalidArgumentException('Invalid crypto_method request option: TLS 1.3 not supported by your version of cURL');
2386 }
2387
2388 return \CURL_SSLVERSION_TLSv1_3;
2389 }
2390
2391 throw new \InvalidArgumentException('Invalid crypto_method request option: unknown version provided');
2392 }
2393
2394 /**
2395 * @param mixed $value
2396 */
2397 private static function curlMaxSslVersion($value): int
2398 {
2399 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT) {
2400 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_0');
2401 }
2402
2403 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT) {
2404 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_1');
2405 }
2406
2407 if ($value === \STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT) {
2408 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_2');
2409 }
2410
2411 if (\defined('STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT') && $value === \STREAM_CRYPTO_METHOD_TLSv1_3_CLIENT) {
2412 return self::requireCurlMaxSslVersion('CURL_SSLVERSION_MAX_TLSv1_3');
2413 }
2414
2415 throw new \InvalidArgumentException('Invalid crypto_method_max request option: unknown version provided');
2416 }
2417
2418 private static function requireCurlMaxSslVersion(string $constant): int
2419 {
2420 if (\defined($constant)) {
2421 /** @var int */
2422 return \constant($constant);
2423 }
2424
2425 throw new \InvalidArgumentException(
2426 'Invalid crypto_method_max request option: maximum TLS version control is not supported by your version of cURL'
2427 );
2428 }
2429
2430 private static function validateRequestUriScheme(RequestInterface $request): void
2431 {
2432 $scheme = $request->getUri()->getScheme();
2433 if ($scheme === '') {
2434 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);
2435 }
2436
2437 if (!\in_array($scheme, ['http', 'https'], true)) {
2438 throw new RequestException(\sprintf("The scheme '%s' is not supported.", $scheme), $request);
2439 }
2440 }
2441
2442 /**
2443 * This function ensures that a response was set on a transaction. If one
2444 * was not set, then the request is retried if possible. This error
2445 * typically means you are sending a payload, curl encountered a
2446 * "Connection died, retrying a fresh connect" error, tried to rewind the
2447 * stream, and then encountered a "necessary data rewind wasn't possible"
2448 * error, causing the request to be sent through curl_multi_info_read()
2449 * without an error status.
2450 *
2451 * @param callable(RequestInterface, array): PromiseInterface $handler
2452 */
2453 private static function retryFailedRewind(callable $handler, EasyHandle $easy, array $ctx): PromiseInterface
2454 {
2455 try {
2456 // Only rewind if the body has been read from.
2457 $body = $easy->request->getBody();
2458 if ($body->tell() > 0) {
2459 $body->rewind();
2460 }
2461 } catch (\RuntimeException $e) {
2462 $ctx['error'] = 'The connection unexpectedly failed without '
2463 .'providing an error. The request would have been retried, '
2464 .'but attempting to rewind the request body failed. '
2465 .'Exception: '.$e;
2466
2467 return self::createRejection($easy, $ctx);
2468 }
2469
2470 // Retry no more than 3 times before giving up.
2471 if (!isset($easy->options['_curl_retries'])) {
2472 $easy->options['_curl_retries'] = 1;
2473 } elseif ($easy->options['_curl_retries'] == 2) {
2474 $ctx['error'] = 'The cURL request was retried 3 times '
2475 .'and did not succeed. The most likely reason for the failure '
2476 .'is that cURL was unable to rewind the body of the request '
2477 .'and subsequent retries resulted in the same error. Turn on '
2478 .'the debug option to see what went wrong. See '
2479 .'https://bugs.php.net/bug.php?id=47204 for more information.';
2480
2481 return self::createRejection($easy, $ctx);
2482 } else {
2483 ++$easy->options['_curl_retries'];
2484 }
2485
2486 return $handler($easy->request, $easy->options);
2487 }
2488
2489 /**
2490 * Parses validated trailer field lines into an associative array keyed by
2491 * lowercased field name, preserving first-occurrence key order and wire
2492 * value order.
2493 */
2494 private static function headersFromTrailerLines(array $lines): array
2495 {
2496 $headers = [];
2497
2498 foreach ($lines as $line) {
2499 [$name, $value] = \explode(':', $line, 2);
2500 $name = Psr7\Utils::asciiToLower(\trim($name, " \n\r\t\0\x0B"));
2501 $headers[$name][] = \trim($value, " \n\r\t\0\x0B");
2502 }
2503
2504 return $headers;
2505 }
2506
2507 private function createHeaderFn(EasyHandle $easy): callable
2508 {
2509 if (isset($easy->options['on_headers'])) {
2510 $onHeaders = $easy->options['on_headers'];
2511
2512 if (!\is_callable($onHeaders)) {
2513 throw new \InvalidArgumentException('on_headers must be callable');
2514 }
2515 } else {
2516 $onHeaders = null;
2517 }
2518
2519 $startingResponse = false;
2520 $collectingTrailers = false;
2521 $retainTrailers = isset($easy->options['on_trailers']);
2522
2523 return static function ($ch, $h) use (
2524 $onHeaders,
2525 $easy,
2526 &$startingResponse,
2527 &$collectingTrailers,
2528 $retainTrailers
2529 ) {
2530 $value = \trim($h, " \n\r\t\0\x0B");
2531 if ($h === "\r\n" || $h === "\n" || $h === "\r" || $h === '') {
2532 if ($collectingTrailers) {
2533 // A blank line ends the trailer section; the response has
2534 // already been created.
2535 return \strlen($h);
2536 }
2537 $startingResponse = true;
2538 try {
2539 $easy->createResponse();
2540 } catch (\Throwable $e) {
2541 $easy->response = null;
2542 $easy->createResponseException = $e;
2543
2544 return -1;
2545 }
2546 if ($onHeaders !== null) {
2547 try {
2548 $onHeaders($easy->response);
2549 } catch (\Throwable $e) {
2550 // Associate the exception with the handle and trigger
2551 // a curl header write error by returning 0.
2552 $easy->onHeadersException = $e;
2553
2554 return -1;
2555 }
2556 }
2557 } elseif ($startingResponse || $collectingTrailers) {
2558 if ($easy->response !== null && !HeaderProcessor::isStatusLineCandidate($h)) {
2559 // Trailer fields arrive through the header callback after
2560 // the body; a new header block always begins with a status
2561 // line.
2562 $collectingTrailers = true;
2563
2564 if ($retainTrailers && HeaderProcessor::isValidHeaderFieldLine($h)) {
2565 $easy->trailers[] = $value;
2566 }
2567 } else {
2568 $collectingTrailers = false;
2569 $easy->trailers = [];
2570 $easy->headers = [$value];
2571 }
2572 $startingResponse = false;
2573 } else {
2574 $easy->headers[] = $value;
2575 }
2576
2577 return \strlen($h);
2578 };
2579 }
2580
2581 public function __destruct()
2582 {
2583 $this->discardIdleHandles();
2584 }
2585}